source: src/tesselation.cpp@ b32dbb

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

Fixes and changes to tesselation and concavity measurements.

Here, we implement two attempts for a concavity measure:

  1. Measure concavity per point by looking at neighbouring triangles
    • BoundaryLineSet::CheckConvexityCriterion() split up (calculation of angle outsourced to CalculateConvexity())
    • CHANGE: CalculateConcavityPerBoundaryPoint() uses new concavity measure per BoundaryPointSet containing:
      • concavity per line uses angle instead of +/-1 for line, averaged by number of lines
      • also concavity over all attached triangles uses area of triangle and only in case of concavity, averaged by total area
    • new functions
      • BoundaryLineSet::CalculateConvexity() - calculates the angle between two triangles.
      • BoundaryLineSet::GetOtherTriangle() - for a closed line returns the other triangle for a given one
      • BoundaryTriangleSet::GetThirdLine() - for a given boundary point returns the line of the three which does not contain it (opposite line to a point)
      • CalculateAreaofGeneralTriangle() - calculates area of arbitrary triangle
  1. Measure concavity by the distance to a more convex envelope (i.e. created with bigger sphere radius)

Other unrelated stuff:

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

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