source: src/tesselation.cpp@ 9fb860

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

Attempt to fix the tesselation::IsInnerPoint().

We try the IsInnerPoint() as follows:

  1. Find nearest BoundaryPoints - working
  2. Find Closest BoundaryLine's - working
  3. Find closest Triangle that is well aligned (wrt to NormalVector and Distance) - unsure whether correctly working
  4. Check whether alignment is on boundary or inside/outside - working
  5. If on boundary, we check whether it's inside of triangle by intersecting with boundary lines - not working

Hence, we code a wrapper for GSL routines, to - finally - allow for solution of linear system of equations.

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

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