source: src/tesselation.cpp@ f2bb0f

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

Huge Refactoring due to class molecule now being an STL container.

  • molecule::start and molecule::end were dropped. Hence, the usual construct Walker = start while (Walker->next != end) {

Walker = walker->next
...

}
was changed to
for (molecule::iterator iter = begin(); iter != end(); ++iter) {

...

}
and (*iter) used instead of Walker.

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