source: src/tesselation.cpp@ 5ec8e3

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

Merge branch 'StructureRefactoring' into stable

Conflicts:

molecuilder/src/analysis_bonds.cpp
molecuilder/src/analysis_bonds.hpp
molecuilder/src/builder.cpp
molecuilder/src/unittests/Makefile.am
molecuilder/src/unittests/TestRunnerMain.cpp

  • TESTFIX: Tesselations/heptan - Due to different implementations of GetCircumCenter() sequence of triangles nodes has changed in degenerate case
  • TESTFIX: Tesselation/1-3 - Due to convexity criterion fourth argument (i.e. the value at the node) has changed.

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

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