source: src/tesselation.cpp@ 5f612ee

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

Merge branch 'Analysis_PairCorrelation' into StructureRefactoring

Conflicts:

molecuilder/src/Makefile.am
molecuilder/src/World.cpp
molecuilder/src/World.hpp
molecuilder/src/boundary.cpp
molecuilder/src/builder.cpp
molecuilder/src/log.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/periodentafel.cpp
molecuilder/src/tesselation.cpp
molecuilder/src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
molecuilder/src/unittests/Makefile.am
molecuilder/src/unittests/bondgraphunittest.cpp
molecuilder/src/unittests/gslvectorunittest.cpp
molecuilder/src/unittests/logunittest.cpp
molecuilder/src/unittests/tesselation_boundarytriangleunittest.hpp
molecuilder/src/vector.cpp
molecuilder/tests/Tesselations/defs.in

Conflicts have been many and too numerous to listen here, just the few general cases

  • new molecule() replaced by World::getInstance().createMolecule()
  • new atom() replaced by World::getInstance().createAtom() where appropriate.
  • Some DoLog()s added interfered with changes to the message produced by Log() << Verbose(.) << ...
  • DoLog() has been erroneously added to TestRunner.cpp as well, there cout is appropriate
  • ...

Additionally, there was a bug in atom::clone(), sort was set to atom::nr of the atom to clone not of the clone itself. This caused a failure of the fragmentation.

This merge has been fully checked from a clean build directory with subsequent configure,make all install and make check.
It configures, compiles and runs all test cases and the test suite without errors.

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

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