source: src/tesselation.cpp@ c15ca2

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

Changes to FindClosest...ToVector() and use of ..Map,..Set,..List defines in tesselation.cpp.

  • Property mode set to 100644
File size: 200.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 "info.hpp"
12#include "linkedcell.hpp"
13#include "log.hpp"
14#include "tesselation.hpp"
15#include "tesselationhelpers.hpp"
16#include "vector.hpp"
17#include "verbose.hpp"
18
19class molecule;
20
21// ======================================== Points on Boundary =================================
22
23/** Constructor of BoundaryPointSet.
24 */
25BoundaryPointSet::BoundaryPointSet() :
26 LinesCount(0),
27 value(0.),
28 Nr(-1)
29{
30 Info FunctionInfo(__func__);
31 Log() << Verbose(1) << "Adding noname." << endl;
32};
33
34/** Constructor of BoundaryPointSet with Tesselpoint.
35 * \param *Walker TesselPoint this boundary point represents
36 */
37BoundaryPointSet::BoundaryPointSet(TesselPoint * Walker) :
38 LinesCount(0),
39 node(Walker),
40 value(0.),
41 Nr(Walker->nr)
42{
43 Info FunctionInfo(__func__);
44 Log() << Verbose(1) << "Adding Node " << *Walker << endl;
45};
46
47/** Destructor of BoundaryPointSet.
48 * Sets node to NULL to avoid removing the original, represented TesselPoint.
49 * \note When removing point from a class Tesselation, use RemoveTesselationPoint()
50 */
51BoundaryPointSet::~BoundaryPointSet()
52{
53 Info FunctionInfo(__func__);
54 //Log() << Verbose(0) << "Erasing point nr. " << Nr << "." << endl;
55 if (!lines.empty())
56 eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some lines." << endl;
57 node = NULL;
58};
59
60/** Add a line to the LineMap of this point.
61 * \param *line line to add
62 */
63void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
64{
65 Info FunctionInfo(__func__);
66 Log() << Verbose(1) << "Adding " << *this << " to line " << *line << "."
67 << endl;
68 if (line->endpoints[0] == this)
69 {
70 lines.insert(LinePair(line->endpoints[1]->Nr, line));
71 }
72 else
73 {
74 lines.insert(LinePair(line->endpoints[0]->Nr, line));
75 }
76 LinesCount++;
77};
78
79/** output operator for BoundaryPointSet.
80 * \param &ost output stream
81 * \param &a boundary point
82 */
83ostream & operator <<(ostream &ost, const BoundaryPointSet &a)
84{
85 ost << "[" << a.Nr << "|" << a.node->Name << " at " << *a.node->node << "]";
86 return ost;
87}
88;
89
90// ======================================== Lines on Boundary =================================
91
92/** Constructor of BoundaryLineSet.
93 */
94BoundaryLineSet::BoundaryLineSet() :
95 Nr(-1)
96{
97 Info FunctionInfo(__func__);
98 for (int i = 0; i < 2; i++)
99 endpoints[i] = NULL;
100};
101
102/** Constructor of BoundaryLineSet with two endpoints.
103 * Adds line automatically to each endpoints' LineMap
104 * \param *Point[2] array of two boundary points
105 * \param number number of the list
106 */
107BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], const int number)
108{
109 Info FunctionInfo(__func__);
110 // set number
111 Nr = number;
112 // set endpoints in ascending order
113 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
114 // add this line to the hash maps of both endpoints
115 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
116 Point[1]->AddLine(this); //
117 // set skipped to false
118 skipped = false;
119 // clear triangles list
120 Log() << Verbose(0) << "New Line with endpoints " << *this << "." << endl;
121};
122
123/** Destructor for BoundaryLineSet.
124 * Removes itself from each endpoints' LineMap, calling RemoveTrianglePoint() when point not connected anymore.
125 * \note When removing lines from a class Tesselation, use RemoveTesselationLine()
126 */
127BoundaryLineSet::~BoundaryLineSet()
128{
129 Info FunctionInfo(__func__);
130 int Numbers[2];
131
132 // get other endpoint number of finding copies of same line
133 if (endpoints[1] != NULL)
134 Numbers[0] = endpoints[1]->Nr;
135 else
136 Numbers[0] = -1;
137 if (endpoints[0] != NULL)
138 Numbers[1] = endpoints[0]->Nr;
139 else
140 Numbers[1] = -1;
141
142 for (int i = 0; i < 2; i++) {
143 if (endpoints[i] != NULL) {
144 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
145 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
146 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
147 if ((*Runner).second == this) {
148 //Log() << Verbose(0) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
149 endpoints[i]->lines.erase(Runner);
150 break;
151 }
152 } else { // there's just a single line left
153 if (endpoints[i]->lines.erase(Nr)) {
154 //Log() << Verbose(0) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
155 }
156 }
157 if (endpoints[i]->lines.empty()) {
158 //Log() << Verbose(0) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
159 if (endpoints[i] != NULL) {
160 delete(endpoints[i]);
161 endpoints[i] = NULL;
162 }
163 }
164 }
165 }
166 if (!triangles.empty())
167 eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some triangles." << endl;
168};
169
170/** Add triangle to TriangleMap of this boundary line.
171 * \param *triangle to add
172 */
173void BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
174{
175 Info FunctionInfo(__func__);
176 Log() << Verbose(0) << "Add " << triangle->Nr << " to line " << *this << "." << endl;
177 triangles.insert(TrianglePair(triangle->Nr, triangle));
178};
179
180/** Checks whether we have a common endpoint with given \a *line.
181 * \param *line other line to test
182 * \return true - common endpoint present, false - not connected
183 */
184bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
185{
186 Info FunctionInfo(__func__);
187 if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
188 return true;
189 else
190 return false;
191};
192
193/** Checks whether the adjacent triangles of a baseline are convex or not.
194 * We sum the two angles of each height vector with respect to the center of the baseline.
195 * If greater/equal M_PI than we are convex.
196 * \param *out output stream for debugging
197 * \return true - triangles are convex, false - concave or less than two triangles connected
198 */
199bool BoundaryLineSet::CheckConvexityCriterion()
200{
201 Info FunctionInfo(__func__);
202 Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2], NormalCheck;
203 // get the two triangles
204 if (triangles.size() != 2) {
205 eLog() << Verbose(0) << "Baseline " << *this << " is connected to less than two triangles, Tesselation incomplete!" << endl;
206 return true;
207 }
208 // check normal vectors
209 // have a normal vector on the base line pointing outwards
210 //Log() << Verbose(0) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
211 BaseLineCenter.CopyVector(endpoints[0]->node->node);
212 BaseLineCenter.AddVector(endpoints[1]->node->node);
213 BaseLineCenter.Scale(1./2.);
214 BaseLine.CopyVector(endpoints[0]->node->node);
215 BaseLine.SubtractVector(endpoints[1]->node->node);
216 //Log() << Verbose(0) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
217
218 BaseLineNormal.Zero();
219 NormalCheck.Zero();
220 double sign = -1.;
221 int i=0;
222 class BoundaryPointSet *node = NULL;
223 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
224 //Log() << Verbose(0) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
225 NormalCheck.AddVector(&runner->second->NormalVector);
226 NormalCheck.Scale(sign);
227 sign = -sign;
228 if (runner->second->NormalVector.NormSquared() > MYEPSILON)
229 BaseLineNormal.CopyVector(&runner->second->NormalVector); // yes, copy second on top of first
230 else {
231 eLog() << Verbose(0) << "Triangle " << *runner->second << " has zero normal vector!" << endl;
232 }
233 node = runner->second->GetThirdEndpoint(this);
234 if (node != NULL) {
235 //Log() << Verbose(0) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
236 helper[i].CopyVector(node->node->node);
237 helper[i].SubtractVector(&BaseLineCenter);
238 helper[i].MakeNormalVector(&BaseLine); // we want to compare the triangle's heights' angles!
239 //Log() << Verbose(0) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
240 i++;
241 } else {
242 eLog() << Verbose(1) << "I cannot find third node in triangle, something's wrong." << endl;
243 return true;
244 }
245 }
246 //Log() << Verbose(0) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
247 if (NormalCheck.NormSquared() < MYEPSILON) {
248 Log() << Verbose(0) << "ACCEPT: Normalvectors of both triangles are the same: convex." << endl;
249 return true;
250 }
251 BaseLineNormal.Scale(-1.);
252 double angle = GetAngle(helper[0], helper[1], BaseLineNormal);
253 if ((angle - M_PI) > -MYEPSILON) {
254 Log() << Verbose(0) << "ACCEPT: Angle is greater than pi: convex." << endl;
255 return true;
256 } else {
257 Log() << Verbose(0) << "REJECT: Angle is less than pi: concave." << endl;
258 return false;
259 }
260}
261
262/** Checks whether point is any of the two endpoints this line contains.
263 * \param *point point to test
264 * \return true - point is of the line, false - is not
265 */
266bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
267{
268 Info FunctionInfo(__func__);
269 for(int i=0;i<2;i++)
270 if (point == endpoints[i])
271 return true;
272 return false;
273};
274
275/** Returns other endpoint of the line.
276 * \param *point other endpoint
277 * \return NULL - if endpoint not contained in BoundaryLineSet, or pointer to BoundaryPointSet otherwise
278 */
279class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(class BoundaryPointSet *point)
280{
281 Info FunctionInfo(__func__);
282 if (endpoints[0] == point)
283 return endpoints[1];
284 else if (endpoints[1] == point)
285 return endpoints[0];
286 else
287 return NULL;
288};
289
290/** output operator for BoundaryLineSet.
291 * \param &ost output stream
292 * \param &a boundary line
293 */
294ostream & operator <<(ostream &ost, const BoundaryLineSet &a)
295{
296 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 << "]";
297 return ost;
298};
299
300// ======================================== Triangles on Boundary =================================
301
302/** Constructor for BoundaryTriangleSet.
303 */
304BoundaryTriangleSet::BoundaryTriangleSet() :
305 Nr(-1)
306{
307 Info FunctionInfo(__func__);
308 for (int i = 0; i < 3; i++)
309 {
310 endpoints[i] = NULL;
311 lines[i] = NULL;
312 }
313};
314
315/** Constructor for BoundaryTriangleSet with three lines.
316 * \param *line[3] lines that make up the triangle
317 * \param number number of triangle
318 */
319BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number) :
320 Nr(number)
321{
322 Info FunctionInfo(__func__);
323 // set number
324 // set lines
325 for (int i = 0; i < 3; i++) {
326 lines[i] = line[i];
327 lines[i]->AddTriangle(this);
328 }
329 // get ascending order of endpoints
330 PointMap OrderMap;
331 for (int i = 0; i < 3; i++)
332 // for all three lines
333 for (int j = 0; j < 2; j++) { // for both endpoints
334 OrderMap.insert(pair<int, class BoundaryPointSet *> (
335 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
336 // and we don't care whether insertion fails
337 }
338 // set endpoints
339 int Counter = 0;
340 Log() << Verbose(0) << "New triangle " << Nr << " with end points: " << endl;
341 for (PointMap::iterator runner = OrderMap.begin(); runner != OrderMap.end(); runner++) {
342 endpoints[Counter] = runner->second;
343 Log() << Verbose(0) << " " << *endpoints[Counter] << endl;
344 Counter++;
345 }
346 if (Counter < 3) {
347 eLog() << Verbose(0) << "We have a triangle with only two distinct endpoints!" << endl;
348 performCriticalExit();
349 }
350};
351
352/** Destructor of BoundaryTriangleSet.
353 * Removes itself from each of its lines' LineMap and removes them if necessary.
354 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
355 */
356BoundaryTriangleSet::~BoundaryTriangleSet()
357{
358 Info FunctionInfo(__func__);
359 for (int i = 0; i < 3; i++) {
360 if (lines[i] != NULL) {
361 if (lines[i]->triangles.erase(Nr)) {
362 //Log() << Verbose(0) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
363 }
364 if (lines[i]->triangles.empty()) {
365 //Log() << Verbose(0) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
366 delete (lines[i]);
367 lines[i] = NULL;
368 }
369 }
370 }
371 //Log() << Verbose(0) << "Erasing triangle Nr." << Nr << " itself." << endl;
372};
373
374/** Calculates the normal vector for this triangle.
375 * Is made unique by comparison with \a OtherVector to point in the other direction.
376 * \param &OtherVector direction vector to make normal vector unique.
377 */
378void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
379{
380 Info FunctionInfo(__func__);
381 // get normal vector
382 NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
383
384 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
385 if (NormalVector.ScalarProduct(&OtherVector) > 0.)
386 NormalVector.Scale(-1.);
387 Log() << Verbose(1) << "Normal Vector is " << NormalVector << "." << endl;
388};
389
390/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
391 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
392 * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
393 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
394 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
395 * the first two basepoints) or not.
396 * \param *out output stream for debugging
397 * \param *MolCenter offset vector of line
398 * \param *x second endpoint of line, minus \a *MolCenter is directional vector of line
399 * \param *Intersection intersection on plane on return
400 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
401 */
402bool BoundaryTriangleSet::GetIntersectionInsideTriangle(Vector *MolCenter, Vector *x, Vector *Intersection)
403{
404 Info FunctionInfo(__func__);
405 Vector CrossPoint;
406 Vector helper;
407
408 if (!Intersection->GetIntersectionWithPlane(&NormalVector, endpoints[0]->node->node, MolCenter, x)) {
409 eLog() << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl;
410 return false;
411 }
412
413 // Calculate cross point between one baseline and the line from the third endpoint to intersection
414 int i=0;
415 do {
416 if (CrossPoint.GetIntersectionOfTwoLinesOnPlane(endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection, &NormalVector)) {
417 helper.CopyVector(endpoints[(i+1)%3]->node->node);
418 helper.SubtractVector(endpoints[i%3]->node->node);
419 } else
420 i++;
421 if (i>2)
422 break;
423 } while (CrossPoint.NormSquared() < MYEPSILON);
424 if (i==3) {
425 eLog() << Verbose(0) << "Could not find any cross points, something's utterly wrong here!" << endl;
426 }
427 CrossPoint.SubtractVector(endpoints[i%3]->node->node); // cross point was returned as absolute vector
428
429 // check whether intersection is inside or not by comparing length of intersection and length of cross point
430 if ((CrossPoint.NormSquared() - helper.NormSquared()) < MYEPSILON) { // inside
431 return true;
432 } else { // outside!
433 Intersection->Zero();
434 return false;
435 }
436};
437
438/** Checks whether lines is any of the three boundary lines this triangle contains.
439 * \param *line line to test
440 * \return true - line is of the triangle, false - is not
441 */
442bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
443{
444 Info FunctionInfo(__func__);
445 for(int i=0;i<3;i++)
446 if (line == lines[i])
447 return true;
448 return false;
449};
450
451/** Checks whether point is any of the three endpoints this triangle contains.
452 * \param *point point to test
453 * \return true - point is of the triangle, false - is not
454 */
455bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
456{
457 Info FunctionInfo(__func__);
458 for(int i=0;i<3;i++)
459 if (point == endpoints[i])
460 return true;
461 return false;
462};
463
464/** Checks whether point is any of the three endpoints this triangle contains.
465 * \param *point TesselPoint to test
466 * \return true - point is of the triangle, false - is not
467 */
468bool BoundaryTriangleSet::ContainsBoundaryPoint(class TesselPoint *point)
469{
470 Info FunctionInfo(__func__);
471 for(int i=0;i<3;i++)
472 if (point == endpoints[i]->node)
473 return true;
474 return false;
475};
476
477/** Checks whether three given \a *Points coincide with triangle's endpoints.
478 * \param *Points[3] pointer to BoundaryPointSet
479 * \return true - is the very triangle, false - is not
480 */
481bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
482{
483 Info FunctionInfo(__func__);
484 Log() << Verbose(1) << "INFO: Checking " << Points[0] << "," << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << "." << endl;
485 return (((endpoints[0] == Points[0])
486 || (endpoints[0] == Points[1])
487 || (endpoints[0] == Points[2])
488 ) && (
489 (endpoints[1] == Points[0])
490 || (endpoints[1] == Points[1])
491 || (endpoints[1] == Points[2])
492 ) && (
493 (endpoints[2] == Points[0])
494 || (endpoints[2] == Points[1])
495 || (endpoints[2] == Points[2])
496
497 ));
498};
499
500/** Checks whether three given \a *Points coincide with triangle's endpoints.
501 * \param *Points[3] pointer to BoundaryPointSet
502 * \return true - is the very triangle, false - is not
503 */
504bool BoundaryTriangleSet::IsPresentTupel(class BoundaryTriangleSet *T)
505{
506 Info FunctionInfo(__func__);
507 return (((endpoints[0] == T->endpoints[0])
508 || (endpoints[0] == T->endpoints[1])
509 || (endpoints[0] == T->endpoints[2])
510 ) && (
511 (endpoints[1] == T->endpoints[0])
512 || (endpoints[1] == T->endpoints[1])
513 || (endpoints[1] == T->endpoints[2])
514 ) && (
515 (endpoints[2] == T->endpoints[0])
516 || (endpoints[2] == T->endpoints[1])
517 || (endpoints[2] == T->endpoints[2])
518
519 ));
520};
521
522/** Returns the endpoint which is not contained in the given \a *line.
523 * \param *line baseline defining two endpoints
524 * \return pointer third endpoint or NULL if line does not belong to triangle.
525 */
526class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(class BoundaryLineSet *line)
527{
528 Info FunctionInfo(__func__);
529 // sanity check
530 if (!ContainsBoundaryLine(line))
531 return NULL;
532 for(int i=0;i<3;i++)
533 if (!line->ContainsBoundaryPoint(endpoints[i]))
534 return endpoints[i];
535 // actually, that' impossible :)
536 return NULL;
537};
538
539/** Calculates the center point of the triangle.
540 * Is third of the sum of all endpoints.
541 * \param *center central point on return.
542 */
543void BoundaryTriangleSet::GetCenter(Vector *center)
544{
545 Info FunctionInfo(__func__);
546 center->Zero();
547 for(int i=0;i<3;i++)
548 center->AddVector(endpoints[i]->node->node);
549 center->Scale(1./3.);
550}
551
552/** output operator for BoundaryTriangleSet.
553 * \param &ost output stream
554 * \param &a boundary triangle
555 */
556ostream &operator <<(ostream &ost, const BoundaryTriangleSet &a)
557{
558 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << "," << a.endpoints[1]->node->Name << "," << a.endpoints[2]->node->Name << "]";
559// ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
560// << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
561 return ost;
562};
563
564// ======================================== Polygons on Boundary =================================
565
566/** Constructor for BoundaryPolygonSet.
567 */
568BoundaryPolygonSet::BoundaryPolygonSet() :
569 Nr(-1)
570{
571 Info FunctionInfo(__func__);
572};
573
574/** Destructor of BoundaryPolygonSet.
575 * Just clears endpoints.
576 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
577 */
578BoundaryPolygonSet::~BoundaryPolygonSet()
579{
580 Info FunctionInfo(__func__);
581 endpoints.clear();
582 Log() << Verbose(1) << "Erasing polygon Nr." << Nr << " itself." << endl;
583};
584
585/** Calculates the normal vector for this triangle.
586 * Is made unique by comparison with \a OtherVector to point in the other direction.
587 * \param &OtherVector direction vector to make normal vector unique.
588 * \return allocated vector in normal direction
589 */
590Vector * BoundaryPolygonSet::GetNormalVector(const Vector &OtherVector) const
591{
592 Info FunctionInfo(__func__);
593 // get normal vector
594 Vector TemporaryNormal;
595 Vector *TotalNormal = new Vector;
596 PointSet::const_iterator Runner[3];
597 for (int i=0;i<3; i++) {
598 Runner[i] = endpoints.begin();
599 for (int j = 0; j<i; j++) { // go as much further
600 Runner[i]++;
601 if (Runner[i] == endpoints.end()) {
602 eLog() << Verbose(0) << "There are less than three endpoints in the polygon!" << endl;
603 performCriticalExit();
604 }
605 }
606 }
607 TotalNormal->Zero();
608 int counter=0;
609 for (; Runner[2] != endpoints.end(); ) {
610 TemporaryNormal.MakeNormalVector((*Runner[0])->node->node, (*Runner[1])->node->node, (*Runner[2])->node->node);
611 for (int i=0;i<3;i++) // increase each of them
612 Runner[i]++;
613 TotalNormal->AddVector(&TemporaryNormal);
614 }
615 TotalNormal->Scale(1./(double)counter);
616
617 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
618 if (TotalNormal->ScalarProduct(&OtherVector) > 0.)
619 TotalNormal->Scale(-1.);
620 Log() << Verbose(1) << "Normal Vector is " << *TotalNormal << "." << endl;
621
622 return TotalNormal;
623};
624
625/** Calculates the center point of the triangle.
626 * Is third of the sum of all endpoints.
627 * \param *center central point on return.
628 */
629void BoundaryPolygonSet::GetCenter(Vector * const center) const
630{
631 Info FunctionInfo(__func__);
632 center->Zero();
633 int counter = 0;
634 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
635 center->AddVector((*Runner)->node->node);
636 counter++;
637 }
638 center->Scale(1./(double)counter);
639 Log() << Verbose(1) << "Center is at " << *center << "." << endl;
640}
641
642/** Checks whether the polygons contains all three endpoints of the triangle.
643 * \param *triangle triangle to test
644 * \return true - triangle is contained polygon, false - is not
645 */
646bool BoundaryPolygonSet::ContainsBoundaryTriangle(const BoundaryTriangleSet * const triangle) const
647{
648 Info FunctionInfo(__func__);
649 return ContainsPresentTupel(triangle->endpoints, 3);
650};
651
652/** Checks whether the polygons contains both endpoints of the line.
653 * \param *line line to test
654 * \return true - line is of the triangle, false - is not
655 */
656bool BoundaryPolygonSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
657{
658 Info FunctionInfo(__func__);
659 return ContainsPresentTupel(line->endpoints, 2);
660};
661
662/** Checks whether point is any of the three endpoints this triangle contains.
663 * \param *point point to test
664 * \return true - point is of the triangle, false - is not
665 */
666bool BoundaryPolygonSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
667{
668 Info FunctionInfo(__func__);
669 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
670 Log() << Verbose(0) << "Checking against " << **Runner << endl;
671 if (point == (*Runner)) {
672 Log() << Verbose(0) << " Contained." << endl;
673 return true;
674 }
675 }
676 Log() << Verbose(0) << " Not contained." << endl;
677 return false;
678};
679
680/** Checks whether point is any of the three endpoints this triangle contains.
681 * \param *point TesselPoint to test
682 * \return true - point is of the triangle, false - is not
683 */
684bool BoundaryPolygonSet::ContainsBoundaryPoint(const TesselPoint * const point) const
685{
686 Info FunctionInfo(__func__);
687 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
688 if (point == (*Runner)->node) {
689 Log() << Verbose(0) << " Contained." << endl;
690 return true;
691 }
692 Log() << Verbose(0) << " Not contained." << endl;
693 return false;
694};
695
696/** Checks whether given array of \a *Points coincide with polygons's endpoints.
697 * \param **Points pointer to an array of BoundaryPointSet
698 * \param dim dimension of array
699 * \return true - set of points is contained in polygon, false - is not
700 */
701bool BoundaryPolygonSet::ContainsPresentTupel(const BoundaryPointSet * const * Points, const int dim) const
702{
703 Info FunctionInfo(__func__);
704 int counter = 0;
705 Log() << Verbose(1) << "Polygon is " << *this << endl;
706 for(int i=0;i<dim;i++) {
707 Log() << Verbose(1) << " Testing endpoint " << *Points[i] << endl;
708 if (ContainsBoundaryPoint(Points[i])) {
709 counter++;
710 }
711 }
712
713 if (counter == dim)
714 return true;
715 else
716 return false;
717};
718
719/** Checks whether given PointList coincide with polygons's endpoints.
720 * \param &endpoints PointList
721 * \return true - set of points is contained in polygon, false - is not
722 */
723bool BoundaryPolygonSet::ContainsPresentTupel(const PointSet &endpoints) const
724{
725 Info FunctionInfo(__func__);
726 size_t counter = 0;
727 Log() << Verbose(1) << "Polygon is " << *this << endl;
728 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
729 Log() << Verbose(1) << " Testing endpoint " << **Runner << endl;
730 if (ContainsBoundaryPoint(*Runner))
731 counter++;
732 }
733
734 if (counter == endpoints.size())
735 return true;
736 else
737 return false;
738};
739
740/** Checks whether given set of \a *Points coincide with polygons's endpoints.
741 * \param *P pointer to BoundaryPolygonSet
742 * \return true - is the very triangle, false - is not
743 */
744bool BoundaryPolygonSet::ContainsPresentTupel(const BoundaryPolygonSet * const P) const
745{
746 return ContainsPresentTupel((const PointSet)P->endpoints);
747};
748
749/** Gathers all the endpoints' triangles in a unique set.
750 * \return set of all triangles
751 */
752TriangleSet * BoundaryPolygonSet::GetAllContainedTrianglesFromEndpoints() const
753{
754 Info FunctionInfo(__func__);
755 pair <TriangleSet::iterator, bool> Tester;
756 TriangleSet *triangles = new TriangleSet;
757
758 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
759 for(LineMap::const_iterator Walker = (*Runner)->lines.begin(); Walker != (*Runner)->lines.end(); Walker++)
760 for(TriangleMap::const_iterator Sprinter = (Walker->second)->triangles.begin(); Sprinter != (Walker->second)->triangles.end(); Sprinter++) {
761 //Log() << Verbose(0) << " Testing triangle " << *(Sprinter->second) << endl;
762 if (ContainsBoundaryTriangle(Sprinter->second)) {
763 Tester = triangles->insert(Sprinter->second);
764 if (Tester.second)
765 Log() << Verbose(0) << "Adding triangle " << *(Sprinter->second) << endl;
766 }
767 }
768
769 Log() << Verbose(1) << "The Polygon of " << endpoints.size() << " endpoints has " << triangles->size() << " unique triangles in total." << endl;
770 return triangles;
771};
772
773/** Fills the endpoints of this polygon from the triangles attached to \a *line.
774 * \param *line lines with triangles attached
775 * \return true - polygon contains endpoints, false - line was NULL
776 */
777bool BoundaryPolygonSet::FillPolygonFromTrianglesOfLine(const BoundaryLineSet * const line)
778{
779 Info FunctionInfo(__func__);
780 pair <PointSet::iterator, bool> Tester;
781 if (line == NULL)
782 return false;
783 Log() << Verbose(1) << "Filling polygon from line " << *line << endl;
784 for(TriangleMap::const_iterator Runner = line->triangles.begin(); Runner != line->triangles.end(); Runner++) {
785 for (int i=0;i<3;i++) {
786 Tester = endpoints.insert((Runner->second)->endpoints[i]);
787 if (Tester.second)
788 Log() << Verbose(1) << " Inserting endpoint " << *((Runner->second)->endpoints[i]) << endl;
789 }
790 }
791
792 return true;
793};
794
795/** output operator for BoundaryPolygonSet.
796 * \param &ost output stream
797 * \param &a boundary polygon
798 */
799ostream &operator <<(ostream &ost, const BoundaryPolygonSet &a)
800{
801 ost << "[" << a.Nr << "|";
802 for(PointSet::const_iterator Runner = a.endpoints.begin(); Runner != a.endpoints.end();) {
803 ost << (*Runner)->node->Name;
804 Runner++;
805 if (Runner != a.endpoints.end())
806 ost << ",";
807 }
808 ost<< "]";
809 return ost;
810};
811
812// =========================================================== class TESSELPOINT ===========================================
813
814/** Constructor of class TesselPoint.
815 */
816TesselPoint::TesselPoint()
817{
818 Info FunctionInfo(__func__);
819 node = NULL;
820 nr = -1;
821 Name = NULL;
822};
823
824/** Destructor for class TesselPoint.
825 */
826TesselPoint::~TesselPoint()
827{
828 Info FunctionInfo(__func__);
829};
830
831/** Prints LCNode to screen.
832 */
833ostream & operator << (ostream &ost, const TesselPoint &a)
834{
835 ost << "[" << (a.Name) << "|" << a.Name << " at " << *a.node << "]";
836 return ost;
837};
838
839/** Prints LCNode to screen.
840 */
841ostream & TesselPoint::operator << (ostream &ost)
842{
843 Info FunctionInfo(__func__);
844 ost << "[" << (nr) << "|" << this << "]";
845 return ost;
846};
847
848
849// =========================================================== class POINTCLOUD ============================================
850
851/** Constructor of class PointCloud.
852 */
853PointCloud::PointCloud()
854{
855 Info FunctionInfo(__func__);
856};
857
858/** Destructor for class PointCloud.
859 */
860PointCloud::~PointCloud()
861{
862 Info FunctionInfo(__func__);
863};
864
865// ============================ CandidateForTesselation =============================
866
867/** Constructor of class CandidateForTesselation.
868 */
869CandidateForTesselation::CandidateForTesselation (BoundaryLineSet* line) :
870 BaseLine(line),
871 ShortestAngle(2.*M_PI),
872 OtherShortestAngle(2.*M_PI)
873{
874 Info FunctionInfo(__func__);
875};
876
877
878/** Constructor of class CandidateForTesselation.
879 */
880CandidateForTesselation::CandidateForTesselation (TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) :
881 BaseLine(line),
882 ShortestAngle(2.*M_PI),
883 OtherShortestAngle(2.*M_PI)
884{
885 Info FunctionInfo(__func__);
886 OptCenter.CopyVector(&OptCandidateCenter);
887 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
888};
889
890/** Destructor for class CandidateForTesselation.
891 */
892CandidateForTesselation::~CandidateForTesselation() {
893 BaseLine = NULL;
894};
895
896/** output operator for CandidateForTesselation.
897 * \param &ost output stream
898 * \param &a boundary line
899 */
900ostream & operator <<(ostream &ost, const CandidateForTesselation &a)
901{
902 ost << "[" << a.BaseLine->Nr << "|" << a.BaseLine->endpoints[0]->node->Name << "," << a.BaseLine->endpoints[1]->node->Name << "] with ";
903 if (a.pointlist.empty())
904 ost << "no candidate.";
905 else {
906 ost << "candidate";
907 if (a.pointlist.size() != 1)
908 ost << "s ";
909 else
910 ost << " ";
911 for (TesselPointList::const_iterator Runner = a.pointlist.begin(); Runner != a.pointlist.end(); Runner++)
912 ost << *(*Runner) << " ";
913 ost << " at angle " << (a.ShortestAngle)<< ".";
914 }
915
916 return ost;
917};
918
919
920// =========================================================== class TESSELATION ===========================================
921
922/** Constructor of class Tesselation.
923 */
924Tesselation::Tesselation() :
925 PointsOnBoundaryCount(0),
926 LinesOnBoundaryCount(0),
927 TrianglesOnBoundaryCount(0),
928 LastTriangle(NULL),
929 TriangleFilesWritten(0),
930 InternalPointer(PointsOnBoundary.begin())
931{
932 Info FunctionInfo(__func__);
933}
934;
935
936/** Destructor of class Tesselation.
937 * We have to free all points, lines and triangles.
938 */
939Tesselation::~Tesselation()
940{
941 Info FunctionInfo(__func__);
942 Log() << Verbose(0) << "Free'ing TesselStruct ... " << endl;
943 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
944 if (runner->second != NULL) {
945 delete (runner->second);
946 runner->second = NULL;
947 } else
948 eLog() << Verbose(1) << "The triangle " << runner->first << " has already been free'd." << endl;
949 }
950 Log() << Verbose(0) << "This envelope was written to file " << TriangleFilesWritten << " times(s)." << endl;
951}
952;
953
954/** PointCloud implementation of GetCenter
955 * Uses PointsOnBoundary and STL stuff.
956 */
957Vector * Tesselation::GetCenter(ofstream *out) const
958{
959 Info FunctionInfo(__func__);
960 Vector *Center = new Vector(0.,0.,0.);
961 int num=0;
962 for (GoToFirst(); (!IsEnd()); GoToNext()) {
963 Center->AddVector(GetPoint()->node);
964 num++;
965 }
966 Center->Scale(1./num);
967 return Center;
968};
969
970/** PointCloud implementation of GoPoint
971 * Uses PointsOnBoundary and STL stuff.
972 */
973TesselPoint * Tesselation::GetPoint() const
974{
975 Info FunctionInfo(__func__);
976 return (InternalPointer->second->node);
977};
978
979/** PointCloud implementation of GetTerminalPoint.
980 * Uses PointsOnBoundary and STL stuff.
981 */
982TesselPoint * Tesselation::GetTerminalPoint() const
983{
984 Info FunctionInfo(__func__);
985 PointMap::const_iterator Runner = PointsOnBoundary.end();
986 Runner--;
987 return (Runner->second->node);
988};
989
990/** PointCloud implementation of GoToNext.
991 * Uses PointsOnBoundary and STL stuff.
992 */
993void Tesselation::GoToNext() const
994{
995 Info FunctionInfo(__func__);
996 if (InternalPointer != PointsOnBoundary.end())
997 InternalPointer++;
998};
999
1000/** PointCloud implementation of GoToPrevious.
1001 * Uses PointsOnBoundary and STL stuff.
1002 */
1003void Tesselation::GoToPrevious() const
1004{
1005 Info FunctionInfo(__func__);
1006 if (InternalPointer != PointsOnBoundary.begin())
1007 InternalPointer--;
1008};
1009
1010/** PointCloud implementation of GoToFirst.
1011 * Uses PointsOnBoundary and STL stuff.
1012 */
1013void Tesselation::GoToFirst() const
1014{
1015 Info FunctionInfo(__func__);
1016 InternalPointer = PointsOnBoundary.begin();
1017};
1018
1019/** PointCloud implementation of GoToLast.
1020 * Uses PointsOnBoundary and STL stuff.
1021 */
1022void Tesselation::GoToLast() const
1023{
1024 Info FunctionInfo(__func__);
1025 InternalPointer = PointsOnBoundary.end();
1026 InternalPointer--;
1027};
1028
1029/** PointCloud implementation of IsEmpty.
1030 * Uses PointsOnBoundary and STL stuff.
1031 */
1032bool Tesselation::IsEmpty() const
1033{
1034 Info FunctionInfo(__func__);
1035 return (PointsOnBoundary.empty());
1036};
1037
1038/** PointCloud implementation of IsLast.
1039 * Uses PointsOnBoundary and STL stuff.
1040 */
1041bool Tesselation::IsEnd() const
1042{
1043 Info FunctionInfo(__func__);
1044 return (InternalPointer == PointsOnBoundary.end());
1045};
1046
1047
1048/** Gueses first starting triangle of the convex envelope.
1049 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
1050 * \param *out output stream for debugging
1051 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
1052 */
1053void
1054Tesselation::GuessStartingTriangle()
1055{
1056 Info FunctionInfo(__func__);
1057 // 4b. create a starting triangle
1058 // 4b1. create all distances
1059 DistanceMultiMap DistanceMMap;
1060 double distance, tmp;
1061 Vector PlaneVector, TrialVector;
1062 PointMap::iterator A, B, C; // three nodes of the first triangle
1063 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
1064
1065 // with A chosen, take each pair B,C and sort
1066 if (A != PointsOnBoundary.end())
1067 {
1068 B = A;
1069 B++;
1070 for (; B != PointsOnBoundary.end(); B++)
1071 {
1072 C = B;
1073 C++;
1074 for (; C != PointsOnBoundary.end(); C++)
1075 {
1076 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
1077 distance = tmp * tmp;
1078 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
1079 distance += tmp * tmp;
1080 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
1081 distance += tmp * tmp;
1082 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
1083 }
1084 }
1085 }
1086 // // listing distances
1087 // Log() << Verbose(1) << "Listing DistanceMMap:";
1088 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
1089 // Log() << Verbose(0) << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
1090 // }
1091 // Log() << Verbose(0) << endl;
1092 // 4b2. pick three baselines forming a triangle
1093 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1094 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
1095 for (; baseline != DistanceMMap.end(); baseline++)
1096 {
1097 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1098 // 2. next, we have to check whether all points reside on only one side of the triangle
1099 // 3. construct plane vector
1100 PlaneVector.MakeNormalVector(A->second->node->node,
1101 baseline->second.first->second->node->node,
1102 baseline->second.second->second->node->node);
1103 Log() << Verbose(2) << "Plane vector of candidate triangle is " << PlaneVector << endl;
1104 // 4. loop over all points
1105 double sign = 0.;
1106 PointMap::iterator checker = PointsOnBoundary.begin();
1107 for (; checker != PointsOnBoundary.end(); checker++)
1108 {
1109 // (neglecting A,B,C)
1110 if ((checker == A) || (checker == baseline->second.first) || (checker
1111 == baseline->second.second))
1112 continue;
1113 // 4a. project onto plane vector
1114 TrialVector.CopyVector(checker->second->node->node);
1115 TrialVector.SubtractVector(A->second->node->node);
1116 distance = TrialVector.ScalarProduct(&PlaneVector);
1117 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
1118 continue;
1119 Log() << Verbose(2) << "Projection of " << checker->second->node->Name << " yields distance of " << distance << "." << endl;
1120 tmp = distance / fabs(distance);
1121 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
1122 if ((sign != 0) && (tmp != sign))
1123 {
1124 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
1125 Log() << Verbose(2) << "Current candidates: "
1126 << A->second->node->Name << ","
1127 << baseline->second.first->second->node->Name << ","
1128 << baseline->second.second->second->node->Name << " leaves "
1129 << checker->second->node->Name << " outside the convex hull."
1130 << endl;
1131 break;
1132 }
1133 else
1134 { // note the sign for later
1135 Log() << Verbose(2) << "Current candidates: "
1136 << A->second->node->Name << ","
1137 << baseline->second.first->second->node->Name << ","
1138 << baseline->second.second->second->node->Name << " leave "
1139 << checker->second->node->Name << " inside the convex hull."
1140 << endl;
1141 sign = tmp;
1142 }
1143 // 4d. Check whether the point is inside the triangle (check distance to each node
1144 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
1145 int innerpoint = 0;
1146 if ((tmp < A->second->node->node->DistanceSquared(
1147 baseline->second.first->second->node->node)) && (tmp
1148 < A->second->node->node->DistanceSquared(
1149 baseline->second.second->second->node->node)))
1150 innerpoint++;
1151 tmp = checker->second->node->node->DistanceSquared(
1152 baseline->second.first->second->node->node);
1153 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
1154 A->second->node->node)) && (tmp
1155 < baseline->second.first->second->node->node->DistanceSquared(
1156 baseline->second.second->second->node->node)))
1157 innerpoint++;
1158 tmp = checker->second->node->node->DistanceSquared(
1159 baseline->second.second->second->node->node);
1160 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
1161 baseline->second.first->second->node->node)) && (tmp
1162 < baseline->second.second->second->node->node->DistanceSquared(
1163 A->second->node->node)))
1164 innerpoint++;
1165 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
1166 if (innerpoint == 3)
1167 break;
1168 }
1169 // 5. come this far, all on same side? Then break 1. loop and construct triangle
1170 if (checker == PointsOnBoundary.end())
1171 {
1172 Log() << Verbose(2) << "Looks like we have a candidate!" << endl;
1173 break;
1174 }
1175 }
1176 if (baseline != DistanceMMap.end())
1177 {
1178 BPS[0] = baseline->second.first->second;
1179 BPS[1] = baseline->second.second->second;
1180 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1181 BPS[0] = A->second;
1182 BPS[1] = baseline->second.second->second;
1183 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1184 BPS[0] = baseline->second.first->second;
1185 BPS[1] = A->second;
1186 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1187
1188 // 4b3. insert created triangle
1189 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1190 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1191 TrianglesOnBoundaryCount++;
1192 for (int i = 0; i < NDIM; i++)
1193 {
1194 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
1195 LinesOnBoundaryCount++;
1196 }
1197
1198 Log() << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
1199 }
1200 else
1201 {
1202 eLog() << Verbose(0) << "No starting triangle found." << endl;
1203 }
1204}
1205;
1206
1207/** Tesselates the convex envelope of a cluster from a single starting triangle.
1208 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
1209 * 2 triangles. Hence, we go through all current lines:
1210 * -# if the lines contains to only one triangle
1211 * -# We search all points in the boundary
1212 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
1213 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
1214 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
1215 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
1216 * \param *out output stream for debugging
1217 * \param *configuration for IsAngstroem
1218 * \param *cloud cluster of points
1219 */
1220void Tesselation::TesselateOnBoundary(const PointCloud * const cloud)
1221{
1222 Info FunctionInfo(__func__);
1223 bool flag;
1224 PointMap::iterator winner;
1225 class BoundaryPointSet *peak = NULL;
1226 double SmallestAngle, TempAngle;
1227 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
1228 LineMap::iterator LineChecker[2];
1229
1230 Center = cloud->GetCenter();
1231 // create a first tesselation with the given BoundaryPoints
1232 do {
1233 flag = false;
1234 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
1235 if (baseline->second->triangles.size() == 1) {
1236 // 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)
1237 SmallestAngle = M_PI;
1238
1239 // get peak point with respect to this base line's only triangle
1240 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
1241 Log() << Verbose(0) << "Current baseline is between " << *(baseline->second) << "." << endl;
1242 for (int i = 0; i < 3; i++)
1243 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
1244 peak = BTS->endpoints[i];
1245 Log() << Verbose(1) << " and has peak " << *peak << "." << endl;
1246
1247 // prepare some auxiliary vectors
1248 Vector BaseLineCenter, BaseLine;
1249 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
1250 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
1251 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
1252 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
1253 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
1254
1255 // offset to center of triangle
1256 CenterVector.Zero();
1257 for (int i = 0; i < 3; i++)
1258 CenterVector.AddVector(BTS->endpoints[i]->node->node);
1259 CenterVector.Scale(1. / 3.);
1260 Log() << Verbose(2) << "CenterVector of base triangle is " << CenterVector << endl;
1261
1262 // normal vector of triangle
1263 NormalVector.CopyVector(Center);
1264 NormalVector.SubtractVector(&CenterVector);
1265 BTS->GetNormalVector(NormalVector);
1266 NormalVector.CopyVector(&BTS->NormalVector);
1267 Log() << Verbose(2) << "NormalVector of base triangle is " << NormalVector << endl;
1268
1269 // vector in propagation direction (out of triangle)
1270 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
1271 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
1272 TempVector.CopyVector(&CenterVector);
1273 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
1274 //Log() << Verbose(0) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
1275 if (PropagationVector.ScalarProduct(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
1276 PropagationVector.Scale(-1.);
1277 Log() << Verbose(2) << "PropagationVector of base triangle is " << PropagationVector << endl;
1278 winner = PointsOnBoundary.end();
1279
1280 // loop over all points and calculate angle between normal vector of new and present triangle
1281 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
1282 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
1283 Log() << Verbose(1) << "Target point is " << *(target->second) << ":" << endl;
1284
1285 // first check direction, so that triangles don't intersect
1286 VirtualNormalVector.CopyVector(target->second->node->node);
1287 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
1288 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
1289 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
1290 Log() << Verbose(2) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
1291 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
1292 Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
1293 continue;
1294 } else
1295 Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
1296
1297 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
1298 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
1299 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
1300 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->triangles.size() == 2))) {
1301 Log() << Verbose(2) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->triangles.size() << " triangles." << endl;
1302 continue;
1303 }
1304 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->triangles.size() == 2))) {
1305 Log() << Verbose(2) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->triangles.size() << " triangles." << endl;
1306 continue;
1307 }
1308
1309 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
1310 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)))) {
1311 Log() << Verbose(4) << "Current target is peak!" << endl;
1312 continue;
1313 }
1314
1315 // check for linear dependence
1316 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1317 TempVector.SubtractVector(target->second->node->node);
1318 helper.CopyVector(baseline->second->endpoints[1]->node->node);
1319 helper.SubtractVector(target->second->node->node);
1320 helper.ProjectOntoPlane(&TempVector);
1321 if (fabs(helper.NormSquared()) < MYEPSILON) {
1322 Log() << Verbose(2) << "Chosen set of vectors is linear dependent." << endl;
1323 continue;
1324 }
1325
1326 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
1327 flag = true;
1328 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
1329 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1330 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
1331 TempVector.AddVector(target->second->node->node);
1332 TempVector.Scale(1./3.);
1333 TempVector.SubtractVector(Center);
1334 // make it always point outward
1335 if (VirtualNormalVector.ScalarProduct(&TempVector) < 0)
1336 VirtualNormalVector.Scale(-1.);
1337 // calculate angle
1338 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1339 Log() << Verbose(2) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
1340 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
1341 SmallestAngle = TempAngle;
1342 winner = target;
1343 Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1344 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
1345 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
1346 helper.CopyVector(target->second->node->node);
1347 helper.SubtractVector(&BaseLineCenter);
1348 helper.ProjectOntoPlane(&BaseLine);
1349 // ...the one with the smaller angle is the better candidate
1350 TempVector.CopyVector(target->second->node->node);
1351 TempVector.SubtractVector(&BaseLineCenter);
1352 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1353 TempAngle = TempVector.Angle(&helper);
1354 TempVector.CopyVector(winner->second->node->node);
1355 TempVector.SubtractVector(&BaseLineCenter);
1356 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1357 if (TempAngle < TempVector.Angle(&helper)) {
1358 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1359 SmallestAngle = TempAngle;
1360 winner = target;
1361 Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
1362 } else
1363 Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
1364 } else
1365 Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1366 }
1367 } // end of loop over all boundary points
1368
1369 // 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
1370 if (winner != PointsOnBoundary.end()) {
1371 Log() << Verbose(0) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
1372 // create the lins of not yet present
1373 BLS[0] = baseline->second;
1374 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1375 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
1376 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
1377 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
1378 BPS[0] = baseline->second->endpoints[0];
1379 BPS[1] = winner->second;
1380 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1381 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
1382 LinesOnBoundaryCount++;
1383 } else
1384 BLS[1] = LineChecker[0]->second;
1385 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
1386 BPS[0] = baseline->second->endpoints[1];
1387 BPS[1] = winner->second;
1388 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1389 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
1390 LinesOnBoundaryCount++;
1391 } else
1392 BLS[2] = LineChecker[1]->second;
1393 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1394 BTS->GetCenter(&helper);
1395 helper.SubtractVector(Center);
1396 helper.Scale(-1);
1397 BTS->GetNormalVector(helper);
1398 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1399 TrianglesOnBoundaryCount++;
1400 } else {
1401 eLog() << Verbose(2) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
1402 }
1403
1404 // 5d. If the set of lines is not yet empty, go to 5. and continue
1405 } else
1406 Log() << Verbose(0) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl;
1407 } while (flag);
1408
1409 // exit
1410 delete(Center);
1411};
1412
1413/** Inserts all points outside of the tesselated surface into it by adding new triangles.
1414 * \param *out output stream for debugging
1415 * \param *cloud cluster of points
1416 * \param *LC LinkedCell structure to find nearest point quickly
1417 * \return true - all straddling points insert, false - something went wrong
1418 */
1419bool Tesselation::InsertStraddlingPoints(const PointCloud *cloud, const LinkedCell *LC)
1420{
1421 Info FunctionInfo(__func__);
1422 Vector Intersection, Normal;
1423 TesselPoint *Walker = NULL;
1424 Vector *Center = cloud->GetCenter();
1425 TriangleList *triangles = NULL;
1426 bool AddFlag = false;
1427 LinkedCell *BoundaryPoints = NULL;
1428
1429 cloud->GoToFirst();
1430 BoundaryPoints = new LinkedCell(this, 5.);
1431 while (!cloud->IsEnd()) { // we only have to go once through all points, as boundary can become only bigger
1432 if (AddFlag) {
1433 delete(BoundaryPoints);
1434 BoundaryPoints = new LinkedCell(this, 5.);
1435 AddFlag = false;
1436 }
1437 Walker = cloud->GetPoint();
1438 Log() << Verbose(0) << "Current point is " << *Walker << "." << endl;
1439 // get the next triangle
1440 triangles = FindClosestTrianglesToVector(Walker->node, BoundaryPoints);
1441 BTS = triangles->front();
1442 if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
1443 Log() << Verbose(0) << "No triangles found, probably a tesselation point itself." << endl;
1444 cloud->GoToNext();
1445 continue;
1446 } else {
1447 }
1448 Log() << Verbose(0) << "Closest triangle is " << *BTS << "." << endl;
1449 // get the intersection point
1450 if (BTS->GetIntersectionInsideTriangle(Center, Walker->node, &Intersection)) {
1451 Log() << Verbose(0) << "We have an intersection at " << Intersection << "." << endl;
1452 // we have the intersection, check whether in- or outside of boundary
1453 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
1454 // inside, next!
1455 Log() << Verbose(0) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
1456 } else {
1457 // outside!
1458 Log() << Verbose(0) << *Walker << " is outside wrt triangle " << *BTS << "." << endl;
1459 class BoundaryLineSet *OldLines[3], *NewLines[3];
1460 class BoundaryPointSet *OldPoints[3], *NewPoint;
1461 // store the three old lines and old points
1462 for (int i=0;i<3;i++) {
1463 OldLines[i] = BTS->lines[i];
1464 OldPoints[i] = BTS->endpoints[i];
1465 }
1466 Normal.CopyVector(&BTS->NormalVector);
1467 // add Walker to boundary points
1468 Log() << Verbose(0) << "Adding " << *Walker << " to BoundaryPoints." << endl;
1469 AddFlag = true;
1470 if (AddBoundaryPoint(Walker,0))
1471 NewPoint = BPS[0];
1472 else
1473 continue;
1474 // remove triangle
1475 Log() << Verbose(0) << "Erasing triangle " << *BTS << "." << endl;
1476 TrianglesOnBoundary.erase(BTS->Nr);
1477 delete(BTS);
1478 // create three new boundary lines
1479 for (int i=0;i<3;i++) {
1480 BPS[0] = NewPoint;
1481 BPS[1] = OldPoints[i];
1482 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1483 Log() << Verbose(1) << "Creating new line " << *NewLines[i] << "." << endl;
1484 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
1485 LinesOnBoundaryCount++;
1486 }
1487 // create three new triangle with new point
1488 for (int i=0;i<3;i++) { // find all baselines
1489 BLS[0] = OldLines[i];
1490 int n = 1;
1491 for (int j=0;j<3;j++) {
1492 if (NewLines[j]->IsConnectedTo(BLS[0])) {
1493 if (n>2) {
1494 eLog() << Verbose(2) << BLS[0] << " connects to all of the new lines?!" << endl;
1495 return false;
1496 } else
1497 BLS[n++] = NewLines[j];
1498 }
1499 }
1500 // create the triangle
1501 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1502 Normal.Scale(-1.);
1503 BTS->GetNormalVector(Normal);
1504 Normal.Scale(-1.);
1505 Log() << Verbose(0) << "Created new triangle " << *BTS << "." << endl;
1506 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1507 TrianglesOnBoundaryCount++;
1508 }
1509 }
1510 } else { // something is wrong with FindClosestTriangleToPoint!
1511 eLog() << Verbose(1) << "The closest triangle did not produce an intersection!" << endl;
1512 return false;
1513 }
1514 cloud->GoToNext();
1515 }
1516
1517 // exit
1518 delete(Center);
1519 return true;
1520};
1521
1522/** Adds a point to the tesselation::PointsOnBoundary list.
1523 * \param *Walker point to add
1524 * \param n TesselStruct::BPS index to put pointer into
1525 * \return true - new point was added, false - point already present
1526 */
1527bool Tesselation::AddBoundaryPoint(TesselPoint * Walker, const int n)
1528{
1529 Info FunctionInfo(__func__);
1530 PointTestPair InsertUnique;
1531 BPS[n] = new class BoundaryPointSet(Walker);
1532 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[n]));
1533 if (InsertUnique.second) { // if new point was not present before, increase counter
1534 PointsOnBoundaryCount++;
1535 return true;
1536 } else {
1537 delete(BPS[n]);
1538 BPS[n] = InsertUnique.first->second;
1539 return false;
1540 }
1541}
1542;
1543
1544/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1545 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1546 * @param Candidate point to add
1547 * @param n index for this point in Tesselation::TPS array
1548 */
1549void Tesselation::AddTesselationPoint(TesselPoint* Candidate, const int n)
1550{
1551 Info FunctionInfo(__func__);
1552 PointTestPair InsertUnique;
1553 TPS[n] = new class BoundaryPointSet(Candidate);
1554 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1555 if (InsertUnique.second) { // if new point was not present before, increase counter
1556 PointsOnBoundaryCount++;
1557 } else {
1558 delete TPS[n];
1559 Log() << Verbose(0) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1560 TPS[n] = (InsertUnique.first)->second;
1561 }
1562}
1563;
1564
1565/** Sets point to a present Tesselation::PointsOnBoundary.
1566 * Tesselation::TPS is set to the existing one or NULL if not found.
1567 * @param Candidate point to set to
1568 * @param n index for this point in Tesselation::TPS array
1569 */
1570void Tesselation::SetTesselationPoint(TesselPoint* Candidate, const int n) const
1571{
1572 Info FunctionInfo(__func__);
1573 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidate->nr);
1574 if (FindPoint != PointsOnBoundary.end())
1575 TPS[n] = FindPoint->second;
1576 else
1577 TPS[n] = NULL;
1578};
1579
1580/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1581 * If successful it raises the line count and inserts the new line into the BLS,
1582 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1583 * @param *a first endpoint
1584 * @param *b second endpoint
1585 * @param n index of Tesselation::BLS giving the line with both endpoints
1586 */
1587void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n) {
1588 bool insertNewLine = true;
1589
1590 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1591 if (FindLine != a->lines.end()) {
1592 Log() << Verbose(1) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1593
1594 pair<LineMap::iterator,LineMap::iterator> FindPair;
1595 FindPair = a->lines.equal_range(b->node->nr);
1596
1597 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1598 // If there is a line with less than two attached triangles, we don't need a new line.
1599 if (FindLine->second->triangles.size() < 2) {
1600 insertNewLine = false;
1601 Log() << Verbose(0) << "Using existing line " << *FindLine->second << endl;
1602
1603 BPS[0] = FindLine->second->endpoints[0];
1604 BPS[1] = FindLine->second->endpoints[1];
1605 BLS[n] = FindLine->second;
1606
1607 // remove existing line from OpenLines
1608 CandidateMap::iterator CandidateLine = OpenLines.find(BLS[n]);
1609 if (CandidateLine != OpenLines.end()) {
1610 Log() << Verbose(1) << " Removing line from OpenLines." << endl;
1611 delete(CandidateLine->second);
1612 OpenLines.erase(CandidateLine);
1613 } else {
1614 eLog() << Verbose(1) << "Line exists and is attached to less than two triangles, but not in OpenLines!" << endl;
1615 }
1616
1617 break;
1618 }
1619 }
1620 }
1621
1622 if (insertNewLine) {
1623 AlwaysAddTesselationTriangleLine(a, b, n);
1624 }
1625}
1626;
1627
1628/**
1629 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1630 * Raises the line count and inserts the new line into the BLS.
1631 *
1632 * @param *a first endpoint
1633 * @param *b second endpoint
1634 * @param n index of Tesselation::BLS giving the line with both endpoints
1635 */
1636void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
1637{
1638 Info FunctionInfo(__func__);
1639 Log() << Verbose(0) << "Adding open line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1640 BPS[0] = a;
1641 BPS[1] = b;
1642 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1643 // add line to global map
1644 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1645 // increase counter
1646 LinesOnBoundaryCount++;
1647 // also add to open lines
1648 CandidateForTesselation *CFT = new CandidateForTesselation(BLS[n]);
1649 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (BLS[n], CFT));
1650};
1651
1652/** Function adds triangle to global list.
1653 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1654 */
1655void Tesselation::AddTesselationTriangle()
1656{
1657 Info FunctionInfo(__func__);
1658 Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1659
1660 // add triangle to global map
1661 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1662 TrianglesOnBoundaryCount++;
1663
1664 // set as last new triangle
1665 LastTriangle = BTS;
1666
1667 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1668};
1669
1670/** Function adds triangle to global list.
1671 * Furthermore, the triangle number is set to \a nr.
1672 * \param nr triangle number
1673 */
1674void Tesselation::AddTesselationTriangle(const int nr)
1675{
1676 Info FunctionInfo(__func__);
1677 Log() << Verbose(0) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1678
1679 // add triangle to global map
1680 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1681
1682 // set as last new triangle
1683 LastTriangle = BTS;
1684
1685 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1686};
1687
1688/** Removes a triangle from the tesselation.
1689 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1690 * Removes itself from memory.
1691 * \param *triangle to remove
1692 */
1693void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1694{
1695 Info FunctionInfo(__func__);
1696 if (triangle == NULL)
1697 return;
1698 for (int i = 0; i < 3; i++) {
1699 if (triangle->lines[i] != NULL) {
1700 Log() << Verbose(0) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1701 triangle->lines[i]->triangles.erase(triangle->Nr);
1702 if (triangle->lines[i]->triangles.empty()) {
1703 Log() << Verbose(0) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1704 RemoveTesselationLine(triangle->lines[i]);
1705 } else {
1706 Log() << Verbose(0) << *triangle->lines[i] << " is still attached to another triangle: ";
1707 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (triangle->lines[i], NULL));
1708 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1709 Log() << Verbose(0) << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1710 Log() << Verbose(0) << endl;
1711// for (int j=0;j<2;j++) {
1712// Log() << Verbose(0) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1713// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1714// Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1715// Log() << Verbose(0) << endl;
1716// }
1717 }
1718 triangle->lines[i] = NULL; // free'd or not: disconnect
1719 } else
1720 eLog() << Verbose(1) << "This line " << i << " has already been free'd." << endl;
1721 }
1722
1723 if (TrianglesOnBoundary.erase(triangle->Nr))
1724 Log() << Verbose(0) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1725 delete(triangle);
1726};
1727
1728/** Removes a line from the tesselation.
1729 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1730 * \param *line line to remove
1731 */
1732void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1733{
1734 Info FunctionInfo(__func__);
1735 int Numbers[2];
1736
1737 if (line == NULL)
1738 return;
1739 // get other endpoint number for finding copies of same line
1740 if (line->endpoints[1] != NULL)
1741 Numbers[0] = line->endpoints[1]->Nr;
1742 else
1743 Numbers[0] = -1;
1744 if (line->endpoints[0] != NULL)
1745 Numbers[1] = line->endpoints[0]->Nr;
1746 else
1747 Numbers[1] = -1;
1748
1749 for (int i = 0; i < 2; i++) {
1750 if (line->endpoints[i] != NULL) {
1751 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
1752 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
1753 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
1754 if ((*Runner).second == line) {
1755 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1756 line->endpoints[i]->lines.erase(Runner);
1757 break;
1758 }
1759 } else { // there's just a single line left
1760 if (line->endpoints[i]->lines.erase(line->Nr))
1761 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1762 }
1763 if (line->endpoints[i]->lines.empty()) {
1764 Log() << Verbose(0) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
1765 RemoveTesselationPoint(line->endpoints[i]);
1766 } else {
1767 Log() << Verbose(0) << *line->endpoints[i] << " has still lines it's attached to: ";
1768 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
1769 Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1770 Log() << Verbose(0) << endl;
1771 }
1772 line->endpoints[i] = NULL; // free'd or not: disconnect
1773 } else
1774 eLog() << Verbose(1) << "Endpoint " << i << " has already been free'd." << endl;
1775 }
1776 if (!line->triangles.empty())
1777 eLog() << Verbose(2) << "Memory Leak! I " << *line << " am still connected to some triangles." << endl;
1778
1779 if (LinesOnBoundary.erase(line->Nr))
1780 Log() << Verbose(0) << "Removing line Nr. " << line->Nr << "." << endl;
1781 delete(line);
1782};
1783
1784/** Removes a point from the tesselation.
1785 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
1786 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
1787 * \param *point point to remove
1788 */
1789void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
1790{
1791 Info FunctionInfo(__func__);
1792 if (point == NULL)
1793 return;
1794 if (PointsOnBoundary.erase(point->Nr))
1795 Log() << Verbose(0) << "Removing point Nr. " << point->Nr << "." << endl;
1796 delete(point);
1797};
1798
1799/** Checks whether the triangle consisting of the three points is already present.
1800 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1801 * lines. If any of the three edges already has two triangles attached, false is
1802 * returned.
1803 * \param *out output stream for debugging
1804 * \param *Candidates endpoints of the triangle candidate
1805 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1806 * triangles exist which is the maximum for three points
1807 */
1808int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) const
1809{
1810 Info FunctionInfo(__func__);
1811 int adjacentTriangleCount = 0;
1812 class BoundaryPointSet *Points[3];
1813
1814 // builds a triangle point set (Points) of the end points
1815 for (int i = 0; i < 3; i++) {
1816 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1817 if (FindPoint != PointsOnBoundary.end()) {
1818 Points[i] = FindPoint->second;
1819 } else {
1820 Points[i] = NULL;
1821 }
1822 }
1823
1824 // checks lines between the points in the Points for their adjacent triangles
1825 for (int i = 0; i < 3; i++) {
1826 if (Points[i] != NULL) {
1827 for (int j = i; j < 3; j++) {
1828 if (Points[j] != NULL) {
1829 LineMap::const_iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1830 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1831 TriangleMap *triangles = &FindLine->second->triangles;
1832 Log() << Verbose(1) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1833 for (TriangleMap::const_iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1834 if (FindTriangle->second->IsPresentTupel(Points)) {
1835 adjacentTriangleCount++;
1836 }
1837 }
1838 Log() << Verbose(1) << "end." << endl;
1839 }
1840 // Only one of the triangle lines must be considered for the triangle count.
1841 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1842 //return adjacentTriangleCount;
1843 }
1844 }
1845 }
1846 }
1847
1848 Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1849 return adjacentTriangleCount;
1850};
1851
1852/** Checks whether the triangle consisting of the three points is already present.
1853 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1854 * lines. If any of the three edges already has two triangles attached, false is
1855 * returned.
1856 * \param *out output stream for debugging
1857 * \param *Candidates endpoints of the triangle candidate
1858 * \return NULL - none found or pointer to triangle
1859 */
1860class BoundaryTriangleSet * Tesselation::GetPresentTriangle(TesselPoint *Candidates[3])
1861{
1862 Info FunctionInfo(__func__);
1863 class BoundaryTriangleSet *triangle = NULL;
1864 class BoundaryPointSet *Points[3];
1865
1866 // builds a triangle point set (Points) of the end points
1867 for (int i = 0; i < 3; i++) {
1868 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1869 if (FindPoint != PointsOnBoundary.end()) {
1870 Points[i] = FindPoint->second;
1871 } else {
1872 Points[i] = NULL;
1873 }
1874 }
1875
1876 // checks lines between the points in the Points for their adjacent triangles
1877 for (int i = 0; i < 3; i++) {
1878 if (Points[i] != NULL) {
1879 for (int j = i; j < 3; j++) {
1880 if (Points[j] != NULL) {
1881 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1882 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1883 TriangleMap *triangles = &FindLine->second->triangles;
1884 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1885 if (FindTriangle->second->IsPresentTupel(Points)) {
1886 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
1887 triangle = FindTriangle->second;
1888 }
1889 }
1890 }
1891 // Only one of the triangle lines must be considered for the triangle count.
1892 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1893 //return adjacentTriangleCount;
1894 }
1895 }
1896 }
1897 }
1898
1899 return triangle;
1900};
1901
1902
1903/** Finds the starting triangle for FindNonConvexBorder().
1904 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
1905 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
1906 * point are called.
1907 * \param *out output stream for debugging
1908 * \param RADIUS radius of virtual rolling sphere
1909 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1910 */
1911void Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
1912{
1913 Info FunctionInfo(__func__);
1914 int i = 0;
1915 TesselPoint* MaxPoint[NDIM];
1916 TesselPoint* Temporary;
1917 double maxCoordinate[NDIM];
1918 BoundaryLineSet BaseLine;
1919 Vector helper;
1920 Vector Chord;
1921 Vector SearchDirection;
1922 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
1923 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
1924 Vector SphereCenter;
1925 Vector NormalVector;
1926
1927 NormalVector.Zero();
1928
1929 for (i = 0; i < 3; i++) {
1930 MaxPoint[i] = NULL;
1931 maxCoordinate[i] = -1;
1932 }
1933
1934 // 1. searching topmost point with respect to each axis
1935 for (int i=0;i<NDIM;i++) { // each axis
1936 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1937 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1938 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1939 const LinkedNodes *List = LC->GetCurrentCell();
1940 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1941 if (List != NULL) {
1942 for (LinkedNodes::const_iterator Runner = List->begin();Runner != List->end();Runner++) {
1943 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
1944 Log() << Verbose(1) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1945 maxCoordinate[i] = (*Runner)->node->x[i];
1946 MaxPoint[i] = (*Runner);
1947 }
1948 }
1949 } else {
1950 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1951 }
1952 }
1953 }
1954
1955 Log() << Verbose(1) << "Found maximum coordinates: ";
1956 for (int i=0;i<NDIM;i++)
1957 Log() << Verbose(0) << i << ": " << *MaxPoint[i] << "\t";
1958 Log() << Verbose(0) << endl;
1959
1960 BTS = NULL;
1961 for (int k=0;k<NDIM;k++) {
1962 NormalVector.Zero();
1963 NormalVector.x[k] = 1.;
1964 BaseLine.endpoints[0] = new BoundaryPointSet(MaxPoint[k]);
1965 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
1966
1967 double ShortestAngle;
1968 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.
1969
1970 FindSecondPointForTesselation(BaseLine.endpoints[0]->node, NormalVector, Temporary, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1971 if (Temporary == NULL) // have we found a second point?
1972 continue;
1973 BaseLine.endpoints[1] = new BoundaryPointSet(Temporary);
1974
1975 // construct center of circle
1976 CircleCenter.CopyVector(BaseLine.endpoints[0]->node->node);
1977 CircleCenter.AddVector(BaseLine.endpoints[1]->node->node);
1978 CircleCenter.Scale(0.5);
1979
1980 // construct normal vector of circle
1981 CirclePlaneNormal.CopyVector(BaseLine.endpoints[0]->node->node);
1982 CirclePlaneNormal.SubtractVector(BaseLine.endpoints[1]->node->node);
1983
1984 double radius = CirclePlaneNormal.NormSquared();
1985 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1986
1987 NormalVector.ProjectOntoPlane(&CirclePlaneNormal);
1988 NormalVector.Normalize();
1989 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1990
1991 SphereCenter.CopyVector(&NormalVector);
1992 SphereCenter.Scale(CircleRadius);
1993 SphereCenter.AddVector(&CircleCenter);
1994 // Now, NormalVector and SphereCenter are two orthonormalized vectors in the plane defined by CirclePlaneNormal (not normalized)
1995
1996 // look in one direction of baseline for initial candidate
1997 SearchDirection.MakeNormalVector(&CirclePlaneNormal, &NormalVector); // whether we look "left" first or "right" first is not important ...
1998
1999 // adding point 1 and point 2 and add the line between them
2000 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
2001 Log() << Verbose(0) << "Found second point is at " << *BaseLine.endpoints[1]->node << ".\n";
2002
2003 //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << helper << ".\n";
2004 CandidateForTesselation OptCandidates(&BaseLine);
2005 FindThirdPointForTesselation(NormalVector, SearchDirection, SphereCenter, OptCandidates, NULL, RADIUS, LC);
2006 Log() << Verbose(0) << "List of third Points is:" << endl;
2007 for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); it++) {
2008 Log() << Verbose(0) << " " << *(*it) << endl;
2009 }
2010
2011 BTS = NULL;
2012 AddCandidateTriangle(OptCandidates);
2013// delete(BaseLine.endpoints[0]);
2014// delete(BaseLine.endpoints[1]);
2015
2016 if (BTS != NULL) // we have created one starting triangle
2017 break;
2018 else {
2019 // remove all candidates from the list and then the list itself
2020 OptCandidates.pointlist.clear();
2021 }
2022 }
2023};
2024
2025/** Checks for a given baseline and a third point candidate whether baselines of the found triangle don't have even better candidates.
2026 * This is supposed to prevent early closing of the tesselation.
2027 * \param CandidateLine CandidateForTesselation with baseline and shortestangle , i.e. not \a *OptCandidate
2028 * \param *ThirdNode third point in triangle, not in BoundaryLineSet::endpoints
2029 * \param RADIUS radius of sphere
2030 * \param *LC LinkedCell structure
2031 * \return true - there is a better candidate (smaller angle than \a ShortestAngle), false - no better TesselPoint candidate found
2032 */
2033//bool Tesselation::HasOtherBaselineBetterCandidate(CandidateForTesselation &CandidateLine, const TesselPoint * const ThirdNode, double RADIUS, const LinkedCell * const LC) const
2034//{
2035// Info FunctionInfo(__func__);
2036// bool result = false;
2037// Vector CircleCenter;
2038// Vector CirclePlaneNormal;
2039// Vector OldSphereCenter;
2040// Vector SearchDirection;
2041// Vector helper;
2042// TesselPoint *OtherOptCandidate = NULL;
2043// double OtherShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2044// double radius, CircleRadius;
2045// BoundaryLineSet *Line = NULL;
2046// BoundaryTriangleSet *T = NULL;
2047//
2048// // check both other lines
2049// PointMap::const_iterator FindPoint = PointsOnBoundary.find(ThirdNode->nr);
2050// if (FindPoint != PointsOnBoundary.end()) {
2051// for (int i=0;i<2;i++) {
2052// LineMap::const_iterator FindLine = (FindPoint->second)->lines.find(BaseRay->endpoints[0]->node->nr);
2053// if (FindLine != (FindPoint->second)->lines.end()) {
2054// Line = FindLine->second;
2055// Log() << Verbose(0) << "Found line " << *Line << "." << endl;
2056// if (Line->triangles.size() == 1) {
2057// T = Line->triangles.begin()->second;
2058// // construct center of circle
2059// CircleCenter.CopyVector(Line->endpoints[0]->node->node);
2060// CircleCenter.AddVector(Line->endpoints[1]->node->node);
2061// CircleCenter.Scale(0.5);
2062//
2063// // construct normal vector of circle
2064// CirclePlaneNormal.CopyVector(Line->endpoints[0]->node->node);
2065// CirclePlaneNormal.SubtractVector(Line->endpoints[1]->node->node);
2066//
2067// // calculate squared radius of circle
2068// radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2069// if (radius/4. < RADIUS*RADIUS) {
2070// CircleRadius = RADIUS*RADIUS - radius/4.;
2071// CirclePlaneNormal.Normalize();
2072// //Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2073//
2074// // construct old center
2075// GetCenterofCircumcircle(&OldSphereCenter, *T->endpoints[0]->node->node, *T->endpoints[1]->node->node, *T->endpoints[2]->node->node);
2076// helper.CopyVector(&T->NormalVector); // normal vector ensures that this is correct center of the two possible ones
2077// radius = Line->endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
2078// helper.Scale(sqrt(RADIUS*RADIUS - radius));
2079// OldSphereCenter.AddVector(&helper);
2080// OldSphereCenter.SubtractVector(&CircleCenter);
2081// //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2082//
2083// // construct SearchDirection
2084// SearchDirection.MakeNormalVector(&T->NormalVector, &CirclePlaneNormal);
2085// helper.CopyVector(Line->endpoints[0]->node->node);
2086// helper.SubtractVector(ThirdNode->node);
2087// if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2088// SearchDirection.Scale(-1.);
2089// SearchDirection.ProjectOntoPlane(&OldSphereCenter);
2090// SearchDirection.Normalize();
2091// Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2092// if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2093// // rotated the wrong way!
2094// eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2095// }
2096//
2097// // add third point
2098// FindThirdPointForTesselation(T->NormalVector, SearchDirection, OldSphereCenter, OptCandidates, ThirdNode, RADIUS, LC);
2099// for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); ++it) {
2100// if (((*it) == BaseRay->endpoints[0]->node) || ((*it) == BaseRay->endpoints[1]->node)) // skip if it's the same triangle than suggested
2101// continue;
2102// Log() << Verbose(0) << " Third point candidate is " << (*it)
2103// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2104// Log() << Verbose(0) << " Baseline is " << *BaseRay << endl;
2105//
2106// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2107// TesselPoint *PointCandidates[3];
2108// PointCandidates[0] = (*it);
2109// PointCandidates[1] = BaseRay->endpoints[0]->node;
2110// PointCandidates[2] = BaseRay->endpoints[1]->node;
2111// bool check=false;
2112// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2113// // If there is no triangle, add it regularly.
2114// if (existentTrianglesCount == 0) {
2115// SetTesselationPoint((*it), 0);
2116// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2117// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2118//
2119// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2120// OtherOptCandidate = (*it);
2121// check = true;
2122// }
2123// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2124// SetTesselationPoint((*it), 0);
2125// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2126// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2127//
2128// // 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)
2129// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2130// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS)) {
2131// OtherOptCandidate = (*it);
2132// check = true;
2133// }
2134// }
2135//
2136// if (check) {
2137// if (ShortestAngle > OtherShortestAngle) {
2138// Log() << Verbose(0) << "There is a better candidate than " << *ThirdNode << " with " << ShortestAngle << " from baseline " << *Line << ": " << *OtherOptCandidate << " with " << OtherShortestAngle << "." << endl;
2139// result = true;
2140// break;
2141// }
2142// }
2143// }
2144// delete(OptCandidates);
2145// if (result)
2146// break;
2147// } else {
2148// Log() << Verbose(0) << "Circumcircle for base line " << *Line << " and base triangle " << T << " is too big!" << endl;
2149// }
2150// } else {
2151// eLog() << Verbose(2) << "Baseline is connected to two triangles already?" << endl;
2152// }
2153// } else {
2154// Log() << Verbose(1) << "No present baseline between " << BaseRay->endpoints[0] << " and candidate " << *ThirdNode << "." << endl;
2155// }
2156// }
2157// } else {
2158// eLog() << Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl;
2159// }
2160//
2161// return result;
2162//};
2163
2164/** This function finds a triangle to a line, adjacent to an existing one.
2165 * @param out output stream for debugging
2166 * @param CandidateLine current cadndiate baseline to search from
2167 * @param T current triangle which \a Line is edge of
2168 * @param RADIUS radius of the rolling ball
2169 * @param N number of found triangles
2170 * @param *LC LinkedCell structure with neighbouring points
2171 */
2172bool Tesselation::FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
2173{
2174 Info FunctionInfo(__func__);
2175 bool result = true;
2176
2177 Vector CircleCenter;
2178 Vector CirclePlaneNormal;
2179 Vector RelativeSphereCenter;
2180 Vector SearchDirection;
2181 Vector helper;
2182 TesselPoint *ThirdNode = NULL;
2183 LineMap::iterator testline;
2184 double radius, CircleRadius;
2185
2186 for (int i=0;i<3;i++)
2187 if ((T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[0]->node) && (T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[1]->node)) {
2188 ThirdNode = T.endpoints[i]->node;
2189 break;
2190 }
2191 Log() << Verbose(0) << "Current baseline is " << *CandidateLine.BaseLine << " with ThirdNode " << *ThirdNode << " of triangle " << T << "." << endl;
2192
2193 // construct center of circle
2194 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2195 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2196 CircleCenter.Scale(0.5);
2197
2198 // construct normal vector of circle
2199 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2200 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2201
2202 // calculate squared radius of circle
2203 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2204 if (radius/4. < RADIUS*RADIUS) {
2205 // construct relative sphere center with now known CircleCenter
2206 RelativeSphereCenter.CopyVector(&T.SphereCenter);
2207 RelativeSphereCenter.SubtractVector(&CircleCenter);
2208
2209 CircleRadius = RADIUS*RADIUS - radius/4.;
2210 CirclePlaneNormal.Normalize();
2211 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2212
2213 Log() << Verbose(1) << "INFO: OldSphereCenter is at " << T.SphereCenter << "." << endl;
2214
2215 // construct SearchDirection and an "outward pointer"
2216 SearchDirection.MakeNormalVector(&RelativeSphereCenter, &CirclePlaneNormal);
2217 helper.CopyVector(&CircleCenter);
2218 helper.SubtractVector(ThirdNode->node);
2219 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2220 SearchDirection.Scale(-1.);
2221 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2222 if (fabs(RelativeSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2223 // rotated the wrong way!
2224 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2225 }
2226
2227 // add third point
2228 FindThirdPointForTesselation(T.NormalVector, SearchDirection, T.SphereCenter, CandidateLine, ThirdNode, RADIUS, LC);
2229
2230 } else {
2231 Log() << Verbose(0) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and base triangle " << T << " is too big!" << endl;
2232 }
2233
2234 if (CandidateLine.pointlist.empty()) {
2235 eLog() << Verbose(2) << "Could not find a suitable candidate." << endl;
2236 return false;
2237 }
2238 Log() << Verbose(0) << "Third Points are: " << endl;
2239 for (TesselPointList::iterator it = CandidateLine.pointlist.begin(); it != CandidateLine.pointlist.end(); ++it) {
2240 Log() << Verbose(0) << " " << *(*it) << endl;
2241 }
2242
2243 return true;
2244
2245// BoundaryLineSet *BaseRay = CandidateLine.BaseLine;
2246// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2247// Log() << Verbose(0) << "Third point candidate is " << *(*it)->point
2248// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2249// Log() << Verbose(0) << "Baseline is " << *BaseRay << endl;
2250//
2251// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2252// TesselPoint *PointCandidates[3];
2253// PointCandidates[0] = (*it)->point;
2254// PointCandidates[1] = BaseRay->endpoints[0]->node;
2255// PointCandidates[2] = BaseRay->endpoints[1]->node;
2256// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2257//
2258// BTS = NULL;
2259// // check for present edges and whether we reach better candidates from them
2260// //if (HasOtherBaselineBetterCandidate(BaseRay, (*it)->point, ShortestAngle, RADIUS, LC) ) {
2261// if (0) {
2262// result = false;
2263// break;
2264// } else {
2265// // If there is no triangle, add it regularly.
2266// if (existentTrianglesCount == 0) {
2267// AddTesselationPoint((*it)->point, 0);
2268// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2269// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2270//
2271// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2272// CandidateLine.point = (*it)->point;
2273// CandidateLine.OptCenter.CopyVector(&((*it)->OptCenter));
2274// CandidateLine.OtherOptCenter.CopyVector(&((*it)->OtherOptCenter));
2275// CandidateLine.ShortestAngle = ShortestAngle;
2276// } else {
2277//// eLog() << Verbose(1) << "This triangle consisting of ";
2278//// Log() << Verbose(0) << *(*it)->point << ", ";
2279//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2280//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2281//// Log() << Verbose(0) << "exists and is not added, as it 0x80000000006fc150(does not seem helpful!" << endl;
2282// result = false;
2283// }
2284// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2285// AddTesselationPoint((*it)->point, 0);
2286// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2287// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2288//
2289// // 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)
2290// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2291// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS) || CandidateLine.BaseLine->skipped) {
2292// CandidateLine.point = (*it)->point;
2293// CandidateLine.OptCenter.CopyVector(&(*it)->OptCenter);
2294// CandidateLine.OtherOptCenter.CopyVector(&(*it)->OtherOptCenter);
2295// CandidateLine.ShortestAngle = ShortestAngle+2.*M_PI;
2296//
2297// } else {
2298//// eLog() << Verbose(1) << "This triangle consisting of " << *(*it)->point << ", " << *BaseRay->endpoints[0]->node << " and " << *BaseRay->endpoints[1]->node << " " << "exists and is not added, as it does not seem helpful!" << endl;
2299// result = false;
2300// }
2301// } else {
2302//// Log() << Verbose(1) << "This triangle consisting of ";
2303//// Log() << Verbose(0) << *(*it)->point << ", ";
2304//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2305//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2306//// Log() << Verbose(0) << "is invalid!" << endl;
2307// result = false;
2308// }
2309// }
2310//
2311// // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
2312// BaseRay = BLS[0];
2313// if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
2314// eLog() << Verbose(1) << "Triangle " << *BTS << " has zero normal vector!" << endl;
2315// exit(255);
2316// }
2317//
2318// }
2319//
2320// // remove all candidates from the list and then the list itself
2321// class CandidateForTesselation *remover = NULL;
2322// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2323// remover = *it;
2324// delete(remover);
2325// }
2326// delete(OptCandidates);
2327 return result;
2328};
2329
2330/** Adds the present line and candidate point from \a &CandidateLine to the Tesselation.
2331 * \param CandidateLine triangle to add
2332 * \NOTE we need the copy operator here as the original CandidateForTesselation is removed in AddTesselationLine()
2333 */
2334void Tesselation::AddCandidateTriangle(CandidateForTesselation CandidateLine)
2335{
2336 Info FunctionInfo(__func__);
2337 Vector Center;
2338 TesselPoint * const TurningPoint = CandidateLine.BaseLine->endpoints[0]->node;
2339
2340 // fill the set of neighbours
2341 TesselPointSet SetOfNeighbours;
2342 SetOfNeighbours.insert(CandidateLine.BaseLine->endpoints[1]->node);
2343 for (TesselPointList::iterator Runner = CandidateLine.pointlist.begin(); Runner != CandidateLine.pointlist.end(); Runner++)
2344 SetOfNeighbours.insert(*Runner);
2345 TesselPointList *connectedClosestPoints = GetCircleOfSetOfPoints(&SetOfNeighbours, TurningPoint, CandidateLine.BaseLine->endpoints[1]->node->node);
2346
2347 // go through all angle-sorted candidates (in degenerate n-nodes case we may have to add multiple triangles)
2348 Log() << Verbose(0) << "List of Candidates for Turning Point: " << *TurningPoint << "." << endl;
2349 for (TesselPointList::iterator TesselRunner = connectedClosestPoints->begin(); TesselRunner != connectedClosestPoints->end(); ++TesselRunner)
2350 Log() << Verbose(0) << **TesselRunner << endl;
2351 TesselPointList::iterator Runner = connectedClosestPoints->begin();
2352 TesselPointList::iterator Sprinter = Runner;
2353 Sprinter++;
2354 while(Sprinter != connectedClosestPoints->end()) {
2355 // add the points
2356 AddTesselationPoint(TurningPoint, 0);
2357 AddTesselationPoint((*Runner), 1);
2358 AddTesselationPoint((*Sprinter), 2);
2359
2360 // add the lines
2361 AddTesselationLine(TPS[0], TPS[1], 0);
2362 AddTesselationLine(TPS[0], TPS[2], 1);
2363 AddTesselationLine(TPS[1], TPS[2], 2);
2364
2365 // add the triangles
2366 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2367 AddTesselationTriangle();
2368 BTS->GetCenter(&Center);
2369 Center.SubtractVector(&CandidateLine.OptCenter);
2370 BTS->SphereCenter.CopyVector(&CandidateLine.OptCenter);
2371 BTS->GetNormalVector(Center);
2372
2373 Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector << "." << endl;
2374 Runner = Sprinter;
2375 Sprinter++;
2376 Log() << Verbose(0) << "Current Runner is " << **Runner << "." << endl;
2377 if (Sprinter != connectedClosestPoints->end())
2378 Log() << Verbose(0) << " There are still more triangles to add." << endl;
2379 }
2380 delete(connectedClosestPoints);
2381};
2382
2383/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
2384 * We look whether the closest point on \a *Base with respect to the other baseline is outside
2385 * of the segment formed by both endpoints (concave) or not (convex).
2386 * \param *out output stream for debugging
2387 * \param *Base line to be flipped
2388 * \return NULL - convex, otherwise endpoint that makes it concave
2389 */
2390class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
2391{
2392 Info FunctionInfo(__func__);
2393 class BoundaryPointSet *Spot = NULL;
2394 class BoundaryLineSet *OtherBase;
2395 Vector *ClosestPoint;
2396
2397 int m=0;
2398 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2399 for (int j=0;j<3;j++) // all of their endpoints and baselines
2400 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2401 BPS[m++] = runner->second->endpoints[j];
2402 OtherBase = new class BoundaryLineSet(BPS,-1);
2403
2404 Log() << Verbose(1) << "INFO: Current base line is " << *Base << "." << endl;
2405 Log() << Verbose(1) << "INFO: Other base line is " << *OtherBase << "." << endl;
2406
2407 // get the closest point on each line to the other line
2408 ClosestPoint = GetClosestPointBetweenLine(Base, OtherBase);
2409
2410 // delete the temporary other base line
2411 delete(OtherBase);
2412
2413 // get the distance vector from Base line to OtherBase line
2414 Vector DistanceToIntersection[2], BaseLine;
2415 double distance[2];
2416 BaseLine.CopyVector(Base->endpoints[1]->node->node);
2417 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
2418 for (int i=0;i<2;i++) {
2419 DistanceToIntersection[i].CopyVector(ClosestPoint);
2420 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
2421 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
2422 }
2423 delete(ClosestPoint);
2424 if ((distance[0] * distance[1]) > 0) { // have same sign?
2425 Log() << Verbose(1) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
2426 if (distance[0] < distance[1]) {
2427 Spot = Base->endpoints[0];
2428 } else {
2429 Spot = Base->endpoints[1];
2430 }
2431 return Spot;
2432 } else { // different sign, i.e. we are in between
2433 Log() << Verbose(0) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
2434 return NULL;
2435 }
2436
2437};
2438
2439void Tesselation::PrintAllBoundaryPoints(ofstream *out) const
2440{
2441 Info FunctionInfo(__func__);
2442 // print all lines
2443 Log() << Verbose(0) << "Printing all boundary points for debugging:" << endl;
2444 for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
2445 Log() << Verbose(0) << *(PointRunner->second) << endl;
2446};
2447
2448void Tesselation::PrintAllBoundaryLines(ofstream *out) const
2449{
2450 Info FunctionInfo(__func__);
2451 // print all lines
2452 Log() << Verbose(0) << "Printing all boundary lines for debugging:" << endl;
2453 for (LineMap::const_iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
2454 Log() << Verbose(0) << *(LineRunner->second) << endl;
2455};
2456
2457void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
2458{
2459 Info FunctionInfo(__func__);
2460 // print all triangles
2461 Log() << Verbose(0) << "Printing all boundary triangles for debugging:" << endl;
2462 for (TriangleMap::const_iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
2463 Log() << Verbose(0) << *(TriangleRunner->second) << endl;
2464};
2465
2466/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
2467 * \param *out output stream for debugging
2468 * \param *Base line to be flipped
2469 * \return volume change due to flipping (0 - then no flipped occured)
2470 */
2471double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
2472{
2473 Info FunctionInfo(__func__);
2474 class BoundaryLineSet *OtherBase;
2475 Vector *ClosestPoint[2];
2476 double volume;
2477
2478 int m=0;
2479 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2480 for (int j=0;j<3;j++) // all of their endpoints and baselines
2481 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2482 BPS[m++] = runner->second->endpoints[j];
2483 OtherBase = new class BoundaryLineSet(BPS,-1);
2484
2485 Log() << Verbose(0) << "INFO: Current base line is " << *Base << "." << endl;
2486 Log() << Verbose(0) << "INFO: Other base line is " << *OtherBase << "." << endl;
2487
2488 // get the closest point on each line to the other line
2489 ClosestPoint[0] = GetClosestPointBetweenLine(Base, OtherBase);
2490 ClosestPoint[1] = GetClosestPointBetweenLine(OtherBase, Base);
2491
2492 // get the distance vector from Base line to OtherBase line
2493 Vector Distance;
2494 Distance.CopyVector(ClosestPoint[1]);
2495 Distance.SubtractVector(ClosestPoint[0]);
2496
2497 // calculate volume
2498 volume = CalculateVolumeofGeneralTetraeder(*Base->endpoints[1]->node->node, *OtherBase->endpoints[0]->node->node, *OtherBase->endpoints[1]->node->node, *Base->endpoints[0]->node->node);
2499
2500 // delete the temporary other base line and the closest points
2501 delete(ClosestPoint[0]);
2502 delete(ClosestPoint[1]);
2503 delete(OtherBase);
2504
2505 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2506 Log() << Verbose(0) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2507 return false;
2508 } else { // check for sign against BaseLineNormal
2509 Vector BaseLineNormal;
2510 BaseLineNormal.Zero();
2511 if (Base->triangles.size() < 2) {
2512 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2513 return 0.;
2514 }
2515 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2516 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2517 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2518 }
2519 BaseLineNormal.Scale(1./2.);
2520
2521 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2522 Log() << Verbose(0) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2523 // calculate volume summand as a general tetraeder
2524 return volume;
2525 } else { // Base higher than OtherBase -> do nothing
2526 Log() << Verbose(0) << "REJECT: Base line is higher: Nothing to do." << endl;
2527 return 0.;
2528 }
2529 }
2530};
2531
2532/** For a given baseline and its two connected triangles, flips the baseline.
2533 * I.e. we create the new baseline between the other two endpoints of these four
2534 * endpoints and reconstruct the two triangles accordingly.
2535 * \param *out output stream for debugging
2536 * \param *Base line to be flipped
2537 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2538 */
2539class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
2540{
2541 Info FunctionInfo(__func__);
2542 class BoundaryLineSet *OldLines[4], *NewLine;
2543 class BoundaryPointSet *OldPoints[2];
2544 Vector BaseLineNormal;
2545 int OldTriangleNrs[2], OldBaseLineNr;
2546 int i,m;
2547
2548 // calculate NormalVector for later use
2549 BaseLineNormal.Zero();
2550 if (Base->triangles.size() < 2) {
2551 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2552 return NULL;
2553 }
2554 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2555 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2556 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2557 }
2558 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2559
2560 // get the two triangles
2561 // gather four endpoints and four lines
2562 for (int j=0;j<4;j++)
2563 OldLines[j] = NULL;
2564 for (int j=0;j<2;j++)
2565 OldPoints[j] = NULL;
2566 i=0;
2567 m=0;
2568 Log() << Verbose(0) << "The four old lines are: ";
2569 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2570 for (int j=0;j<3;j++) // all of their endpoints and baselines
2571 if (runner->second->lines[j] != Base) { // pick not the central baseline
2572 OldLines[i++] = runner->second->lines[j];
2573 Log() << Verbose(0) << *runner->second->lines[j] << "\t";
2574 }
2575 Log() << Verbose(0) << endl;
2576 Log() << Verbose(0) << "The two old points are: ";
2577 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2578 for (int j=0;j<3;j++) // all of their endpoints and baselines
2579 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2580 OldPoints[m++] = runner->second->endpoints[j];
2581 Log() << Verbose(0) << *runner->second->endpoints[j] << "\t";
2582 }
2583 Log() << Verbose(0) << endl;
2584
2585 // check whether everything is in place to create new lines and triangles
2586 if (i<4) {
2587 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2588 return NULL;
2589 }
2590 for (int j=0;j<4;j++)
2591 if (OldLines[j] == NULL) {
2592 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2593 return NULL;
2594 }
2595 for (int j=0;j<2;j++)
2596 if (OldPoints[j] == NULL) {
2597 eLog() << Verbose(1) << "We have not gathered enough endpoints!" << endl;
2598 return NULL;
2599 }
2600
2601 // remove triangles and baseline removes itself
2602 Log() << Verbose(0) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2603 OldBaseLineNr = Base->Nr;
2604 m=0;
2605 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2606 Log() << Verbose(0) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
2607 OldTriangleNrs[m++] = runner->second->Nr;
2608 RemoveTesselationTriangle(runner->second);
2609 }
2610
2611 // construct new baseline (with same number as old one)
2612 BPS[0] = OldPoints[0];
2613 BPS[1] = OldPoints[1];
2614 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2615 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2616 Log() << Verbose(0) << "INFO: Created new baseline " << *NewLine << "." << endl;
2617
2618 // construct new triangles with flipped baseline
2619 i=-1;
2620 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2621 i=2;
2622 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2623 i=3;
2624 if (i!=-1) {
2625 BLS[0] = OldLines[0];
2626 BLS[1] = OldLines[i];
2627 BLS[2] = NewLine;
2628 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2629 BTS->GetNormalVector(BaseLineNormal);
2630 AddTesselationTriangle(OldTriangleNrs[0]);
2631 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
2632
2633 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
2634 BLS[1] = OldLines[1];
2635 BLS[2] = NewLine;
2636 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2637 BTS->GetNormalVector(BaseLineNormal);
2638 AddTesselationTriangle(OldTriangleNrs[1]);
2639 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
2640 } else {
2641 eLog() << Verbose(0) << "The four old lines do not connect, something's utterly wrong here!" << endl;
2642 return NULL;
2643 }
2644
2645 return NewLine;
2646};
2647
2648
2649/** Finds the second point of starting triangle.
2650 * \param *a first node
2651 * \param Oben vector indicating the outside
2652 * \param OptCandidate reference to recommended candidate on return
2653 * \param Storage[3] array storing angles and other candidate information
2654 * \param RADIUS radius of virtual sphere
2655 * \param *LC LinkedCell structure with neighbouring points
2656 */
2657void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC)
2658{
2659 Info FunctionInfo(__func__);
2660 Vector AngleCheck;
2661 class TesselPoint* Candidate = NULL;
2662 double norm = -1.;
2663 double angle = 0.;
2664 int N[NDIM];
2665 int Nlower[NDIM];
2666 int Nupper[NDIM];
2667
2668 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2669 for(int i=0;i<NDIM;i++) // store indices of this cell
2670 N[i] = LC->n[i];
2671 } else {
2672 eLog() << Verbose(1) << "Point " << *a << " is not found in cell " << LC->index << "." << endl;
2673 return;
2674 }
2675 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2676 for (int i=0;i<NDIM;i++) {
2677 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2678 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2679 }
2680 Log() << Verbose(0) << "LC Intervals from [" << N[0] << "<->" << LC->N[0] << ", " << N[1] << "<->" << LC->N[1] << ", " << N[2] << "<->" << LC->N[2] << "] :"
2681 << " [" << Nlower[0] << "," << Nupper[0] << "], " << " [" << Nlower[1] << "," << Nupper[1] << "], " << " [" << Nlower[2] << "," << Nupper[2] << "], " << endl;
2682
2683 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2684 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2685 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2686 const LinkedNodes *List = LC->GetCurrentCell();
2687 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2688 if (List != NULL) {
2689 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2690 Candidate = (*Runner);
2691 // check if we only have one unique point yet ...
2692 if (a != Candidate) {
2693 // Calculate center of the circle with radius RADIUS through points a and Candidate
2694 Vector OrthogonalizedOben, aCandidate, Center;
2695 double distance, scaleFactor;
2696
2697 OrthogonalizedOben.CopyVector(&Oben);
2698 aCandidate.CopyVector(a->node);
2699 aCandidate.SubtractVector(Candidate->node);
2700 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
2701 OrthogonalizedOben.Normalize();
2702 distance = 0.5 * aCandidate.Norm();
2703 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2704 OrthogonalizedOben.Scale(scaleFactor);
2705
2706 Center.CopyVector(Candidate->node);
2707 Center.AddVector(a->node);
2708 Center.Scale(0.5);
2709 Center.AddVector(&OrthogonalizedOben);
2710
2711 AngleCheck.CopyVector(&Center);
2712 AngleCheck.SubtractVector(a->node);
2713 norm = aCandidate.Norm();
2714 // second point shall have smallest angle with respect to Oben vector
2715 if (norm < RADIUS*2.) {
2716 angle = AngleCheck.Angle(&Oben);
2717 if (angle < Storage[0]) {
2718 //Log() << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2719 Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2720 OptCandidate = Candidate;
2721 Storage[0] = angle;
2722 //Log() << Verbose(1) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2723 } else {
2724 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
2725 }
2726 } else {
2727 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2728 }
2729 } else {
2730 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2731 }
2732 }
2733 } else {
2734 Log() << Verbose(0) << "Linked cell list is empty." << endl;
2735 }
2736 }
2737};
2738
2739
2740/** This recursive function finds a third point, to form a triangle with two given ones.
2741 * Note that this function is for the starting triangle.
2742 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2743 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2744 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2745 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2746 * us the "null" on this circle, the new center of the candidate point will be some way along this
2747 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2748 * by the normal vector of the base triangle that always points outwards by construction.
2749 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2750 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2751 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2752 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2753 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2754 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2755 * both.
2756 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2757 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2758 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2759 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2760 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2761 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2762 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2763 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2764 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2765 * @param CandidateLine CandidateForTesselation with the current base line and list of candidates and ShortestAngle
2766 * @param ThirdNode third point to avoid in search
2767 * @param RADIUS radius of sphere
2768 * @param *LC LinkedCell structure with neighbouring points
2769 */
2770void Tesselation::FindThirdPointForTesselation(Vector &NormalVector, Vector &SearchDirection, Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class TesselPoint * const ThirdNode, const double RADIUS, const LinkedCell *LC) const
2771{
2772 Info FunctionInfo(__func__);
2773 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2774 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2775 Vector SphereCenter;
2776 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2777 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2778 Vector NewNormalVector; // normal vector of the Candidate's triangle
2779 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2780 Vector RelativeOldSphereCenter;
2781 Vector NewPlaneCenter;
2782 double CircleRadius; // radius of this circle
2783 double radius;
2784 double otherradius;
2785 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2786 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2787 TesselPoint *Candidate = NULL;
2788
2789 Log() << Verbose(1) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
2790
2791 // construct center of circle
2792 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2793 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2794 CircleCenter.Scale(0.5);
2795
2796 // construct normal vector of circle
2797 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2798 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2799
2800 RelativeOldSphereCenter.CopyVector(&OldSphereCenter);
2801 RelativeOldSphereCenter.SubtractVector(&CircleCenter);
2802
2803 // calculate squared radius TesselPoint *ThirdNode,f circle
2804 radius = CirclePlaneNormal.NormSquared()/4.;
2805 if (radius < RADIUS*RADIUS) {
2806 CircleRadius = RADIUS*RADIUS - radius;
2807 CirclePlaneNormal.Normalize();
2808 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2809
2810 // test whether old center is on the band's plane
2811 if (fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
2812 eLog() << Verbose(1) << "Something's very wrong here: RelativeOldSphereCenter is not on the band's plane as desired by " << fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
2813 RelativeOldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
2814 }
2815 radius = RelativeOldSphereCenter.NormSquared();
2816 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2817 Log() << Verbose(1) << "INFO: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << "." << endl;
2818
2819 // check SearchDirection
2820 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2821 if (fabs(RelativeOldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2822 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
2823 }
2824
2825 // get cell for the starting point
2826 if (LC->SetIndexToVector(&CircleCenter)) {
2827 for(int i=0;i<NDIM;i++) // store indices of this cell
2828 N[i] = LC->n[i];
2829 //Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2830 } else {
2831 eLog() << Verbose(1) << "Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
2832 return;
2833 }
2834 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2835 //Log() << Verbose(1) << "LC Intervals:";
2836 for (int i=0;i<NDIM;i++) {
2837 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2838 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2839 //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2840 }
2841 //Log() << Verbose(0) << endl;
2842 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2843 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2844 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2845 const LinkedNodes *List = LC->GetCurrentCell();
2846 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2847 if (List != NULL) {
2848 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2849 Candidate = (*Runner);
2850
2851 // check for three unique points
2852 Log() << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " for BaseLine " << *CandidateLine.BaseLine << " with OldSphereCenter " << OldSphereCenter << "." << endl;
2853 if ((Candidate != CandidateLine.BaseLine->endpoints[0]->node) && (Candidate != CandidateLine.BaseLine->endpoints[1]->node) ){
2854
2855 // find center on the plane
2856 GetCenterofCircumcircle(&NewPlaneCenter, *CandidateLine.BaseLine->endpoints[0]->node->node, *CandidateLine.BaseLine->endpoints[1]->node->node, *Candidate->node);
2857 Log() << Verbose(1) << "INFO: NewPlaneCenter is " << NewPlaneCenter << "." << endl;
2858
2859 if (NewNormalVector.MakeNormalVector(CandidateLine.BaseLine->endpoints[0]->node->node, CandidateLine.BaseLine->endpoints[1]->node->node, Candidate->node)
2860 && (fabs(NewNormalVector.NormSquared()) > HULLEPSILON)
2861 ) {
2862 Log() << Verbose(1) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2863 radius = CandidateLine.BaseLine->endpoints[0]->node->node->DistanceSquared(&NewPlaneCenter);
2864 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2865 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2866 Log() << Verbose(1) << "INFO: Radius of CircumCenterCircle is " << radius << "." << endl;
2867 if (radius < RADIUS*RADIUS) {
2868 otherradius = CandidateLine.BaseLine->endpoints[1]->node->node->DistanceSquared(&NewPlaneCenter);
2869 if (fabs(radius - otherradius) > HULLEPSILON) {
2870 eLog() << Verbose(1) << "Distance to center of circumcircle is not the same from each corner of the triangle: " << fabs(radius-otherradius) << endl;
2871 }
2872 // construct both new centers
2873 NewSphereCenter.CopyVector(&NewPlaneCenter);
2874 OtherNewSphereCenter.CopyVector(&NewPlaneCenter);
2875 helper.CopyVector(&NewNormalVector);
2876 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2877 Log() << Verbose(2) << "INFO: Distance of NewPlaneCenter " << NewPlaneCenter << " to either NewSphereCenter is " << helper.Norm() << " of vector " << helper << " with sphere radius " << RADIUS << "." << endl;
2878 NewSphereCenter.AddVector(&helper);
2879 Log() << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
2880 // OtherNewSphereCenter is created by the same vector just in the other direction
2881 helper.Scale(-1.);
2882 OtherNewSphereCenter.AddVector(&helper);
2883 Log() << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2884
2885 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2886 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2887 alpha = min(alpha, Otheralpha);
2888
2889 // if there is a better candidate, drop the current list and add the new candidate
2890 // otherwise ignore the new candidate and keep the list
2891 if (CandidateLine.ShortestAngle > (alpha - HULLEPSILON)) {
2892 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2893 CandidateLine.OptCenter.CopyVector(&NewSphereCenter);
2894 CandidateLine.OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2895 } else {
2896 CandidateLine.OptCenter.CopyVector(&OtherNewSphereCenter);
2897 CandidateLine.OtherOptCenter.CopyVector(&NewSphereCenter);
2898 }
2899 // if there is an equal candidate, add it to the list without clearing the list
2900 if ((CandidateLine.ShortestAngle - HULLEPSILON) < alpha) {
2901 CandidateLine.pointlist.push_back(Candidate);
2902 Log() << Verbose(0) << "ACCEPT: We have found an equally good candidate: " << *(Candidate) << " with "
2903 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
2904 } else {
2905 // remove all candidates from the list and then the list itself
2906 CandidateLine.pointlist.clear();
2907 CandidateLine.pointlist.push_back(Candidate);
2908 Log() << Verbose(0) << "ACCEPT: We have found a better candidate: " << *(Candidate) << " with "
2909 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
2910 }
2911 CandidateLine.ShortestAngle = alpha;
2912 Log() << Verbose(0) << "INFO: There are " << CandidateLine.pointlist.size() << " candidates in the list now." << endl;
2913 } else {
2914 if ((Candidate != NULL) && (CandidateLine.pointlist.begin() != CandidateLine.pointlist.end())) {
2915 Log() << Verbose(1) << "REJECT: Old candidate " << *(Candidate) << " with " << CandidateLine.ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
2916 } else {
2917 Log() << Verbose(1) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2918 }
2919 }
2920 } else {
2921 Log() << Verbose(1) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
2922 }
2923 } else {
2924 Log() << Verbose(1) << "REJECT: Three points from " << *CandidateLine.BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2925 }
2926 } else {
2927 if (ThirdNode != NULL) {
2928 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2929 } else {
2930 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << "." << endl;
2931 }
2932 }
2933 }
2934 }
2935 }
2936 } else {
2937 eLog() << Verbose(1) << "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2938 }
2939 } else {
2940 if (ThirdNode != NULL)
2941 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2942 else
2943 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " is too big!" << endl;
2944 }
2945
2946 Log() << Verbose(1) << "INFO: Sorting candidate list ..." << endl;
2947 if (CandidateLine.pointlist.size() > 1) {
2948 CandidateLine.pointlist.unique();
2949 CandidateLine.pointlist.sort(); //SortCandidates);
2950 }
2951};
2952
2953/** Finds the endpoint two lines are sharing.
2954 * \param *line1 first line
2955 * \param *line2 second line
2956 * \return point which is shared or NULL if none
2957 */
2958class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
2959{
2960 Info FunctionInfo(__func__);
2961 const BoundaryLineSet * lines[2] = { line1, line2 };
2962 class BoundaryPointSet *node = NULL;
2963 PointMap OrderMap;
2964 PointTestPair OrderTest;
2965 for (int i = 0; i < 2; i++)
2966 // for both lines
2967 for (int j = 0; j < 2; j++)
2968 { // for both endpoints
2969 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
2970 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
2971 if (!OrderTest.second)
2972 { // if insertion fails, we have common endpoint
2973 node = OrderTest.first->second;
2974 Log() << Verbose(1) << "Common endpoint of lines " << *line1
2975 << " and " << *line2 << " is: " << *node << "." << endl;
2976 j = 2;
2977 i = 2;
2978 break;
2979 }
2980 }
2981 return node;
2982};
2983
2984/** Finds the boundary points that are closest to a given Vector \a *x.
2985 * \param *out output stream for debugging
2986 * \param *x Vector to look from
2987 * \return map of BoundaryPointSet of closest points sorted by squared distance or NULL.
2988 */
2989DistanceMap * Tesselation::FindClosestBoundaryPointsToVector(const Vector *x, const LinkedCell* LC) const
2990{
2991 Info FunctionInfo(__func__);
2992 PointMap::const_iterator FindPoint;
2993 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2994
2995 if (LinesOnBoundary.empty()) {
2996 eLog() << Verbose(1) << "There is no tesselation structure to compare the point with, please create one first." << endl;
2997 return NULL;
2998 }
2999
3000 // gather all points close to the desired one
3001 LC->SetIndexToVector(x); // ignore status as we calculate bounds below sensibly
3002 for(int i=0;i<NDIM;i++) // store indices of this cell
3003 N[i] = LC->n[i];
3004 Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
3005
3006 DistanceMap * points = new DistanceMap;
3007 LC->GetNeighbourBounds(Nlower, Nupper);
3008 //Log() << Verbose(1) << endl;
3009 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
3010 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
3011 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
3012 const LinkedNodes *List = LC->GetCurrentCell();
3013 //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
3014 if (List != NULL) {
3015 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
3016 FindPoint = PointsOnBoundary.find((*Runner)->nr);
3017 if (FindPoint != PointsOnBoundary.end())
3018 points->insert(DistancePair (FindPoint->second->node->node->DistanceSquared(x), FindPoint->second) );
3019 }
3020 } else {
3021 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
3022 }
3023 }
3024
3025 // check whether we found some points
3026 if (points->empty()) {
3027 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3028 delete(points);
3029 return NULL;
3030 }
3031 return points;
3032};
3033
3034/** Finds the boundary line that is closest to a given Vector \a *x.
3035 * \param *out output stream for debugging
3036 * \param *x Vector to look from
3037 * \return closest BoundaryLineSet or NULL in degenerate case.
3038 */
3039BoundaryLineSet * Tesselation::FindClosestBoundaryLineToVector(const Vector *x, const LinkedCell* LC) const
3040{
3041 Info FunctionInfo(__func__);
3042
3043 // get closest points
3044 DistanceMap * points = FindClosestBoundaryPointsToVector(x,LC);
3045 if (points == NULL) {
3046 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3047 return NULL;
3048 }
3049
3050 // for each point, check its lines, remember closest
3051 Log() << Verbose(1) << "Finding closest BoundaryLine to " << *x << " ... " << endl;
3052 BoundaryLineSet *ClosestLine = NULL;
3053 double MinDistance = -1.;
3054 Vector helper;
3055 Vector Center;
3056 Vector BaseLine;
3057 for (DistanceMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3058 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3059 // calculate closest point on line to desired point
3060 helper.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3061 helper.AddVector((LineRunner->second)->endpoints[1]->node->node);
3062 helper.Scale(0.5);
3063 Center.CopyVector(x);
3064 Center.SubtractVector(&helper);
3065 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3066 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3067 Center.ProjectOntoPlane(&BaseLine);
3068 const double distance = Center.NormSquared();
3069 if ((ClosestLine == NULL) || (distance < MinDistance)) {
3070 // additionally calculate intersection on line (whether it's on the line section or not)
3071 helper.CopyVector(x);
3072 helper.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3073 helper.SubtractVector(&Center);
3074 const double lengthA = helper.ScalarProduct(&BaseLine);
3075 helper.CopyVector(x);
3076 helper.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3077 helper.SubtractVector(&Center);
3078 const double lengthB = helper.ScalarProduct(&BaseLine);
3079 if (lengthB*lengthA < 0) { // if have different sign
3080 ClosestLine = LineRunner->second;
3081 MinDistance = distance;
3082 Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl;
3083 } else {
3084 Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl;
3085 }
3086 } else {
3087 Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl;
3088 }
3089 }
3090 }
3091 delete(points);
3092 // check whether closest line is "too close" :), then it's inside
3093 if (ClosestLine == NULL) {
3094 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3095 return NULL;
3096 }
3097 return ClosestLine;
3098};
3099
3100
3101/** Finds the triangle that is closest to a given Vector \a *x.
3102 * \param *out output stream for debugging
3103 * \param *x Vector to look from
3104 * \return BoundaryTriangleSet of nearest triangle or NULL.
3105 */
3106TriangleList * Tesselation::FindClosestTrianglesToVector(const Vector *x, const LinkedCell* LC) const
3107{
3108 Info FunctionInfo(__func__);
3109
3110 // get closest points
3111 DistanceMap * points = FindClosestBoundaryPointsToVector(x,LC);
3112 if (points == NULL) {
3113 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3114 return NULL;
3115 }
3116
3117 // for each point, check its lines, remember closest
3118 Log() << Verbose(1) << "Finding closest BoundaryTriangle to " << *x << " ... " << endl;
3119 BoundaryLineSet *ClosestLine = NULL;
3120 double MinDistance = -1.;
3121 Vector helper;
3122 Vector Center;
3123 Vector BaseLine;
3124 for (DistanceMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3125 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3126 for (TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++) {
3127 // calculate closest point on line to desired point
3128 helper.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3129 helper.AddVector((LineRunner->second)->endpoints[1]->node->node);
3130 helper.Scale(0.5);
3131 Center.CopyVector(x);
3132 Center.SubtractVector(&helper);
3133 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3134 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3135 Center.ProjectOntoPlane(&BaseLine);
3136 const double distance = Center.NormSquared();
3137 if ((ClosestLine == NULL) || (distance < MinDistance)) {
3138 // additionally calculate intersection on line (whether it's on the line section or not)
3139 helper.CopyVector(x);
3140 helper.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3141 helper.SubtractVector(&Center);
3142 const double lengthA = helper.ScalarProduct(&BaseLine);
3143 helper.CopyVector(x);
3144 helper.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3145 helper.SubtractVector(&Center);
3146 const double lengthB = helper.ScalarProduct(&BaseLine);
3147 if (lengthB*lengthA < 0) { // if have different sign
3148 ClosestLine = LineRunner->second;
3149 MinDistance = distance;
3150 Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl;
3151 } else {
3152 Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl;
3153 }
3154 } else {
3155 Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl;
3156 }
3157 }
3158 }
3159 }
3160 delete(points);
3161
3162 // check whether closest line is "too close" :), then it's inside
3163 if (ClosestLine == NULL) {
3164 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3165 return NULL;
3166 }
3167 TriangleList * candidates = new TriangleList;
3168 for (TriangleMap::iterator Runner = ClosestLine->triangles.begin(); Runner != ClosestLine->triangles.end(); Runner++) {
3169 candidates->push_back(Runner->second);
3170 }
3171 return candidates;
3172};
3173
3174/** Finds closest triangle to a point.
3175 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
3176 * \param *out output stream for debugging
3177 * \param *x Vector to look from
3178 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
3179 */
3180class BoundaryTriangleSet * Tesselation::FindClosestTriangleToVector(const Vector *x, const LinkedCell* LC) const
3181{
3182 Info FunctionInfo(__func__);
3183 class BoundaryTriangleSet *result = NULL;
3184 TriangleList *triangles = FindClosestTrianglesToVector(x, LC);
3185 TriangleList candidates;
3186 Vector Center;
3187 Vector helper;
3188
3189 if ((triangles == NULL) || (triangles->empty()))
3190 return NULL;
3191
3192 // reject all which are not closest
3193 double MinDistance = -1.;
3194 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++) {
3195 (*Runner)->GetCenter(&Center);
3196 helper.CopyVector(x);
3197 helper.SubtractVector(&Center);
3198 helper.ProjectOntoPlane(&(*Runner)->NormalVector);
3199 const double distance = helper.NormSquared();
3200 if (fabs(distance - MinDistance) < MYEPSILON) { // degenerate case, keep both
3201 candidates.push_back(*Runner);
3202 } else if (distance < MinDistance) {
3203 candidates.clear();
3204 candidates.push_back(*Runner);
3205 MinDistance = distance;
3206 }
3207 }
3208 delete(triangles);
3209 if (!candidates.empty()) {
3210 if (candidates.size() == 1) { // there is no degenerate case
3211 result = candidates.front();
3212 Log() << Verbose(1) << "Normal Vector of this triangle is " << result->NormalVector << "." << endl;
3213 } else {
3214 result = candidates.front();
3215 result->GetCenter(&Center);
3216 Center.SubtractVector(x);
3217 Log() << Verbose(1) << "Normal Vector of this front side is " << result->NormalVector << "." << endl;
3218 if (Center.ScalarProduct(&result->NormalVector) < 0) {
3219 result = candidates.back();
3220 Log() << Verbose(1) << "Normal Vector of this back side is " << result->NormalVector << "." << endl;
3221 if (Center.ScalarProduct(&result->NormalVector) < 0) {
3222 eLog() << Verbose(1) << "Front and back side yield NormalVector in wrong direction!" << endl;
3223 }
3224 }
3225 }
3226 } else {
3227 result = NULL;
3228 Log() << Verbose(0) << "No closest triangle found." << endl;
3229 }
3230 return result;
3231};
3232
3233/** Checks whether the provided Vector is within the tesselation structure.
3234 *
3235 * @param point of which to check the position
3236 * @param *LC LinkedCell structure
3237 * @param epsilon Distance of \a &Point to Center of triangle (of point outwards) is tested less against this value (standard: -MYEPSILON)
3238 *
3239 * @return true if the point is inside the tesselation structure, false otherwise
3240 */
3241bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC, const double epsilon) const
3242{
3243 Info FunctionInfo(__func__);
3244 class BoundaryTriangleSet *result = FindClosestTriangleToVector(&Point, LC);
3245 Vector Center;
3246 Vector helper;
3247
3248 if (result == NULL) {// is boundary point or only point in point cloud?
3249 Log() << Verbose(1) << Point << " is the only point in vicinity." << endl;
3250 return false;
3251 } else {
3252 Log() << Verbose(1) << "INFO: Closest triangle found is " << *result << "." << endl;
3253 }
3254
3255 result->GetCenter(&Center);
3256 Log() << Verbose(2) << "INFO: Central point of the triangle is " << Center << "." << endl;
3257 Center.SubtractVector(&Point);
3258 Log() << Verbose(2) << "INFO: Vector from point to test to center is " << Center << "." << endl;
3259 if (Center.ScalarProduct(&result->NormalVector) > -MYEPSILON) {
3260 Log() << Verbose(1) << Point << " is an inner point." << endl;
3261 return true;
3262 } else {
3263 for (int i=0;i<3;i++) {
3264 helper.CopyVector(result->endpoints[i]->node->node);
3265 helper.SubtractVector(&Point);
3266 if (Center.NormSquared() > helper.NormSquared())
3267 Center.CopyVector(&helper);
3268 }
3269 if (Center.NormSquared() < epsilon*epsilon) {
3270 Log() << Verbose(1) << Point << " is inner point, being sufficiently close (wrt " << epsilon << ") to boundary." << endl;
3271 return true;
3272 }
3273 Log() << Verbose(1) << Point << " is NOT an inner point." << endl;
3274 return false;
3275 }
3276}
3277
3278/** Checks whether the provided TesselPoint is within the tesselation structure.
3279 *
3280 * @param *Point of which to check the position
3281 * @param *LC Linked Cell structure
3282 * @param epsilon Distance of \a &Point to Center of triangle is tested greater against this value (standard: -MYEPSILON)
3283 *
3284 * @return true if the point is inside the tesselation structure, false otherwise
3285 */
3286bool Tesselation::IsInnerPoint(const TesselPoint * const Point, const LinkedCell* const LC, const double epsilon) const
3287{
3288 Info FunctionInfo(__func__);
3289 return IsInnerPoint(*(Point->node), LC, epsilon);
3290}
3291
3292/** Gets all points connected to the provided point by triangulation lines.
3293 *
3294 * @param *Point of which get all connected points
3295 *
3296 * @return set of the all points linked to the provided one
3297 */
3298TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
3299{
3300 Info FunctionInfo(__func__);
3301 TesselPointSet *connectedPoints = new TesselPointSet;
3302 class BoundaryPointSet *ReferencePoint = NULL;
3303 TesselPoint* current;
3304 bool takePoint = false;
3305
3306 // find the respective boundary point
3307 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
3308 if (PointRunner != PointsOnBoundary.end()) {
3309 ReferencePoint = PointRunner->second;
3310 } else {
3311 eLog() << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
3312 ReferencePoint = NULL;
3313 }
3314
3315 // little trick so that we look just through lines connect to the BoundaryPoint
3316 // OR fall-back to look through all lines if there is no such BoundaryPoint
3317 const LineMap *Lines;;
3318 if (ReferencePoint != NULL)
3319 Lines = &(ReferencePoint->lines);
3320 else
3321 Lines = &LinesOnBoundary;
3322 LineMap::const_iterator findLines = Lines->begin();
3323 while (findLines != Lines->end()) {
3324 takePoint = false;
3325
3326 if (findLines->second->endpoints[0]->Nr == Point->nr) {
3327 takePoint = true;
3328 current = findLines->second->endpoints[1]->node;
3329 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
3330 takePoint = true;
3331 current = findLines->second->endpoints[0]->node;
3332 }
3333
3334 if (takePoint) {
3335 Log() << Verbose(1) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
3336 connectedPoints->insert(current);
3337 }
3338
3339 findLines++;
3340 }
3341
3342 if (connectedPoints->empty()) { // if have not found any points
3343 eLog() << Verbose(1) << "We have not found any connected points to " << *Point<< "." << endl;
3344 return NULL;
3345 }
3346
3347 return connectedPoints;
3348};
3349
3350
3351/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3352 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3353 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3354 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3355 * triangle we are looking for.
3356 *
3357 * @param *out output stream for debugging
3358 * @param *SetOfNeighbours all points for which the angle should be calculated
3359 * @param *Point of which get all connected points
3360 * @param *Reference Reference vector for zero angle or NULL for no preference
3361 * @return list of the all points linked to the provided one
3362 */
3363TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3364{
3365 Info FunctionInfo(__func__);
3366 map<double, TesselPoint*> anglesOfPoints;
3367 TesselPointList *connectedCircle = new TesselPointList;
3368 Vector PlaneNormal;
3369 Vector AngleZero;
3370 Vector OrthogonalVector;
3371 Vector helper;
3372 const TesselPoint * const TrianglePoints[3] = {Point, NULL, NULL};
3373 TriangleList *triangles = NULL;
3374
3375 if (SetOfNeighbours == NULL) {
3376 eLog() << Verbose(2) << "Could not find any connected points!" << endl;
3377 delete(connectedCircle);
3378 return NULL;
3379 }
3380
3381 // calculate central point
3382 triangles = FindTriangles(TrianglePoints);
3383 if ((triangles != NULL) && (!triangles->empty())) {
3384 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
3385 PlaneNormal.AddVector(&(*Runner)->NormalVector);
3386 } else {
3387 eLog() << Verbose(0) << "Could not find any triangles for point " << *Point << "." << endl;
3388 performCriticalExit();
3389 }
3390 PlaneNormal.Scale(1.0/triangles->size());
3391 Log() << Verbose(1) << "INFO: Calculated PlaneNormal of all circle points is " << PlaneNormal << "." << endl;
3392 PlaneNormal.Normalize();
3393
3394 // construct one orthogonal vector
3395 if (Reference != NULL) {
3396 AngleZero.CopyVector(Reference);
3397 AngleZero.SubtractVector(Point->node);
3398 AngleZero.ProjectOntoPlane(&PlaneNormal);
3399 }
3400 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3401 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3402 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3403 AngleZero.SubtractVector(Point->node);
3404 AngleZero.ProjectOntoPlane(&PlaneNormal);
3405 if (AngleZero.NormSquared() < MYEPSILON) {
3406 eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
3407 performCriticalExit();
3408 }
3409 }
3410 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3411 if (AngleZero.NormSquared() > MYEPSILON)
3412 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3413 else
3414 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3415 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3416
3417 // go through all connected points and calculate angle
3418 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3419 helper.CopyVector((*listRunner)->node);
3420 helper.SubtractVector(Point->node);
3421 helper.ProjectOntoPlane(&PlaneNormal);
3422 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3423 Log() << Verbose(0) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
3424 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3425 }
3426
3427 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3428 connectedCircle->push_back(AngleRunner->second);
3429 }
3430
3431 return connectedCircle;
3432}
3433
3434/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3435 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3436 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3437 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3438 * triangle we are looking for.
3439 *
3440 * @param *SetOfNeighbours all points for which the angle should be calculated
3441 * @param *Point of which get all connected points
3442 * @param *Reference Reference vector for zero angle or NULL for no preference
3443 * @return list of the all points linked to the provided one
3444 */
3445TesselPointList * Tesselation::GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3446{
3447 Info FunctionInfo(__func__);
3448 map<double, TesselPoint*> anglesOfPoints;
3449 TesselPointList *connectedCircle = new TesselPointList;
3450 Vector center;
3451 Vector PlaneNormal;
3452 Vector AngleZero;
3453 Vector OrthogonalVector;
3454 Vector helper;
3455
3456 if (SetOfNeighbours == NULL) {
3457 eLog() << Verbose(2) << "Could not find any connected points!" << endl;
3458 delete(connectedCircle);
3459 return NULL;
3460 }
3461
3462 // calculate central point
3463 for (TesselPointSet::const_iterator TesselRunner = SetOfNeighbours->begin(); TesselRunner != SetOfNeighbours->end(); TesselRunner++)
3464 center.AddVector((*TesselRunner)->node);
3465 //Log() << Verbose(0) << "Summed vectors " << center << "; number of points " << connectedPoints.size()
3466 // << "; scale factor " << 1.0/connectedPoints.size();
3467 center.Scale(1.0/SetOfNeighbours->size());
3468 Log() << Verbose(1) << "INFO: Calculated center of all circle points is " << center << "." << endl;
3469
3470 // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
3471 PlaneNormal.CopyVector(Point->node);
3472 PlaneNormal.SubtractVector(&center);
3473 PlaneNormal.Normalize();
3474 Log() << Verbose(1) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
3475
3476 // construct one orthogonal vector
3477 if (Reference != NULL) {
3478 AngleZero.CopyVector(Reference);
3479 AngleZero.SubtractVector(Point->node);
3480 AngleZero.ProjectOntoPlane(&PlaneNormal);
3481 }
3482 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3483 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3484 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3485 AngleZero.SubtractVector(Point->node);
3486 AngleZero.ProjectOntoPlane(&PlaneNormal);
3487 if (AngleZero.NormSquared() < MYEPSILON) {
3488 eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
3489 performCriticalExit();
3490 }
3491 }
3492 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3493 if (AngleZero.NormSquared() > MYEPSILON)
3494 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3495 else
3496 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3497 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3498
3499 // go through all connected points and calculate angle
3500 pair <map<double, TesselPoint*>::iterator, bool > InserterTest;
3501 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3502 helper.CopyVector((*listRunner)->node);
3503 helper.SubtractVector(Point->node);
3504 helper.ProjectOntoPlane(&PlaneNormal);
3505 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3506 Log() << Verbose(0) << "INFO: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << "." << endl;
3507 InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3508 if (!InserterTest.second) {
3509 eLog() << Verbose(0) << "GetCircleOfSetOfPoints() got two atoms with same angle: " << *((InserterTest.first)->second) << " and " << (*listRunner) << endl;
3510 performCriticalExit();
3511 }
3512 }
3513
3514 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3515 connectedCircle->push_back(AngleRunner->second);
3516 }
3517
3518 return connectedCircle;
3519}
3520
3521/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
3522 *
3523 * @param *out output stream for debugging
3524 * @param *Point of which get all connected points
3525 * @return list of the all points linked to the provided one
3526 */
3527list< TesselPointList *> * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
3528{
3529 Info FunctionInfo(__func__);
3530 map<double, TesselPoint*> anglesOfPoints;
3531 list< TesselPointList *> *ListOfPaths = new list< TesselPointList *>;
3532 TesselPointList *connectedPath = NULL;
3533 Vector center;
3534 Vector PlaneNormal;
3535 Vector AngleZero;
3536 Vector OrthogonalVector;
3537 Vector helper;
3538 class BoundaryPointSet *ReferencePoint = NULL;
3539 class BoundaryPointSet *CurrentPoint = NULL;
3540 class BoundaryTriangleSet *triangle = NULL;
3541 class BoundaryLineSet *CurrentLine = NULL;
3542 class BoundaryLineSet *StartLine = NULL;
3543
3544 // find the respective boundary point
3545 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
3546 if (PointRunner != PointsOnBoundary.end()) {
3547 ReferencePoint = PointRunner->second;
3548 } else {
3549 eLog() << Verbose(1) << "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
3550 return NULL;
3551 }
3552
3553 map <class BoundaryLineSet *, bool> TouchedLine;
3554 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
3555 map <class BoundaryLineSet *, bool>::iterator LineRunner;
3556 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
3557 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
3558 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
3559 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
3560 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
3561 }
3562 if (!ReferencePoint->lines.empty()) {
3563 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
3564 LineRunner = TouchedLine.find(runner->second);
3565 if (LineRunner == TouchedLine.end()) {
3566 eLog() << Verbose(1) << "I could not find " << *runner->second << " in the touched list." << endl;
3567 } else if (!LineRunner->second) {
3568 LineRunner->second = true;
3569 connectedPath = new TesselPointList;
3570 triangle = NULL;
3571 CurrentLine = runner->second;
3572 StartLine = CurrentLine;
3573 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3574 Log() << Verbose(1)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
3575 do {
3576 // push current one
3577 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3578 connectedPath->push_back(CurrentPoint->node);
3579
3580 // find next triangle
3581 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
3582 Log() << Verbose(1) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
3583 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
3584 triangle = Runner->second;
3585 TriangleRunner = TouchedTriangle.find(triangle);
3586 if (TriangleRunner != TouchedTriangle.end()) {
3587 if (!TriangleRunner->second) {
3588 TriangleRunner->second = true;
3589 Log() << Verbose(1) << "INFO: Connecting triangle is " << *triangle << "." << endl;
3590 break;
3591 } else {
3592 Log() << Verbose(1) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
3593 triangle = NULL;
3594 }
3595 } else {
3596 eLog() << Verbose(1) << "I could not find " << *triangle << " in the touched list." << endl;
3597 triangle = NULL;
3598 }
3599 }
3600 }
3601 if (triangle == NULL)
3602 break;
3603 // find next line
3604 for (int i=0;i<3;i++) {
3605 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
3606 CurrentLine = triangle->lines[i];
3607 Log() << Verbose(1) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
3608 break;
3609 }
3610 }
3611 LineRunner = TouchedLine.find(CurrentLine);
3612 if (LineRunner == TouchedLine.end())
3613 eLog() << Verbose(1) << "I could not find " << *CurrentLine << " in the touched list." << endl;
3614 else
3615 LineRunner->second = true;
3616 // find next point
3617 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3618
3619 } while (CurrentLine != StartLine);
3620 // last point is missing, as it's on start line
3621 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3622 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
3623 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
3624
3625 ListOfPaths->push_back(connectedPath);
3626 } else {
3627 Log() << Verbose(1) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
3628 }
3629 }
3630 } else {
3631 eLog() << Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl;
3632 }
3633
3634 return ListOfPaths;
3635}
3636
3637/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
3638 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
3639 * @param *out output stream for debugging
3640 * @param *Point of which get all connected points
3641 * @return list of the closed paths
3642 */
3643list<TesselPointList *> * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
3644{
3645 Info FunctionInfo(__func__);
3646 list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
3647 list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *>;
3648 TesselPointList *connectedPath = NULL;
3649 TesselPointList *newPath = NULL;
3650 int count = 0;
3651
3652
3653 TesselPointList::iterator CircleRunner;
3654 TesselPointList::iterator CircleStart;
3655
3656 for(list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
3657 connectedPath = *ListRunner;
3658
3659 Log() << Verbose(1) << "INFO: Current path is " << connectedPath << "." << endl;
3660
3661 // go through list, look for reappearance of starting Point and count
3662 CircleStart = connectedPath->begin();
3663
3664 // go through list, look for reappearance of starting Point and create list
3665 TesselPointList::iterator Marker = CircleStart;
3666 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
3667 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
3668 // we have a closed circle from Marker to new Marker
3669 Log() << Verbose(1) << count+1 << ". closed path consists of: ";
3670 newPath = new TesselPointList;
3671 TesselPointList::iterator CircleSprinter = Marker;
3672 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
3673 newPath->push_back(*CircleSprinter);
3674 Log() << Verbose(0) << (**CircleSprinter) << " <-> ";
3675 }
3676 Log() << Verbose(0) << ".." << endl;
3677 count++;
3678 Marker = CircleRunner;
3679
3680 // add to list
3681 ListofClosedPaths->push_back(newPath);
3682 }
3683 }
3684 }
3685 Log() << Verbose(1) << "INFO: " << count << " closed additional path(s) have been created." << endl;
3686
3687 // delete list of paths
3688 while (!ListofPaths->empty()) {
3689 connectedPath = *(ListofPaths->begin());
3690 ListofPaths->remove(connectedPath);
3691 delete(connectedPath);
3692 }
3693 delete(ListofPaths);
3694
3695 // exit
3696 return ListofClosedPaths;
3697};
3698
3699
3700/** Gets all belonging triangles for a given BoundaryPointSet.
3701 * \param *out output stream for debugging
3702 * \param *Point BoundaryPoint
3703 * \return pointer to allocated list of triangles
3704 */
3705TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
3706{
3707 Info FunctionInfo(__func__);
3708 TriangleSet *connectedTriangles = new TriangleSet;
3709
3710 if (Point == NULL) {
3711 eLog() << Verbose(1) << "Point given is NULL." << endl;
3712 } else {
3713 // go through its lines and insert all triangles
3714 for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
3715 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
3716 connectedTriangles->insert(TriangleRunner->second);
3717 }
3718 }
3719
3720 return connectedTriangles;
3721};
3722
3723
3724/** Removes a boundary point from the envelope while keeping it closed.
3725 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
3726 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
3727 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
3728 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
3729 * -# the surface is closed, when the path is empty
3730 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
3731 * \param *out output stream for debugging
3732 * \param *point point to be removed
3733 * \return volume added to the volume inside the tesselated surface by the removal
3734 */
3735double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point) {
3736 class BoundaryLineSet *line = NULL;
3737 class BoundaryTriangleSet *triangle = NULL;
3738 Vector OldPoint, NormalVector;
3739 double volume = 0;
3740 int count = 0;
3741
3742 if (point == NULL) {
3743 eLog() << Verbose(1) << "Cannot remove the point " << point << ", it's NULL!" << endl;
3744 return 0.;
3745 } else
3746 Log() << Verbose(0) << "Removing point " << *point << " from tesselated boundary ..." << endl;
3747
3748 // copy old location for the volume
3749 OldPoint.CopyVector(point->node->node);
3750
3751 // get list of connected points
3752 if (point->lines.empty()) {
3753 eLog() << Verbose(1) << "Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
3754 return 0.;
3755 }
3756
3757 list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
3758 TesselPointList *connectedPath = NULL;
3759
3760 // gather all triangles
3761 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3762 count+=LineRunner->second->triangles.size();
3763 TriangleMap Candidates;
3764 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3765 line = LineRunner->second;
3766 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3767 triangle = TriangleRunner->second;
3768 Candidates.insert( TrianglePair (triangle->Nr, triangle) );
3769 }
3770 }
3771
3772 // remove all triangles
3773 count=0;
3774 NormalVector.Zero();
3775 for (TriangleMap::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3776 Log() << Verbose(1) << "INFO: Removing triangle " << *(Runner->second) << "." << endl;
3777 NormalVector.SubtractVector(&Runner->second->NormalVector); // has to point inward
3778 RemoveTesselationTriangle(Runner->second);
3779 count++;
3780 }
3781 Log() << Verbose(1) << count << " triangles were removed." << endl;
3782
3783 list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
3784 list<TesselPointList *>::iterator ListRunner = ListAdvance;
3785 TriangleMap::iterator NumberRunner = Candidates.begin();
3786 TesselPointList::iterator StartNode, MiddleNode, EndNode;
3787 double angle;
3788 double smallestangle;
3789 Vector Point, Reference, OrthogonalVector;
3790 if (count > 2) { // less than three triangles, then nothing will be created
3791 class TesselPoint *TriangleCandidates[3];
3792 count = 0;
3793 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3794 if (ListAdvance != ListOfClosedPaths->end())
3795 ListAdvance++;
3796
3797 connectedPath = *ListRunner;
3798
3799 // re-create all triangles by going through connected points list
3800 LineList NewLines;
3801 for (;!connectedPath->empty();) {
3802 // search middle node with widest angle to next neighbours
3803 EndNode = connectedPath->end();
3804 smallestangle = 0.;
3805 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3806 Log() << Verbose(1) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3807 // construct vectors to next and previous neighbour
3808 StartNode = MiddleNode;
3809 if (StartNode == connectedPath->begin())
3810 StartNode = connectedPath->end();
3811 StartNode--;
3812 //Log() << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
3813 Point.CopyVector((*StartNode)->node);
3814 Point.SubtractVector((*MiddleNode)->node);
3815 StartNode = MiddleNode;
3816 StartNode++;
3817 if (StartNode == connectedPath->end())
3818 StartNode = connectedPath->begin();
3819 //Log() << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
3820 Reference.CopyVector((*StartNode)->node);
3821 Reference.SubtractVector((*MiddleNode)->node);
3822 OrthogonalVector.CopyVector((*MiddleNode)->node);
3823 OrthogonalVector.SubtractVector(&OldPoint);
3824 OrthogonalVector.MakeNormalVector(&Reference);
3825 angle = GetAngle(Point, Reference, OrthogonalVector);
3826 //if (angle < M_PI) // no wrong-sided triangles, please?
3827 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3828 smallestangle = angle;
3829 EndNode = MiddleNode;
3830 }
3831 }
3832 MiddleNode = EndNode;
3833 if (MiddleNode == connectedPath->end()) {
3834 eLog() << Verbose(0) << "CRITICAL: Could not find a smallest angle!" << endl;
3835 performCriticalExit();
3836 }
3837 StartNode = MiddleNode;
3838 if (StartNode == connectedPath->begin())
3839 StartNode = connectedPath->end();
3840 StartNode--;
3841 EndNode++;
3842 if (EndNode == connectedPath->end())
3843 EndNode = connectedPath->begin();
3844 Log() << Verbose(2) << "INFO: StartNode is " << **StartNode << "." << endl;
3845 Log() << Verbose(2) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3846 Log() << Verbose(2) << "INFO: EndNode is " << **EndNode << "." << endl;
3847 Log() << Verbose(1) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
3848 TriangleCandidates[0] = *StartNode;
3849 TriangleCandidates[1] = *MiddleNode;
3850 TriangleCandidates[2] = *EndNode;
3851 triangle = GetPresentTriangle(TriangleCandidates);
3852 if (triangle != NULL) {
3853 eLog() << Verbose(0) << "New triangle already present, skipping!" << endl;
3854 StartNode++;
3855 MiddleNode++;
3856 EndNode++;
3857 if (StartNode == connectedPath->end())
3858 StartNode = connectedPath->begin();
3859 if (MiddleNode == connectedPath->end())
3860 MiddleNode = connectedPath->begin();
3861 if (EndNode == connectedPath->end())
3862 EndNode = connectedPath->begin();
3863 continue;
3864 }
3865 Log() << Verbose(3) << "Adding new triangle points."<< endl;
3866 AddTesselationPoint(*StartNode, 0);
3867 AddTesselationPoint(*MiddleNode, 1);
3868 AddTesselationPoint(*EndNode, 2);
3869 Log() << Verbose(3) << "Adding new triangle lines."<< endl;
3870 AddTesselationLine(TPS[0], TPS[1], 0);
3871 AddTesselationLine(TPS[0], TPS[2], 1);
3872 NewLines.push_back(BLS[1]);
3873 AddTesselationLine(TPS[1], TPS[2], 2);
3874 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3875 BTS->GetNormalVector(NormalVector);
3876 AddTesselationTriangle();
3877 // calculate volume summand as a general tetraeder
3878 volume += CalculateVolumeofGeneralTetraeder(*TPS[0]->node->node, *TPS[1]->node->node, *TPS[2]->node->node, OldPoint);
3879 // advance number
3880 count++;
3881
3882 // prepare nodes for next triangle
3883 StartNode = EndNode;
3884 Log() << Verbose(2) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
3885 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3886 if (connectedPath->size() == 2) { // we are done
3887 connectedPath->remove(*StartNode); // remove the start node
3888 connectedPath->remove(*EndNode); // remove the end node
3889 break;
3890 } else if (connectedPath->size() < 2) { // something's gone wrong!
3891 eLog() << Verbose(0) << "CRITICAL: There are only two endpoints left!" << endl;
3892 performCriticalExit();
3893 } else {
3894 MiddleNode = StartNode;
3895 MiddleNode++;
3896 if (MiddleNode == connectedPath->end())
3897 MiddleNode = connectedPath->begin();
3898 EndNode = MiddleNode;
3899 EndNode++;
3900 if (EndNode == connectedPath->end())
3901 EndNode = connectedPath->begin();
3902 }
3903 }
3904 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
3905 if (NewLines.size() > 1) {
3906 LineList::iterator Candidate;
3907 class BoundaryLineSet *OtherBase = NULL;
3908 double tmp, maxgain;
3909 do {
3910 maxgain = 0;
3911 for(LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
3912 tmp = PickFarthestofTwoBaselines(*Runner);
3913 if (maxgain < tmp) {
3914 maxgain = tmp;
3915 Candidate = Runner;
3916 }
3917 }
3918 if (maxgain != 0) {
3919 volume += maxgain;
3920 Log() << Verbose(1) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
3921 OtherBase = FlipBaseline(*Candidate);
3922 NewLines.erase(Candidate);
3923 NewLines.push_back(OtherBase);
3924 }
3925 } while (maxgain != 0.);
3926 }
3927
3928 ListOfClosedPaths->remove(connectedPath);
3929 delete(connectedPath);
3930 }
3931 Log() << Verbose(0) << count << " triangles were created." << endl;
3932 } else {
3933 while (!ListOfClosedPaths->empty()) {
3934 ListRunner = ListOfClosedPaths->begin();
3935 connectedPath = *ListRunner;
3936 ListOfClosedPaths->remove(connectedPath);
3937 delete(connectedPath);
3938 }
3939 Log() << Verbose(0) << "No need to create any triangles." << endl;
3940 }
3941 delete(ListOfClosedPaths);
3942
3943 Log() << Verbose(0) << "Removed volume is " << volume << "." << endl;
3944
3945 return volume;
3946};
3947
3948
3949
3950/**
3951 * Finds triangles belonging to the three provided points.
3952 *
3953 * @param *Points[3] list, is expected to contain three points (NULL means wildcard)
3954 *
3955 * @return triangles which belong to the provided points, will be empty if there are none,
3956 * will usually be one, in case of degeneration, there will be two
3957 */
3958TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
3959{
3960 Info FunctionInfo(__func__);
3961 TriangleList *result = new TriangleList;
3962 LineMap::const_iterator FindLine;
3963 TriangleMap::const_iterator FindTriangle;
3964 class BoundaryPointSet *TrianglePoints[3];
3965 size_t NoOfWildcards = 0;
3966
3967 for (int i = 0; i < 3; i++) {
3968 if (Points[i] == NULL) {
3969 NoOfWildcards++;
3970 TrianglePoints[i] = NULL;
3971 } else {
3972 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->nr);
3973 if (FindPoint != PointsOnBoundary.end()) {
3974 TrianglePoints[i] = FindPoint->second;
3975 } else {
3976 TrianglePoints[i] = NULL;
3977 }
3978 }
3979 }
3980
3981 switch (NoOfWildcards) {
3982 case 0: // checks lines between the points in the Points for their adjacent triangles
3983 for (int i = 0; i < 3; i++) {
3984 if (TrianglePoints[i] != NULL) {
3985 for (int j = i+1; j < 3; j++) {
3986 if (TrianglePoints[j] != NULL) {
3987 for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr); // is a multimap!
3988 (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->nr);
3989 FindLine++) {
3990 for (FindTriangle = FindLine->second->triangles.begin();
3991 FindTriangle != FindLine->second->triangles.end();
3992 FindTriangle++) {
3993 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3994 result->push_back(FindTriangle->second);
3995 }
3996 }
3997 }
3998 // Is it sufficient to consider one of the triangle lines for this.
3999 return result;
4000 }
4001 }
4002 }
4003 }
4004 break;
4005 case 1: // copy all triangles of the respective line
4006 {
4007 int i=0;
4008 for (; i < 3; i++)
4009 if (TrianglePoints[i] == NULL)
4010 break;
4011 for (FindLine = TrianglePoints[(i+1)%3]->lines.find(TrianglePoints[(i+2)%3]->node->nr); // is a multimap!
4012 (FindLine != TrianglePoints[(i+1)%3]->lines.end()) && (FindLine->first == TrianglePoints[(i+2)%3]->node->nr);
4013 FindLine++) {
4014 for (FindTriangle = FindLine->second->triangles.begin();
4015 FindTriangle != FindLine->second->triangles.end();
4016 FindTriangle++) {
4017 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
4018 result->push_back(FindTriangle->second);
4019 }
4020 }
4021 }
4022 break;
4023 }
4024 case 2: // copy all triangles of the respective point
4025 {
4026 int i=0;
4027 for (; i < 3; i++)
4028 if (TrianglePoints[i] != NULL)
4029 break;
4030 for (LineMap::const_iterator line = TrianglePoints[i]->lines.begin(); line != TrianglePoints[i]->lines.end(); line++)
4031 for (TriangleMap::const_iterator triangle = line->second->triangles.begin(); triangle != line->second->triangles.end(); triangle++)
4032 result->push_back(triangle->second);
4033 result->sort();
4034 result->unique();
4035 break;
4036 }
4037 case 3: // copy all triangles
4038 {
4039 for (TriangleMap::const_iterator triangle = TrianglesOnBoundary.begin(); triangle != TrianglesOnBoundary.end(); triangle++)
4040 result->push_back(triangle->second);
4041 break;
4042 }
4043 default:
4044 eLog() << Verbose(0) << "Number of wildcards is greater than 3, cannot happen!" << endl;
4045 performCriticalExit();
4046 break;
4047 }
4048
4049 return result;
4050}
4051
4052struct BoundaryLineSetCompare {
4053 bool operator() (const BoundaryLineSet * const a, const BoundaryLineSet * const b) {
4054 int lowerNra = -1;
4055 int lowerNrb = -1;
4056
4057 if (a->endpoints[0] < a->endpoints[1])
4058 lowerNra = 0;
4059 else
4060 lowerNra = 1;
4061
4062 if (b->endpoints[0] < b->endpoints[1])
4063 lowerNrb = 0;
4064 else
4065 lowerNrb = 1;
4066
4067 if (a->endpoints[lowerNra] < b->endpoints[lowerNrb])
4068 return true;
4069 else if (a->endpoints[lowerNra] > b->endpoints[lowerNrb])
4070 return false;
4071 else { // both lower-numbered endpoints are the same ...
4072 if (a->endpoints[(lowerNra+1)%2] < b->endpoints[(lowerNrb+1)%2])
4073 return true;
4074 else if (a->endpoints[(lowerNra+1)%2] > b->endpoints[(lowerNrb+1)%2])
4075 return false;
4076 }
4077 return false;
4078 };
4079};
4080
4081#define UniqueLines set < class BoundaryLineSet *, BoundaryLineSetCompare>
4082
4083/**
4084 * Finds all degenerated lines within the tesselation structure.
4085 *
4086 * @return map of keys of degenerated line pairs, each line occurs twice
4087 * in the list, once as key and once as value
4088 */
4089IndexToIndex * Tesselation::FindAllDegeneratedLines()
4090{
4091 Info FunctionInfo(__func__);
4092 UniqueLines AllLines;
4093 IndexToIndex * DegeneratedLines = new IndexToIndex;
4094
4095 // sanity check
4096 if (LinesOnBoundary.empty()) {
4097 eLog() << Verbose(2) << "FindAllDegeneratedTriangles() was called without any tesselation structure.";
4098 return DegeneratedLines;
4099 }
4100
4101 LineMap::iterator LineRunner1;
4102 pair< UniqueLines::iterator, bool> tester;
4103 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
4104 tester = AllLines.insert( LineRunner1->second );
4105 if (!tester.second) { // found degenerated line
4106 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr) );
4107 DegeneratedLines->insert ( pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr) );
4108 }
4109 }
4110
4111 AllLines.clear();
4112
4113 Log() << Verbose(0) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
4114 IndexToIndex::iterator it;
4115 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
4116 const LineMap::const_iterator Line1 = LinesOnBoundary.find((*it).first);
4117 const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
4118 if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
4119 Log() << Verbose(0) << *Line1->second << " => " << *Line2->second << endl;
4120 else
4121 eLog() << Verbose(1) << "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!" << endl;
4122 }
4123
4124 return DegeneratedLines;
4125}
4126
4127/**
4128 * Finds all degenerated triangles within the tesselation structure.
4129 *
4130 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
4131 * in the list, once as key and once as value
4132 */
4133IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
4134{
4135 Info FunctionInfo(__func__);
4136 IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
4137 IndexToIndex * DegeneratedTriangles = new IndexToIndex;
4138
4139 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
4140 LineMap::iterator Liner;
4141 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
4142
4143 for (IndexToIndex::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
4144 // run over both lines' triangles
4145 Liner = LinesOnBoundary.find(LineRunner->first);
4146 if (Liner != LinesOnBoundary.end())
4147 line1 = Liner->second;
4148 Liner = LinesOnBoundary.find(LineRunner->second);
4149 if (Liner != LinesOnBoundary.end())
4150 line2 = Liner->second;
4151 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
4152 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
4153 if ((TriangleRunner1->second != TriangleRunner2->second)
4154 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
4155 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
4156 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
4157 }
4158 }
4159 }
4160 }
4161 delete(DegeneratedLines);
4162
4163 Log() << Verbose(0) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
4164 IndexToIndex::iterator it;
4165 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
4166 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
4167
4168 return DegeneratedTriangles;
4169}
4170
4171/**
4172 * Purges degenerated triangles from the tesselation structure if they are not
4173 * necessary to keep a single point within the structure.
4174 */
4175void Tesselation::RemoveDegeneratedTriangles()
4176{
4177 Info FunctionInfo(__func__);
4178 IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
4179 TriangleMap::iterator finder;
4180 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
4181 int count = 0;
4182
4183 for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
4184 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
4185 ) {
4186 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
4187 if (finder != TrianglesOnBoundary.end())
4188 triangle = finder->second;
4189 else
4190 break;
4191 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
4192 if (finder != TrianglesOnBoundary.end())
4193 partnerTriangle = finder->second;
4194 else
4195 break;
4196
4197 bool trianglesShareLine = false;
4198 for (int i = 0; i < 3; ++i)
4199 for (int j = 0; j < 3; ++j)
4200 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
4201
4202 if (trianglesShareLine
4203 && (triangle->endpoints[1]->LinesCount > 2)
4204 && (triangle->endpoints[2]->LinesCount > 2)
4205 && (triangle->endpoints[0]->LinesCount > 2)
4206 ) {
4207 // check whether we have to fix lines
4208 BoundaryTriangleSet *Othertriangle = NULL;
4209 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
4210 TriangleMap::iterator TriangleRunner;
4211 for (int i = 0; i < 3; ++i)
4212 for (int j = 0; j < 3; ++j)
4213 if (triangle->lines[i] != partnerTriangle->lines[j]) {
4214 // get the other two triangles
4215 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
4216 if (TriangleRunner->second != triangle) {
4217 Othertriangle = TriangleRunner->second;
4218 }
4219 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
4220 if (TriangleRunner->second != partnerTriangle) {
4221 OtherpartnerTriangle = TriangleRunner->second;
4222 }
4223 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
4224 // the line of triangle receives the degenerated ones
4225 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
4226 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
4227 for (int k=0;k<3;k++)
4228 if (triangle->lines[i] == Othertriangle->lines[k]) {
4229 Othertriangle->lines[k] = partnerTriangle->lines[j];
4230 break;
4231 }
4232 // the line of partnerTriangle receives the non-degenerated ones
4233 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
4234 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
4235 partnerTriangle->lines[j] = triangle->lines[i];
4236 }
4237
4238 // erase the pair
4239 count += (int) DegeneratedTriangles->erase(triangle->Nr);
4240 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
4241 RemoveTesselationTriangle(triangle);
4242 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
4243 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
4244 RemoveTesselationTriangle(partnerTriangle);
4245 } else {
4246 Log() << Verbose(0) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
4247 << " and its partner " << *partnerTriangle << " because it is essential for at"
4248 << " least one of the endpoints to be kept in the tesselation structure." << endl;
4249 }
4250 }
4251 delete(DegeneratedTriangles);
4252 if (count > 0)
4253 LastTriangle = NULL;
4254
4255 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
4256}
4257
4258/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
4259 * We look for the closest point on the boundary, we look through its connected boundary lines and
4260 * seek the one with the minimum angle between its center point and the new point and this base line.
4261 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
4262 * \param *out output stream for debugging
4263 * \param *point point to add
4264 * \param *LC Linked Cell structure to find nearest point
4265 */
4266void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC)
4267{
4268 Info FunctionInfo(__func__);
4269 // find nearest boundary point
4270 class TesselPoint *BackupPoint = NULL;
4271 class TesselPoint *NearestPoint = FindClosestTesselPoint(point->node, BackupPoint, LC);
4272 class BoundaryPointSet *NearestBoundaryPoint = NULL;
4273 PointMap::iterator PointRunner;
4274
4275 if (NearestPoint == point)
4276 NearestPoint = BackupPoint;
4277 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
4278 if (PointRunner != PointsOnBoundary.end()) {
4279 NearestBoundaryPoint = PointRunner->second;
4280 } else {
4281 eLog() << Verbose(1) << "I cannot find the boundary point." << endl;
4282 return;
4283 }
4284 Log() << Verbose(0) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
4285
4286 // go through its lines and find the best one to split
4287 Vector CenterToPoint;
4288 Vector BaseLine;
4289 double angle, BestAngle = 0.;
4290 class BoundaryLineSet *BestLine = NULL;
4291 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
4292 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
4293 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
4294 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
4295 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
4296 CenterToPoint.Scale(0.5);
4297 CenterToPoint.SubtractVector(point->node);
4298 angle = CenterToPoint.Angle(&BaseLine);
4299 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
4300 BestAngle = angle;
4301 BestLine = Runner->second;
4302 }
4303 }
4304
4305 // remove one triangle from the chosen line
4306 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
4307 BestLine->triangles.erase(TempTriangle->Nr);
4308 int nr = -1;
4309 for (int i=0;i<3; i++) {
4310 if (TempTriangle->lines[i] == BestLine) {
4311 nr = i;
4312 break;
4313 }
4314 }
4315
4316 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
4317 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4318 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4319 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4320 AddTesselationPoint(point, 2);
4321 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4322 AddTesselationLine(TPS[0], TPS[1], 0);
4323 AddTesselationLine(TPS[0], TPS[2], 1);
4324 AddTesselationLine(TPS[1], TPS[2], 2);
4325 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4326 BTS->GetNormalVector(TempTriangle->NormalVector);
4327 BTS->NormalVector.Scale(-1.);
4328 Log() << Verbose(1) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
4329 AddTesselationTriangle();
4330
4331 // create other side of this triangle and close both new sides of the first created triangle
4332 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4333 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4334 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4335 AddTesselationPoint(point, 2);
4336 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4337 AddTesselationLine(TPS[0], TPS[1], 0);
4338 AddTesselationLine(TPS[0], TPS[2], 1);
4339 AddTesselationLine(TPS[1], TPS[2], 2);
4340 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4341 BTS->GetNormalVector(TempTriangle->NormalVector);
4342 Log() << Verbose(1) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
4343 AddTesselationTriangle();
4344
4345 // add removed triangle to the last open line of the second triangle
4346 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
4347 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
4348 if (BestLine == BTS->lines[i]){
4349 eLog() << Verbose(0) << "BestLine is same as found line, something's wrong here!" << endl;
4350 performCriticalExit();
4351 }
4352 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
4353 TempTriangle->lines[nr] = BTS->lines[i];
4354 break;
4355 }
4356 }
4357};
4358
4359/** Writes the envelope to file.
4360 * \param *out otuput stream for debugging
4361 * \param *filename basename of output file
4362 * \param *cloud PointCloud structure with all nodes
4363 */
4364void Tesselation::Output(const char *filename, const PointCloud * const cloud)
4365{
4366 Info FunctionInfo(__func__);
4367 ofstream *tempstream = NULL;
4368 string NameofTempFile;
4369 char NumberName[255];
4370
4371 if (LastTriangle != NULL) {
4372 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
4373 if (DoTecplotOutput) {
4374 string NameofTempFile(filename);
4375 NameofTempFile.append(NumberName);
4376 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4377 NameofTempFile.erase(npos, 1);
4378 NameofTempFile.append(TecplotSuffix);
4379 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4380 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4381 WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
4382 tempstream->close();
4383 tempstream->flush();
4384 delete(tempstream);
4385 }
4386
4387 if (DoRaster3DOutput) {
4388 string NameofTempFile(filename);
4389 NameofTempFile.append(NumberName);
4390 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4391 NameofTempFile.erase(npos, 1);
4392 NameofTempFile.append(Raster3DSuffix);
4393 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4394 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4395 WriteRaster3dFile(tempstream, this, cloud);
4396 IncludeSphereinRaster3D(tempstream, this, cloud);
4397 tempstream->close();
4398 tempstream->flush();
4399 delete(tempstream);
4400 }
4401 }
4402 if (DoTecplotOutput || DoRaster3DOutput)
4403 TriangleFilesWritten++;
4404};
4405
4406struct BoundaryPolygonSetCompare {
4407 bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const {
4408 if (s1->endpoints.size() < s2->endpoints.size())
4409 return true;
4410 else if (s1->endpoints.size() > s2->endpoints.size())
4411 return false;
4412 else { // equality of number of endpoints
4413 PointSet::const_iterator Walker1 = s1->endpoints.begin();
4414 PointSet::const_iterator Walker2 = s2->endpoints.begin();
4415 while ((Walker1 != s1->endpoints.end()) || (Walker2 != s2->endpoints.end())) {
4416 if ((*Walker1)->Nr < (*Walker2)->Nr)
4417 return true;
4418 else if ((*Walker1)->Nr > (*Walker2)->Nr)
4419 return false;
4420 Walker1++;
4421 Walker2++;
4422 }
4423 return false;
4424 }
4425 }
4426};
4427
4428#define UniquePolygonSet set < BoundaryPolygonSet *, BoundaryPolygonSetCompare>
4429
4430/** Finds all degenerated polygons and calls ReTesselateDegeneratedPolygon()/
4431 * \return number of polygons found
4432 */
4433int Tesselation::CorrectAllDegeneratedPolygons()
4434{
4435 Info FunctionInfo(__func__);
4436
4437 /// 2. Go through all BoundaryPointSet's, check their triangles' NormalVector
4438 IndexToIndex *DegeneratedTriangles = FindAllDegeneratedTriangles();
4439 set < BoundaryPointSet *> EndpointCandidateList;
4440 pair < set < BoundaryPointSet *>::iterator, bool > InsertionTester;
4441 pair < map < int, Vector *>::iterator, bool > TriangleInsertionTester;
4442 for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
4443 Log() << Verbose(0) << "Current point is " << *Runner->second << "." << endl;
4444 map < int, Vector *> TriangleVectors;
4445 // gather all NormalVectors
4446 Log() << Verbose(1) << "Gathering triangles ..." << endl;
4447 for (LineMap::const_iterator LineRunner = (Runner->second)->lines.begin(); LineRunner != (Runner->second)->lines.end(); LineRunner++)
4448 for (TriangleMap::const_iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
4449 if (DegeneratedTriangles->find(TriangleRunner->second->Nr) == DegeneratedTriangles->end()) {
4450 TriangleInsertionTester = TriangleVectors.insert( pair< int, Vector *> ((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)) );
4451 if (TriangleInsertionTester.second)
4452 Log() << Verbose(1) << " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list." << endl;
4453 } else {
4454 Log() << Verbose(1) << " NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one." << endl;
4455 }
4456 }
4457 // check whether there are two that are parallel
4458 Log() << Verbose(1) << "Finding two parallel triangles ..." << endl;
4459 for (map < int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
4460 for (map < int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
4461 if (VectorWalker != VectorRunner) { // skip equals
4462 const double SCP = VectorWalker->second->ScalarProduct(VectorRunner->second); // ScalarProduct should result in -1. for degenerated triangles
4463 Log() << Verbose(1) << "Checking " << *VectorWalker->second<< " against " << *VectorRunner->second << ": " << SCP << endl;
4464 if (fabs(SCP + 1.) < ParallelEpsilon) {
4465 InsertionTester = EndpointCandidateList.insert((Runner->second));
4466 if (InsertionTester.second)
4467 Log() << Verbose(0) << " Adding " << *Runner->second << " to endpoint candidate list." << endl;
4468 // and break out of both loops
4469 VectorWalker = TriangleVectors.end();
4470 VectorRunner = TriangleVectors.end();
4471 break;
4472 }
4473 }
4474 }
4475
4476 /// 3. Find connected endpoint candidates and put them into a polygon
4477 UniquePolygonSet ListofDegeneratedPolygons;
4478 BoundaryPointSet *Walker = NULL;
4479 BoundaryPointSet *OtherWalker = NULL;
4480 BoundaryPolygonSet *Current = NULL;
4481 stack <BoundaryPointSet*> ToCheckConnecteds;
4482 while (!EndpointCandidateList.empty()) {
4483 Walker = *(EndpointCandidateList.begin());
4484 if (Current == NULL) { // create a new polygon with current candidate
4485 Log() << Verbose(0) << "Starting new polygon set at point " << *Walker << endl;
4486 Current = new BoundaryPolygonSet;
4487 Current->endpoints.insert(Walker);
4488 EndpointCandidateList.erase(Walker);
4489 ToCheckConnecteds.push(Walker);
4490 }
4491
4492 // go through to-check stack
4493 while (!ToCheckConnecteds.empty()) {
4494 Walker = ToCheckConnecteds.top(); // fetch ...
4495 ToCheckConnecteds.pop(); // ... and remove
4496 for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
4497 OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
4498 Log() << Verbose(1) << "Checking " << *OtherWalker << endl;
4499 set < BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
4500 if (Finder != EndpointCandidateList.end()) { // found a connected partner
4501 Log() << Verbose(1) << " Adding to polygon." << endl;
4502 Current->endpoints.insert(OtherWalker);
4503 EndpointCandidateList.erase(Finder); // remove from candidates
4504 ToCheckConnecteds.push(OtherWalker); // but check its partners too
4505 } else {
4506 Log() << Verbose(1) << " is not connected to " << *Walker << endl;
4507 }
4508 }
4509 }
4510
4511 Log() << Verbose(0) << "Final polygon is " << *Current << endl;
4512 ListofDegeneratedPolygons.insert(Current);
4513 Current = NULL;
4514 }
4515
4516 const int counter = ListofDegeneratedPolygons.size();
4517
4518 Log() << Verbose(0) << "The following " << counter << " degenerated polygons have been found: " << endl;
4519 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
4520 Log() << Verbose(0) << " " << **PolygonRunner << endl;
4521
4522 /// 4. Go through all these degenerated polygons
4523 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++) {
4524 stack <int> TriangleNrs;
4525 Vector NormalVector;
4526 /// 4a. Gather all triangles of this polygon
4527 TriangleSet *T = (*PolygonRunner)->GetAllContainedTrianglesFromEndpoints();
4528
4529 // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
4530 if (T->size() == 2) {
4531 Log() << Verbose(1) << " Skipping degenerated polygon, is just a (already simply degenerated) triangle." << endl;
4532 delete(T);
4533 continue;
4534 }
4535
4536 // check whether number is even
4537 // If this case occurs, we have to think about it!
4538 // The Problem is probably due to two degenerated polygons being connected by a bridging, non-degenerated polygon, as somehow one node has
4539 // connections to either polygon ...
4540 if (T->size() % 2 != 0) {
4541 eLog() << Verbose(0) << " degenerated polygon contains an odd number of triangles, probably contains bridging non-degenerated ones, too!" << endl;
4542 performCriticalExit();
4543 }
4544
4545 TriangleSet::iterator TriangleWalker = T->begin(); // is the inner iterator
4546 /// 4a. Get NormalVector for one side (this is "front")
4547 NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
4548 Log() << Verbose(1) << "\"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector << endl;
4549 TriangleWalker++;
4550 TriangleSet::iterator TriangleSprinter = TriangleWalker; // is the inner advanced iterator
4551 /// 4b. Remove all triangles whose NormalVector is in opposite direction (i.e. "back")
4552 BoundaryTriangleSet *triangle = NULL;
4553 while (TriangleSprinter != T->end()) {
4554 TriangleWalker = TriangleSprinter;
4555 triangle = *TriangleWalker;
4556 TriangleSprinter++;
4557 Log() << Verbose(1) << "Current triangle to test for removal: " << *triangle << endl;
4558 if (triangle->NormalVector.ScalarProduct(&NormalVector) < 0) { // if from other side, then delete and remove from list
4559 Log() << Verbose(1) << " Removing ... " << endl;
4560 TriangleNrs.push(triangle->Nr);
4561 T->erase(TriangleWalker);
4562 RemoveTesselationTriangle(triangle);
4563 } else
4564 Log() << Verbose(1) << " Keeping ... " << endl;
4565 }
4566 /// 4c. Copy all "front" triangles but with inverse NormalVector
4567 TriangleWalker = T->begin();
4568 while (TriangleWalker != T->end()) { // go through all front triangles
4569 Log() << Verbose(1) << " Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector << endl;
4570 for (int i = 0; i < 3; i++)
4571 AddTesselationPoint((*TriangleWalker)->endpoints[i]->node, i);
4572 AddTesselationLine(TPS[0], TPS[1], 0);
4573 AddTesselationLine(TPS[0], TPS[2], 1);
4574 AddTesselationLine(TPS[1], TPS[2], 2);
4575 if (TriangleNrs.empty())
4576 eLog() << Verbose(0) << "No more free triangle numbers!" << endl;
4577 BTS = new BoundaryTriangleSet(BLS, TriangleNrs.top()); // copy triangle ...
4578 AddTesselationTriangle(); // ... and add
4579 TriangleNrs.pop();
4580 BTS->NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
4581 BTS->NormalVector.Scale(-1.);
4582 TriangleWalker++;
4583 }
4584 if (!TriangleNrs.empty()) {
4585 eLog() << Verbose(0) << "There have been less triangles created than removed!" << endl;
4586 }
4587 delete(T); // remove the triangleset
4588 }
4589
4590 IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
4591 Log() << Verbose(0) << "Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:" << endl;
4592 IndexToIndex::iterator it;
4593 for (it = SimplyDegeneratedTriangles->begin(); it != SimplyDegeneratedTriangles->end(); it++)
4594 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
4595 delete(SimplyDegeneratedTriangles);
4596
4597 /// 5. exit
4598 UniquePolygonSet::iterator PolygonRunner;
4599 while (!ListofDegeneratedPolygons.empty()) {
4600 PolygonRunner = ListofDegeneratedPolygons.begin();
4601 delete(*PolygonRunner);
4602 ListofDegeneratedPolygons.erase(PolygonRunner);
4603 }
4604
4605 return counter;
4606};
Note: See TracBrowser for help on using the repository browser.