source: src/tesselation.cpp@ 4ef9b7

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 4ef9b7 was 4e10f5, checked in by Tillmann Crueger <crueger@…>, 14 years ago

Merge branch 'stable' into StructureRefactoring

Conflicts:

src/Actions/WorldAction/CenterOnEdgeAction.cpp
src/Actions/WorldAction/ChangeBoxAction.cpp
src/Actions/WorldAction/RepeatBoxAction.cpp
src/Actions/WorldAction/ScaleBoxAction.cpp
src/World.cpp
src/boundary.cpp

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