source: src/tesselation.cpp@ 124e14

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

FillBoxWithMolecule now allows boundary between filler molecules and the surface.

  • Property mode set to 100644
File size: 210.1 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 GetTerminalPoint.
1103 * Uses PointsOnBoundary and STL stuff.
1104 */
1105TesselPoint * Tesselation::GetTerminalPoint() const
1106{
1107 Info FunctionInfo(__func__);
1108 PointMap::const_iterator Runner = PointsOnBoundary.end();
1109 Runner--;
1110 return (Runner->second->node);
1111};
1112
1113/** PointCloud implementation of GoToNext.
1114 * Uses PointsOnBoundary and STL stuff.
1115 */
1116void Tesselation::GoToNext() const
1117{
1118 Info FunctionInfo(__func__);
1119 if (InternalPointer != PointsOnBoundary.end())
1120 InternalPointer++;
1121};
1122
1123/** PointCloud implementation of GoToPrevious.
1124 * Uses PointsOnBoundary and STL stuff.
1125 */
1126void Tesselation::GoToPrevious() const
1127{
1128 Info FunctionInfo(__func__);
1129 if (InternalPointer != PointsOnBoundary.begin())
1130 InternalPointer--;
1131};
1132
1133/** PointCloud implementation of GoToFirst.
1134 * Uses PointsOnBoundary and STL stuff.
1135 */
1136void Tesselation::GoToFirst() const
1137{
1138 Info FunctionInfo(__func__);
1139 InternalPointer = PointsOnBoundary.begin();
1140};
1141
1142/** PointCloud implementation of GoToLast.
1143 * Uses PointsOnBoundary and STL stuff.
1144 */
1145void Tesselation::GoToLast() const
1146{
1147 Info FunctionInfo(__func__);
1148 InternalPointer = PointsOnBoundary.end();
1149 InternalPointer--;
1150};
1151
1152/** PointCloud implementation of IsEmpty.
1153 * Uses PointsOnBoundary and STL stuff.
1154 */
1155bool Tesselation::IsEmpty() const
1156{
1157 Info FunctionInfo(__func__);
1158 return (PointsOnBoundary.empty());
1159};
1160
1161/** PointCloud implementation of IsLast.
1162 * Uses PointsOnBoundary and STL stuff.
1163 */
1164bool Tesselation::IsEnd() const
1165{
1166 Info FunctionInfo(__func__);
1167 return (InternalPointer == PointsOnBoundary.end());
1168};
1169
1170
1171/** Gueses first starting triangle of the convex envelope.
1172 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
1173 * \param *out output stream for debugging
1174 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
1175 */
1176void
1177Tesselation::GuessStartingTriangle()
1178{
1179 Info FunctionInfo(__func__);
1180 // 4b. create a starting triangle
1181 // 4b1. create all distances
1182 DistanceMultiMap DistanceMMap;
1183 double distance, tmp;
1184 Vector PlaneVector, TrialVector;
1185 PointMap::iterator A, B, C; // three nodes of the first triangle
1186 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
1187
1188 // with A chosen, take each pair B,C and sort
1189 if (A != PointsOnBoundary.end())
1190 {
1191 B = A;
1192 B++;
1193 for (; B != PointsOnBoundary.end(); B++)
1194 {
1195 C = B;
1196 C++;
1197 for (; C != PointsOnBoundary.end(); C++)
1198 {
1199 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
1200 distance = tmp * tmp;
1201 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
1202 distance += tmp * tmp;
1203 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
1204 distance += tmp * tmp;
1205 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
1206 }
1207 }
1208 }
1209 // // listing distances
1210 // Log() << Verbose(1) << "Listing DistanceMMap:";
1211 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
1212 // Log() << Verbose(0) << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
1213 // }
1214 // Log() << Verbose(0) << endl;
1215 // 4b2. pick three baselines forming a triangle
1216 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1217 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
1218 for (; baseline != DistanceMMap.end(); baseline++)
1219 {
1220 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1221 // 2. next, we have to check whether all points reside on only one side of the triangle
1222 // 3. construct plane vector
1223 PlaneVector.MakeNormalVector(A->second->node->node,
1224 baseline->second.first->second->node->node,
1225 baseline->second.second->second->node->node);
1226 Log() << Verbose(2) << "Plane vector of candidate triangle is " << PlaneVector << endl;
1227 // 4. loop over all points
1228 double sign = 0.;
1229 PointMap::iterator checker = PointsOnBoundary.begin();
1230 for (; checker != PointsOnBoundary.end(); checker++)
1231 {
1232 // (neglecting A,B,C)
1233 if ((checker == A) || (checker == baseline->second.first) || (checker
1234 == baseline->second.second))
1235 continue;
1236 // 4a. project onto plane vector
1237 TrialVector.CopyVector(checker->second->node->node);
1238 TrialVector.SubtractVector(A->second->node->node);
1239 distance = TrialVector.ScalarProduct(&PlaneVector);
1240 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
1241 continue;
1242 Log() << Verbose(2) << "Projection of " << checker->second->node->Name << " yields distance of " << distance << "." << endl;
1243 tmp = distance / fabs(distance);
1244 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
1245 if ((sign != 0) && (tmp != sign))
1246 {
1247 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
1248 Log() << Verbose(2) << "Current candidates: "
1249 << A->second->node->Name << ","
1250 << baseline->second.first->second->node->Name << ","
1251 << baseline->second.second->second->node->Name << " leaves "
1252 << checker->second->node->Name << " outside the convex hull."
1253 << endl;
1254 break;
1255 }
1256 else
1257 { // note the sign for later
1258 Log() << Verbose(2) << "Current candidates: "
1259 << A->second->node->Name << ","
1260 << baseline->second.first->second->node->Name << ","
1261 << baseline->second.second->second->node->Name << " leave "
1262 << checker->second->node->Name << " inside the convex hull."
1263 << endl;
1264 sign = tmp;
1265 }
1266 // 4d. Check whether the point is inside the triangle (check distance to each node
1267 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
1268 int innerpoint = 0;
1269 if ((tmp < A->second->node->node->DistanceSquared(
1270 baseline->second.first->second->node->node)) && (tmp
1271 < A->second->node->node->DistanceSquared(
1272 baseline->second.second->second->node->node)))
1273 innerpoint++;
1274 tmp = checker->second->node->node->DistanceSquared(
1275 baseline->second.first->second->node->node);
1276 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
1277 A->second->node->node)) && (tmp
1278 < baseline->second.first->second->node->node->DistanceSquared(
1279 baseline->second.second->second->node->node)))
1280 innerpoint++;
1281 tmp = checker->second->node->node->DistanceSquared(
1282 baseline->second.second->second->node->node);
1283 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
1284 baseline->second.first->second->node->node)) && (tmp
1285 < baseline->second.second->second->node->node->DistanceSquared(
1286 A->second->node->node)))
1287 innerpoint++;
1288 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
1289 if (innerpoint == 3)
1290 break;
1291 }
1292 // 5. come this far, all on same side? Then break 1. loop and construct triangle
1293 if (checker == PointsOnBoundary.end())
1294 {
1295 Log() << Verbose(2) << "Looks like we have a candidate!" << endl;
1296 break;
1297 }
1298 }
1299 if (baseline != DistanceMMap.end())
1300 {
1301 BPS[0] = baseline->second.first->second;
1302 BPS[1] = baseline->second.second->second;
1303 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1304 BPS[0] = A->second;
1305 BPS[1] = baseline->second.second->second;
1306 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1307 BPS[0] = baseline->second.first->second;
1308 BPS[1] = A->second;
1309 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1310
1311 // 4b3. insert created triangle
1312 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1313 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1314 TrianglesOnBoundaryCount++;
1315 for (int i = 0; i < NDIM; i++)
1316 {
1317 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
1318 LinesOnBoundaryCount++;
1319 }
1320
1321 Log() << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
1322 }
1323 else
1324 {
1325 eLog() << Verbose(0) << "No starting triangle found." << endl;
1326 }
1327}
1328;
1329
1330/** Tesselates the convex envelope of a cluster from a single starting triangle.
1331 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
1332 * 2 triangles. Hence, we go through all current lines:
1333 * -# if the lines contains to only one triangle
1334 * -# We search all points in the boundary
1335 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
1336 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
1337 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
1338 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
1339 * \param *out output stream for debugging
1340 * \param *configuration for IsAngstroem
1341 * \param *cloud cluster of points
1342 */
1343void Tesselation::TesselateOnBoundary(const PointCloud * const cloud)
1344{
1345 Info FunctionInfo(__func__);
1346 bool flag;
1347 PointMap::iterator winner;
1348 class BoundaryPointSet *peak = NULL;
1349 double SmallestAngle, TempAngle;
1350 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
1351 LineMap::iterator LineChecker[2];
1352
1353 Center = cloud->GetCenter();
1354 // create a first tesselation with the given BoundaryPoints
1355 do {
1356 flag = false;
1357 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
1358 if (baseline->second->triangles.size() == 1) {
1359 // 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)
1360 SmallestAngle = M_PI;
1361
1362 // get peak point with respect to this base line's only triangle
1363 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
1364 Log() << Verbose(0) << "Current baseline is between " << *(baseline->second) << "." << endl;
1365 for (int i = 0; i < 3; i++)
1366 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
1367 peak = BTS->endpoints[i];
1368 Log() << Verbose(1) << " and has peak " << *peak << "." << endl;
1369
1370 // prepare some auxiliary vectors
1371 Vector BaseLineCenter, BaseLine;
1372 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
1373 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
1374 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
1375 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
1376 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
1377
1378 // offset to center of triangle
1379 CenterVector.Zero();
1380 for (int i = 0; i < 3; i++)
1381 CenterVector.AddVector(BTS->endpoints[i]->node->node);
1382 CenterVector.Scale(1. / 3.);
1383 Log() << Verbose(2) << "CenterVector of base triangle is " << CenterVector << endl;
1384
1385 // normal vector of triangle
1386 NormalVector.CopyVector(Center);
1387 NormalVector.SubtractVector(&CenterVector);
1388 BTS->GetNormalVector(NormalVector);
1389 NormalVector.CopyVector(&BTS->NormalVector);
1390 Log() << Verbose(2) << "NormalVector of base triangle is " << NormalVector << endl;
1391
1392 // vector in propagation direction (out of triangle)
1393 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
1394 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
1395 TempVector.CopyVector(&CenterVector);
1396 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
1397 //Log() << Verbose(0) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
1398 if (PropagationVector.ScalarProduct(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
1399 PropagationVector.Scale(-1.);
1400 Log() << Verbose(2) << "PropagationVector of base triangle is " << PropagationVector << endl;
1401 winner = PointsOnBoundary.end();
1402
1403 // loop over all points and calculate angle between normal vector of new and present triangle
1404 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
1405 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
1406 Log() << Verbose(1) << "Target point is " << *(target->second) << ":" << endl;
1407
1408 // first check direction, so that triangles don't intersect
1409 VirtualNormalVector.CopyVector(target->second->node->node);
1410 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
1411 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
1412 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
1413 Log() << Verbose(2) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
1414 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
1415 Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
1416 continue;
1417 } else
1418 Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
1419
1420 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
1421 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
1422 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
1423 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->triangles.size() == 2))) {
1424 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;
1425 continue;
1426 }
1427 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->triangles.size() == 2))) {
1428 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;
1429 continue;
1430 }
1431
1432 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
1433 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)))) {
1434 Log() << Verbose(4) << "Current target is peak!" << endl;
1435 continue;
1436 }
1437
1438 // check for linear dependence
1439 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1440 TempVector.SubtractVector(target->second->node->node);
1441 helper.CopyVector(baseline->second->endpoints[1]->node->node);
1442 helper.SubtractVector(target->second->node->node);
1443 helper.ProjectOntoPlane(&TempVector);
1444 if (fabs(helper.NormSquared()) < MYEPSILON) {
1445 Log() << Verbose(2) << "Chosen set of vectors is linear dependent." << endl;
1446 continue;
1447 }
1448
1449 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
1450 flag = true;
1451 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
1452 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1453 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
1454 TempVector.AddVector(target->second->node->node);
1455 TempVector.Scale(1./3.);
1456 TempVector.SubtractVector(Center);
1457 // make it always point outward
1458 if (VirtualNormalVector.ScalarProduct(&TempVector) < 0)
1459 VirtualNormalVector.Scale(-1.);
1460 // calculate angle
1461 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1462 Log() << Verbose(2) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
1463 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
1464 SmallestAngle = TempAngle;
1465 winner = target;
1466 Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1467 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
1468 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
1469 helper.CopyVector(target->second->node->node);
1470 helper.SubtractVector(&BaseLineCenter);
1471 helper.ProjectOntoPlane(&BaseLine);
1472 // ...the one with the smaller angle is the better candidate
1473 TempVector.CopyVector(target->second->node->node);
1474 TempVector.SubtractVector(&BaseLineCenter);
1475 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1476 TempAngle = TempVector.Angle(&helper);
1477 TempVector.CopyVector(winner->second->node->node);
1478 TempVector.SubtractVector(&BaseLineCenter);
1479 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1480 if (TempAngle < TempVector.Angle(&helper)) {
1481 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1482 SmallestAngle = TempAngle;
1483 winner = target;
1484 Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
1485 } else
1486 Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
1487 } else
1488 Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1489 }
1490 } // end of loop over all boundary points
1491
1492 // 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
1493 if (winner != PointsOnBoundary.end()) {
1494 Log() << Verbose(0) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
1495 // create the lins of not yet present
1496 BLS[0] = baseline->second;
1497 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1498 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
1499 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
1500 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
1501 BPS[0] = baseline->second->endpoints[0];
1502 BPS[1] = winner->second;
1503 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1504 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
1505 LinesOnBoundaryCount++;
1506 } else
1507 BLS[1] = LineChecker[0]->second;
1508 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
1509 BPS[0] = baseline->second->endpoints[1];
1510 BPS[1] = winner->second;
1511 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1512 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
1513 LinesOnBoundaryCount++;
1514 } else
1515 BLS[2] = LineChecker[1]->second;
1516 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1517 BTS->GetCenter(&helper);
1518 helper.SubtractVector(Center);
1519 helper.Scale(-1);
1520 BTS->GetNormalVector(helper);
1521 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1522 TrianglesOnBoundaryCount++;
1523 } else {
1524 eLog() << Verbose(2) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
1525 }
1526
1527 // 5d. If the set of lines is not yet empty, go to 5. and continue
1528 } else
1529 Log() << Verbose(0) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl;
1530 } while (flag);
1531
1532 // exit
1533 delete(Center);
1534};
1535
1536/** Inserts all points outside of the tesselated surface into it by adding new triangles.
1537 * \param *out output stream for debugging
1538 * \param *cloud cluster of points
1539 * \param *LC LinkedCell structure to find nearest point quickly
1540 * \return true - all straddling points insert, false - something went wrong
1541 */
1542bool Tesselation::InsertStraddlingPoints(const PointCloud *cloud, const LinkedCell *LC)
1543{
1544 Info FunctionInfo(__func__);
1545 Vector Intersection, Normal;
1546 TesselPoint *Walker = NULL;
1547 Vector *Center = cloud->GetCenter();
1548 TriangleList *triangles = NULL;
1549 bool AddFlag = false;
1550 LinkedCell *BoundaryPoints = NULL;
1551
1552 cloud->GoToFirst();
1553 BoundaryPoints = new LinkedCell(this, 5.);
1554 while (!cloud->IsEnd()) { // we only have to go once through all points, as boundary can become only bigger
1555 if (AddFlag) {
1556 delete(BoundaryPoints);
1557 BoundaryPoints = new LinkedCell(this, 5.);
1558 AddFlag = false;
1559 }
1560 Walker = cloud->GetPoint();
1561 Log() << Verbose(0) << "Current point is " << *Walker << "." << endl;
1562 // get the next triangle
1563 triangles = FindClosestTrianglesToVector(Walker->node, BoundaryPoints);
1564 BTS = triangles->front();
1565 if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
1566 Log() << Verbose(0) << "No triangles found, probably a tesselation point itself." << endl;
1567 cloud->GoToNext();
1568 continue;
1569 } else {
1570 }
1571 Log() << Verbose(0) << "Closest triangle is " << *BTS << "." << endl;
1572 // get the intersection point
1573 if (BTS->GetIntersectionInsideTriangle(Center, Walker->node, &Intersection)) {
1574 Log() << Verbose(0) << "We have an intersection at " << Intersection << "." << endl;
1575 // we have the intersection, check whether in- or outside of boundary
1576 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
1577 // inside, next!
1578 Log() << Verbose(0) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
1579 } else {
1580 // outside!
1581 Log() << Verbose(0) << *Walker << " is outside wrt triangle " << *BTS << "." << endl;
1582 class BoundaryLineSet *OldLines[3], *NewLines[3];
1583 class BoundaryPointSet *OldPoints[3], *NewPoint;
1584 // store the three old lines and old points
1585 for (int i=0;i<3;i++) {
1586 OldLines[i] = BTS->lines[i];
1587 OldPoints[i] = BTS->endpoints[i];
1588 }
1589 Normal.CopyVector(&BTS->NormalVector);
1590 // add Walker to boundary points
1591 Log() << Verbose(0) << "Adding " << *Walker << " to BoundaryPoints." << endl;
1592 AddFlag = true;
1593 if (AddBoundaryPoint(Walker,0))
1594 NewPoint = BPS[0];
1595 else
1596 continue;
1597 // remove triangle
1598 Log() << Verbose(0) << "Erasing triangle " << *BTS << "." << endl;
1599 TrianglesOnBoundary.erase(BTS->Nr);
1600 delete(BTS);
1601 // create three new boundary lines
1602 for (int i=0;i<3;i++) {
1603 BPS[0] = NewPoint;
1604 BPS[1] = OldPoints[i];
1605 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1606 Log() << Verbose(1) << "Creating new line " << *NewLines[i] << "." << endl;
1607 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
1608 LinesOnBoundaryCount++;
1609 }
1610 // create three new triangle with new point
1611 for (int i=0;i<3;i++) { // find all baselines
1612 BLS[0] = OldLines[i];
1613 int n = 1;
1614 for (int j=0;j<3;j++) {
1615 if (NewLines[j]->IsConnectedTo(BLS[0])) {
1616 if (n>2) {
1617 eLog() << Verbose(2) << BLS[0] << " connects to all of the new lines?!" << endl;
1618 return false;
1619 } else
1620 BLS[n++] = NewLines[j];
1621 }
1622 }
1623 // create the triangle
1624 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1625 Normal.Scale(-1.);
1626 BTS->GetNormalVector(Normal);
1627 Normal.Scale(-1.);
1628 Log() << Verbose(0) << "Created new triangle " << *BTS << "." << endl;
1629 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1630 TrianglesOnBoundaryCount++;
1631 }
1632 }
1633 } else { // something is wrong with FindClosestTriangleToPoint!
1634 eLog() << Verbose(1) << "The closest triangle did not produce an intersection!" << endl;
1635 return false;
1636 }
1637 cloud->GoToNext();
1638 }
1639
1640 // exit
1641 delete(Center);
1642 return true;
1643};
1644
1645/** Adds a point to the tesselation::PointsOnBoundary list.
1646 * \param *Walker point to add
1647 * \param n TesselStruct::BPS index to put pointer into
1648 * \return true - new point was added, false - point already present
1649 */
1650bool Tesselation::AddBoundaryPoint(TesselPoint * Walker, const int n)
1651{
1652 Info FunctionInfo(__func__);
1653 PointTestPair InsertUnique;
1654 BPS[n] = new class BoundaryPointSet(Walker);
1655 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[n]));
1656 if (InsertUnique.second) { // if new point was not present before, increase counter
1657 PointsOnBoundaryCount++;
1658 return true;
1659 } else {
1660 delete(BPS[n]);
1661 BPS[n] = InsertUnique.first->second;
1662 return false;
1663 }
1664}
1665;
1666
1667/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1668 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1669 * @param Candidate point to add
1670 * @param n index for this point in Tesselation::TPS array
1671 */
1672void Tesselation::AddTesselationPoint(TesselPoint* Candidate, const int n)
1673{
1674 Info FunctionInfo(__func__);
1675 PointTestPair InsertUnique;
1676 TPS[n] = new class BoundaryPointSet(Candidate);
1677 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1678 if (InsertUnique.second) { // if new point was not present before, increase counter
1679 PointsOnBoundaryCount++;
1680 } else {
1681 delete TPS[n];
1682 Log() << Verbose(0) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1683 TPS[n] = (InsertUnique.first)->second;
1684 }
1685}
1686;
1687
1688/** Sets point to a present Tesselation::PointsOnBoundary.
1689 * Tesselation::TPS is set to the existing one or NULL if not found.
1690 * @param Candidate point to set to
1691 * @param n index for this point in Tesselation::TPS array
1692 */
1693void Tesselation::SetTesselationPoint(TesselPoint* Candidate, const int n) const
1694{
1695 Info FunctionInfo(__func__);
1696 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidate->nr);
1697 if (FindPoint != PointsOnBoundary.end())
1698 TPS[n] = FindPoint->second;
1699 else
1700 TPS[n] = NULL;
1701};
1702
1703/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1704 * If successful it raises the line count and inserts the new line into the BLS,
1705 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1706 * @param *a first endpoint
1707 * @param *b second endpoint
1708 * @param n index of Tesselation::BLS giving the line with both endpoints
1709 */
1710void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n) {
1711 bool insertNewLine = true;
1712
1713 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1714 if (FindLine != a->lines.end()) {
1715 Log() << Verbose(1) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1716
1717 pair<LineMap::iterator,LineMap::iterator> FindPair;
1718 FindPair = a->lines.equal_range(b->node->nr);
1719
1720 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1721 // If there is a line with less than two attached triangles, we don't need a new line.
1722 if (FindLine->second->triangles.size() < 2) {
1723 insertNewLine = false;
1724 Log() << Verbose(0) << "Using existing line " << *FindLine->second << endl;
1725
1726 BPS[0] = FindLine->second->endpoints[0];
1727 BPS[1] = FindLine->second->endpoints[1];
1728 BLS[n] = FindLine->second;
1729
1730 // remove existing line from OpenLines
1731 CandidateMap::iterator CandidateLine = OpenLines.find(BLS[n]);
1732 if (CandidateLine != OpenLines.end()) {
1733 Log() << Verbose(1) << " Removing line from OpenLines." << endl;
1734 delete(CandidateLine->second);
1735 OpenLines.erase(CandidateLine);
1736 } else {
1737 eLog() << Verbose(1) << "Line exists and is attached to less than two triangles, but not in OpenLines!" << endl;
1738 }
1739
1740 break;
1741 }
1742 }
1743 }
1744
1745 if (insertNewLine) {
1746 AlwaysAddTesselationTriangleLine(a, b, n);
1747 }
1748}
1749;
1750
1751/**
1752 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1753 * Raises the line count and inserts the new line into the BLS.
1754 *
1755 * @param *a first endpoint
1756 * @param *b second endpoint
1757 * @param n index of Tesselation::BLS giving the line with both endpoints
1758 */
1759void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
1760{
1761 Info FunctionInfo(__func__);
1762 Log() << Verbose(0) << "Adding open line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1763 BPS[0] = a;
1764 BPS[1] = b;
1765 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1766 // add line to global map
1767 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1768 // increase counter
1769 LinesOnBoundaryCount++;
1770 // also add to open lines
1771 CandidateForTesselation *CFT = new CandidateForTesselation(BLS[n]);
1772 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (BLS[n], CFT));
1773};
1774
1775/** Function adds triangle to global list.
1776 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1777 */
1778void Tesselation::AddTesselationTriangle()
1779{
1780 Info FunctionInfo(__func__);
1781 Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1782
1783 // add triangle to global map
1784 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1785 TrianglesOnBoundaryCount++;
1786
1787 // set as last new triangle
1788 LastTriangle = BTS;
1789
1790 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1791};
1792
1793/** Function adds triangle to global list.
1794 * Furthermore, the triangle number is set to \a nr.
1795 * \param nr triangle number
1796 */
1797void Tesselation::AddTesselationTriangle(const int nr)
1798{
1799 Info FunctionInfo(__func__);
1800 Log() << Verbose(0) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1801
1802 // add triangle to global map
1803 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1804
1805 // set as last new triangle
1806 LastTriangle = BTS;
1807
1808 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1809};
1810
1811/** Removes a triangle from the tesselation.
1812 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1813 * Removes itself from memory.
1814 * \param *triangle to remove
1815 */
1816void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1817{
1818 Info FunctionInfo(__func__);
1819 if (triangle == NULL)
1820 return;
1821 for (int i = 0; i < 3; i++) {
1822 if (triangle->lines[i] != NULL) {
1823 Log() << Verbose(0) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1824 triangle->lines[i]->triangles.erase(triangle->Nr);
1825 if (triangle->lines[i]->triangles.empty()) {
1826 Log() << Verbose(0) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1827 RemoveTesselationLine(triangle->lines[i]);
1828 } else {
1829 Log() << Verbose(0) << *triangle->lines[i] << " is still attached to another triangle: ";
1830 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (triangle->lines[i], NULL));
1831 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1832 Log() << Verbose(0) << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1833 Log() << Verbose(0) << endl;
1834// for (int j=0;j<2;j++) {
1835// Log() << Verbose(0) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1836// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1837// Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1838// Log() << Verbose(0) << endl;
1839// }
1840 }
1841 triangle->lines[i] = NULL; // free'd or not: disconnect
1842 } else
1843 eLog() << Verbose(1) << "This line " << i << " has already been free'd." << endl;
1844 }
1845
1846 if (TrianglesOnBoundary.erase(triangle->Nr))
1847 Log() << Verbose(0) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1848 delete(triangle);
1849};
1850
1851/** Removes a line from the tesselation.
1852 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1853 * \param *line line to remove
1854 */
1855void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1856{
1857 Info FunctionInfo(__func__);
1858 int Numbers[2];
1859
1860 if (line == NULL)
1861 return;
1862 // get other endpoint number for finding copies of same line
1863 if (line->endpoints[1] != NULL)
1864 Numbers[0] = line->endpoints[1]->Nr;
1865 else
1866 Numbers[0] = -1;
1867 if (line->endpoints[0] != NULL)
1868 Numbers[1] = line->endpoints[0]->Nr;
1869 else
1870 Numbers[1] = -1;
1871
1872 for (int i = 0; i < 2; i++) {
1873 if (line->endpoints[i] != NULL) {
1874 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
1875 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
1876 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
1877 if ((*Runner).second == line) {
1878 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1879 line->endpoints[i]->lines.erase(Runner);
1880 break;
1881 }
1882 } else { // there's just a single line left
1883 if (line->endpoints[i]->lines.erase(line->Nr))
1884 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1885 }
1886 if (line->endpoints[i]->lines.empty()) {
1887 Log() << Verbose(0) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
1888 RemoveTesselationPoint(line->endpoints[i]);
1889 } else {
1890 Log() << Verbose(0) << *line->endpoints[i] << " has still lines it's attached to: ";
1891 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
1892 Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1893 Log() << Verbose(0) << endl;
1894 }
1895 line->endpoints[i] = NULL; // free'd or not: disconnect
1896 } else
1897 eLog() << Verbose(1) << "Endpoint " << i << " has already been free'd." << endl;
1898 }
1899 if (!line->triangles.empty())
1900 eLog() << Verbose(2) << "Memory Leak! I " << *line << " am still connected to some triangles." << endl;
1901
1902 if (LinesOnBoundary.erase(line->Nr))
1903 Log() << Verbose(0) << "Removing line Nr. " << line->Nr << "." << endl;
1904 delete(line);
1905};
1906
1907/** Removes a point from the tesselation.
1908 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
1909 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
1910 * \param *point point to remove
1911 */
1912void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
1913{
1914 Info FunctionInfo(__func__);
1915 if (point == NULL)
1916 return;
1917 if (PointsOnBoundary.erase(point->Nr))
1918 Log() << Verbose(0) << "Removing point Nr. " << point->Nr << "." << endl;
1919 delete(point);
1920};
1921
1922/** Checks whether the triangle consisting of the three points is already present.
1923 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1924 * lines. If any of the three edges already has two triangles attached, false is
1925 * returned.
1926 * \param *out output stream for debugging
1927 * \param *Candidates endpoints of the triangle candidate
1928 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1929 * triangles exist which is the maximum for three points
1930 */
1931int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) const
1932{
1933 Info FunctionInfo(__func__);
1934 int adjacentTriangleCount = 0;
1935 class BoundaryPointSet *Points[3];
1936
1937 // builds a triangle point set (Points) of the end points
1938 for (int i = 0; i < 3; i++) {
1939 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1940 if (FindPoint != PointsOnBoundary.end()) {
1941 Points[i] = FindPoint->second;
1942 } else {
1943 Points[i] = NULL;
1944 }
1945 }
1946
1947 // checks lines between the points in the Points for their adjacent triangles
1948 for (int i = 0; i < 3; i++) {
1949 if (Points[i] != NULL) {
1950 for (int j = i; j < 3; j++) {
1951 if (Points[j] != NULL) {
1952 LineMap::const_iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1953 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1954 TriangleMap *triangles = &FindLine->second->triangles;
1955 Log() << Verbose(1) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1956 for (TriangleMap::const_iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1957 if (FindTriangle->second->IsPresentTupel(Points)) {
1958 adjacentTriangleCount++;
1959 }
1960 }
1961 Log() << Verbose(1) << "end." << endl;
1962 }
1963 // Only one of the triangle lines must be considered for the triangle count.
1964 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1965 //return adjacentTriangleCount;
1966 }
1967 }
1968 }
1969 }
1970
1971 Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1972 return adjacentTriangleCount;
1973};
1974
1975/** Checks whether the triangle consisting of the three points is already present.
1976 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1977 * lines. If any of the three edges already has two triangles attached, false is
1978 * returned.
1979 * \param *out output stream for debugging
1980 * \param *Candidates endpoints of the triangle candidate
1981 * \return NULL - none found or pointer to triangle
1982 */
1983class BoundaryTriangleSet * Tesselation::GetPresentTriangle(TesselPoint *Candidates[3])
1984{
1985 Info FunctionInfo(__func__);
1986 class BoundaryTriangleSet *triangle = NULL;
1987 class BoundaryPointSet *Points[3];
1988
1989 // builds a triangle point set (Points) of the end points
1990 for (int i = 0; i < 3; i++) {
1991 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1992 if (FindPoint != PointsOnBoundary.end()) {
1993 Points[i] = FindPoint->second;
1994 } else {
1995 Points[i] = NULL;
1996 }
1997 }
1998
1999 // checks lines between the points in the Points for their adjacent triangles
2000 for (int i = 0; i < 3; i++) {
2001 if (Points[i] != NULL) {
2002 for (int j = i; j < 3; j++) {
2003 if (Points[j] != NULL) {
2004 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
2005 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
2006 TriangleMap *triangles = &FindLine->second->triangles;
2007 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
2008 if (FindTriangle->second->IsPresentTupel(Points)) {
2009 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
2010 triangle = FindTriangle->second;
2011 }
2012 }
2013 }
2014 // Only one of the triangle lines must be considered for the triangle count.
2015 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
2016 //return adjacentTriangleCount;
2017 }
2018 }
2019 }
2020 }
2021
2022 return triangle;
2023};
2024
2025
2026/** Finds the starting triangle for FindNonConvexBorder().
2027 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
2028 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
2029 * point are called.
2030 * \param *out output stream for debugging
2031 * \param RADIUS radius of virtual rolling sphere
2032 * \param *LC LinkedCell structure with neighbouring TesselPoint's
2033 */
2034void Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
2035{
2036 Info FunctionInfo(__func__);
2037 int i = 0;
2038 TesselPoint* MaxPoint[NDIM];
2039 TesselPoint* Temporary;
2040 double maxCoordinate[NDIM];
2041 BoundaryLineSet BaseLine;
2042 Vector helper;
2043 Vector Chord;
2044 Vector SearchDirection;
2045 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2046 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2047 Vector SphereCenter;
2048 Vector NormalVector;
2049
2050 NormalVector.Zero();
2051
2052 for (i = 0; i < 3; i++) {
2053 MaxPoint[i] = NULL;
2054 maxCoordinate[i] = -1;
2055 }
2056
2057 // 1. searching topmost point with respect to each axis
2058 for (int i=0;i<NDIM;i++) { // each axis
2059 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
2060 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
2061 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
2062 const LinkedNodes *List = LC->GetCurrentCell();
2063 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2064 if (List != NULL) {
2065 for (LinkedNodes::const_iterator Runner = List->begin();Runner != List->end();Runner++) {
2066 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
2067 Log() << Verbose(1) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
2068 maxCoordinate[i] = (*Runner)->node->x[i];
2069 MaxPoint[i] = (*Runner);
2070 }
2071 }
2072 } else {
2073 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
2074 }
2075 }
2076 }
2077
2078 Log() << Verbose(1) << "Found maximum coordinates: ";
2079 for (int i=0;i<NDIM;i++)
2080 Log() << Verbose(0) << i << ": " << *MaxPoint[i] << "\t";
2081 Log() << Verbose(0) << endl;
2082
2083 BTS = NULL;
2084 for (int k=0;k<NDIM;k++) {
2085 NormalVector.Zero();
2086 NormalVector.x[k] = 1.;
2087 BaseLine.endpoints[0] = new BoundaryPointSet(MaxPoint[k]);
2088 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
2089
2090 double ShortestAngle;
2091 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.
2092
2093 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_...
2094 if (Temporary == NULL) // have we found a second point?
2095 continue;
2096 BaseLine.endpoints[1] = new BoundaryPointSet(Temporary);
2097
2098 // construct center of circle
2099 CircleCenter.CopyVector(BaseLine.endpoints[0]->node->node);
2100 CircleCenter.AddVector(BaseLine.endpoints[1]->node->node);
2101 CircleCenter.Scale(0.5);
2102
2103 // construct normal vector of circle
2104 CirclePlaneNormal.CopyVector(BaseLine.endpoints[0]->node->node);
2105 CirclePlaneNormal.SubtractVector(BaseLine.endpoints[1]->node->node);
2106
2107 double radius = CirclePlaneNormal.NormSquared();
2108 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
2109
2110 NormalVector.ProjectOntoPlane(&CirclePlaneNormal);
2111 NormalVector.Normalize();
2112 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2113
2114 SphereCenter.CopyVector(&NormalVector);
2115 SphereCenter.Scale(CircleRadius);
2116 SphereCenter.AddVector(&CircleCenter);
2117 // Now, NormalVector and SphereCenter are two orthonormalized vectors in the plane defined by CirclePlaneNormal (not normalized)
2118
2119 // look in one direction of baseline for initial candidate
2120 SearchDirection.MakeNormalVector(&CirclePlaneNormal, &NormalVector); // whether we look "left" first or "right" first is not important ...
2121
2122 // adding point 1 and point 2 and add the line between them
2123 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
2124 Log() << Verbose(0) << "Found second point is at " << *BaseLine.endpoints[1]->node << ".\n";
2125
2126 //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << helper << ".\n";
2127 CandidateForTesselation OptCandidates(&BaseLine);
2128 FindThirdPointForTesselation(NormalVector, SearchDirection, SphereCenter, OptCandidates, NULL, RADIUS, LC);
2129 Log() << Verbose(0) << "List of third Points is:" << endl;
2130 for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); it++) {
2131 Log() << Verbose(0) << " " << *(*it) << endl;
2132 }
2133
2134 BTS = NULL;
2135 AddCandidateTriangle(OptCandidates);
2136// delete(BaseLine.endpoints[0]);
2137// delete(BaseLine.endpoints[1]);
2138
2139 if (BTS != NULL) // we have created one starting triangle
2140 break;
2141 else {
2142 // remove all candidates from the list and then the list itself
2143 OptCandidates.pointlist.clear();
2144 }
2145 }
2146};
2147
2148/** Checks for a given baseline and a third point candidate whether baselines of the found triangle don't have even better candidates.
2149 * This is supposed to prevent early closing of the tesselation.
2150 * \param CandidateLine CandidateForTesselation with baseline and shortestangle , i.e. not \a *OptCandidate
2151 * \param *ThirdNode third point in triangle, not in BoundaryLineSet::endpoints
2152 * \param RADIUS radius of sphere
2153 * \param *LC LinkedCell structure
2154 * \return true - there is a better candidate (smaller angle than \a ShortestAngle), false - no better TesselPoint candidate found
2155 */
2156//bool Tesselation::HasOtherBaselineBetterCandidate(CandidateForTesselation &CandidateLine, const TesselPoint * const ThirdNode, double RADIUS, const LinkedCell * const LC) const
2157//{
2158// Info FunctionInfo(__func__);
2159// bool result = false;
2160// Vector CircleCenter;
2161// Vector CirclePlaneNormal;
2162// Vector OldSphereCenter;
2163// Vector SearchDirection;
2164// Vector helper;
2165// TesselPoint *OtherOptCandidate = NULL;
2166// double OtherShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2167// double radius, CircleRadius;
2168// BoundaryLineSet *Line = NULL;
2169// BoundaryTriangleSet *T = NULL;
2170//
2171// // check both other lines
2172// PointMap::const_iterator FindPoint = PointsOnBoundary.find(ThirdNode->nr);
2173// if (FindPoint != PointsOnBoundary.end()) {
2174// for (int i=0;i<2;i++) {
2175// LineMap::const_iterator FindLine = (FindPoint->second)->lines.find(BaseRay->endpoints[0]->node->nr);
2176// if (FindLine != (FindPoint->second)->lines.end()) {
2177// Line = FindLine->second;
2178// Log() << Verbose(0) << "Found line " << *Line << "." << endl;
2179// if (Line->triangles.size() == 1) {
2180// T = Line->triangles.begin()->second;
2181// // construct center of circle
2182// CircleCenter.CopyVector(Line->endpoints[0]->node->node);
2183// CircleCenter.AddVector(Line->endpoints[1]->node->node);
2184// CircleCenter.Scale(0.5);
2185//
2186// // construct normal vector of circle
2187// CirclePlaneNormal.CopyVector(Line->endpoints[0]->node->node);
2188// CirclePlaneNormal.SubtractVector(Line->endpoints[1]->node->node);
2189//
2190// // calculate squared radius of circle
2191// radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2192// if (radius/4. < RADIUS*RADIUS) {
2193// CircleRadius = RADIUS*RADIUS - radius/4.;
2194// CirclePlaneNormal.Normalize();
2195// //Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2196//
2197// // construct old center
2198// GetCenterofCircumcircle(&OldSphereCenter, *T->endpoints[0]->node->node, *T->endpoints[1]->node->node, *T->endpoints[2]->node->node);
2199// helper.CopyVector(&T->NormalVector); // normal vector ensures that this is correct center of the two possible ones
2200// radius = Line->endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
2201// helper.Scale(sqrt(RADIUS*RADIUS - radius));
2202// OldSphereCenter.AddVector(&helper);
2203// OldSphereCenter.SubtractVector(&CircleCenter);
2204// //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2205//
2206// // construct SearchDirection
2207// SearchDirection.MakeNormalVector(&T->NormalVector, &CirclePlaneNormal);
2208// helper.CopyVector(Line->endpoints[0]->node->node);
2209// helper.SubtractVector(ThirdNode->node);
2210// if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2211// SearchDirection.Scale(-1.);
2212// SearchDirection.ProjectOntoPlane(&OldSphereCenter);
2213// SearchDirection.Normalize();
2214// Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2215// if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2216// // rotated the wrong way!
2217// eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2218// }
2219//
2220// // add third point
2221// FindThirdPointForTesselation(T->NormalVector, SearchDirection, OldSphereCenter, OptCandidates, ThirdNode, RADIUS, LC);
2222// for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); ++it) {
2223// if (((*it) == BaseRay->endpoints[0]->node) || ((*it) == BaseRay->endpoints[1]->node)) // skip if it's the same triangle than suggested
2224// continue;
2225// Log() << Verbose(0) << " Third point candidate is " << (*it)
2226// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2227// Log() << Verbose(0) << " Baseline is " << *BaseRay << endl;
2228//
2229// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2230// TesselPoint *PointCandidates[3];
2231// PointCandidates[0] = (*it);
2232// PointCandidates[1] = BaseRay->endpoints[0]->node;
2233// PointCandidates[2] = BaseRay->endpoints[1]->node;
2234// bool check=false;
2235// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2236// // If there is no triangle, add it regularly.
2237// if (existentTrianglesCount == 0) {
2238// SetTesselationPoint((*it), 0);
2239// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2240// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2241//
2242// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2243// OtherOptCandidate = (*it);
2244// check = true;
2245// }
2246// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2247// SetTesselationPoint((*it), 0);
2248// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2249// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2250//
2251// // 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)
2252// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2253// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS)) {
2254// OtherOptCandidate = (*it);
2255// check = true;
2256// }
2257// }
2258//
2259// if (check) {
2260// if (ShortestAngle > OtherShortestAngle) {
2261// Log() << Verbose(0) << "There is a better candidate than " << *ThirdNode << " with " << ShortestAngle << " from baseline " << *Line << ": " << *OtherOptCandidate << " with " << OtherShortestAngle << "." << endl;
2262// result = true;
2263// break;
2264// }
2265// }
2266// }
2267// delete(OptCandidates);
2268// if (result)
2269// break;
2270// } else {
2271// Log() << Verbose(0) << "Circumcircle for base line " << *Line << " and base triangle " << T << " is too big!" << endl;
2272// }
2273// } else {
2274// eLog() << Verbose(2) << "Baseline is connected to two triangles already?" << endl;
2275// }
2276// } else {
2277// Log() << Verbose(1) << "No present baseline between " << BaseRay->endpoints[0] << " and candidate " << *ThirdNode << "." << endl;
2278// }
2279// }
2280// } else {
2281// eLog() << Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl;
2282// }
2283//
2284// return result;
2285//};
2286
2287/** This function finds a triangle to a line, adjacent to an existing one.
2288 * @param out output stream for debugging
2289 * @param CandidateLine current cadndiate baseline to search from
2290 * @param T current triangle which \a Line is edge of
2291 * @param RADIUS radius of the rolling ball
2292 * @param N number of found triangles
2293 * @param *LC LinkedCell structure with neighbouring points
2294 */
2295bool Tesselation::FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
2296{
2297 Info FunctionInfo(__func__);
2298 bool result = true;
2299
2300 Vector CircleCenter;
2301 Vector CirclePlaneNormal;
2302 Vector RelativeSphereCenter;
2303 Vector SearchDirection;
2304 Vector helper;
2305 TesselPoint *ThirdNode = NULL;
2306 LineMap::iterator testline;
2307 double radius, CircleRadius;
2308
2309 for (int i=0;i<3;i++)
2310 if ((T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[0]->node) && (T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[1]->node)) {
2311 ThirdNode = T.endpoints[i]->node;
2312 break;
2313 }
2314 Log() << Verbose(0) << "Current baseline is " << *CandidateLine.BaseLine << " with ThirdNode " << *ThirdNode << " of triangle " << T << "." << endl;
2315
2316 // construct center of circle
2317 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2318 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2319 CircleCenter.Scale(0.5);
2320
2321 // construct normal vector of circle
2322 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2323 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2324
2325 // calculate squared radius of circle
2326 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2327 if (radius/4. < RADIUS*RADIUS) {
2328 // construct relative sphere center with now known CircleCenter
2329 RelativeSphereCenter.CopyVector(&T.SphereCenter);
2330 RelativeSphereCenter.SubtractVector(&CircleCenter);
2331
2332 CircleRadius = RADIUS*RADIUS - radius/4.;
2333 CirclePlaneNormal.Normalize();
2334 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2335
2336 Log() << Verbose(1) << "INFO: OldSphereCenter is at " << T.SphereCenter << "." << endl;
2337
2338 // construct SearchDirection and an "outward pointer"
2339 SearchDirection.MakeNormalVector(&RelativeSphereCenter, &CirclePlaneNormal);
2340 helper.CopyVector(&CircleCenter);
2341 helper.SubtractVector(ThirdNode->node);
2342 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2343 SearchDirection.Scale(-1.);
2344 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2345 if (fabs(RelativeSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2346 // rotated the wrong way!
2347 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2348 }
2349
2350 // add third point
2351 FindThirdPointForTesselation(T.NormalVector, SearchDirection, T.SphereCenter, CandidateLine, ThirdNode, RADIUS, LC);
2352
2353 } else {
2354 Log() << Verbose(0) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and base triangle " << T << " is too big!" << endl;
2355 }
2356
2357 if (CandidateLine.pointlist.empty()) {
2358 eLog() << Verbose(2) << "Could not find a suitable candidate." << endl;
2359 return false;
2360 }
2361 Log() << Verbose(0) << "Third Points are: " << endl;
2362 for (TesselPointList::iterator it = CandidateLine.pointlist.begin(); it != CandidateLine.pointlist.end(); ++it) {
2363 Log() << Verbose(0) << " " << *(*it) << endl;
2364 }
2365
2366 return true;
2367
2368// BoundaryLineSet *BaseRay = CandidateLine.BaseLine;
2369// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2370// Log() << Verbose(0) << "Third point candidate is " << *(*it)->point
2371// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2372// Log() << Verbose(0) << "Baseline is " << *BaseRay << endl;
2373//
2374// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2375// TesselPoint *PointCandidates[3];
2376// PointCandidates[0] = (*it)->point;
2377// PointCandidates[1] = BaseRay->endpoints[0]->node;
2378// PointCandidates[2] = BaseRay->endpoints[1]->node;
2379// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2380//
2381// BTS = NULL;
2382// // check for present edges and whether we reach better candidates from them
2383// //if (HasOtherBaselineBetterCandidate(BaseRay, (*it)->point, ShortestAngle, RADIUS, LC) ) {
2384// if (0) {
2385// result = false;
2386// break;
2387// } else {
2388// // If there is no triangle, add it regularly.
2389// if (existentTrianglesCount == 0) {
2390// AddTesselationPoint((*it)->point, 0);
2391// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2392// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2393//
2394// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2395// CandidateLine.point = (*it)->point;
2396// CandidateLine.OptCenter.CopyVector(&((*it)->OptCenter));
2397// CandidateLine.OtherOptCenter.CopyVector(&((*it)->OtherOptCenter));
2398// CandidateLine.ShortestAngle = ShortestAngle;
2399// } else {
2400//// eLog() << Verbose(1) << "This triangle consisting of ";
2401//// Log() << Verbose(0) << *(*it)->point << ", ";
2402//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2403//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2404//// Log() << Verbose(0) << "exists and is not added, as it 0x80000000006fc150(does not seem helpful!" << endl;
2405// result = false;
2406// }
2407// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2408// AddTesselationPoint((*it)->point, 0);
2409// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2410// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2411//
2412// // 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)
2413// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2414// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS) || CandidateLine.BaseLine->skipped) {
2415// CandidateLine.point = (*it)->point;
2416// CandidateLine.OptCenter.CopyVector(&(*it)->OptCenter);
2417// CandidateLine.OtherOptCenter.CopyVector(&(*it)->OtherOptCenter);
2418// CandidateLine.ShortestAngle = ShortestAngle+2.*M_PI;
2419//
2420// } else {
2421//// 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;
2422// result = false;
2423// }
2424// } else {
2425//// Log() << Verbose(1) << "This triangle consisting of ";
2426//// Log() << Verbose(0) << *(*it)->point << ", ";
2427//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2428//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2429//// Log() << Verbose(0) << "is invalid!" << endl;
2430// result = false;
2431// }
2432// }
2433//
2434// // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
2435// BaseRay = BLS[0];
2436// if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
2437// eLog() << Verbose(1) << "Triangle " << *BTS << " has zero normal vector!" << endl;
2438// exit(255);
2439// }
2440//
2441// }
2442//
2443// // remove all candidates from the list and then the list itself
2444// class CandidateForTesselation *remover = NULL;
2445// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2446// remover = *it;
2447// delete(remover);
2448// }
2449// delete(OptCandidates);
2450 return result;
2451};
2452
2453/** Adds the present line and candidate point from \a &CandidateLine to the Tesselation.
2454 * \param CandidateLine triangle to add
2455 * \NOTE we need the copy operator here as the original CandidateForTesselation is removed in AddTesselationLine()
2456 */
2457void Tesselation::AddCandidateTriangle(CandidateForTesselation CandidateLine)
2458{
2459 Info FunctionInfo(__func__);
2460 Vector Center;
2461 TesselPoint * const TurningPoint = CandidateLine.BaseLine->endpoints[0]->node;
2462
2463 // fill the set of neighbours
2464 TesselPointSet SetOfNeighbours;
2465 SetOfNeighbours.insert(CandidateLine.BaseLine->endpoints[1]->node);
2466 for (TesselPointList::iterator Runner = CandidateLine.pointlist.begin(); Runner != CandidateLine.pointlist.end(); Runner++)
2467 SetOfNeighbours.insert(*Runner);
2468 TesselPointList *connectedClosestPoints = GetCircleOfSetOfPoints(&SetOfNeighbours, TurningPoint, CandidateLine.BaseLine->endpoints[1]->node->node);
2469
2470 // go through all angle-sorted candidates (in degenerate n-nodes case we may have to add multiple triangles)
2471 Log() << Verbose(0) << "List of Candidates for Turning Point: " << *TurningPoint << "." << endl;
2472 for (TesselPointList::iterator TesselRunner = connectedClosestPoints->begin(); TesselRunner != connectedClosestPoints->end(); ++TesselRunner)
2473 Log() << Verbose(0) << **TesselRunner << endl;
2474 TesselPointList::iterator Runner = connectedClosestPoints->begin();
2475 TesselPointList::iterator Sprinter = Runner;
2476 Sprinter++;
2477 while(Sprinter != connectedClosestPoints->end()) {
2478 // add the points
2479 AddTesselationPoint(TurningPoint, 0);
2480 AddTesselationPoint((*Runner), 1);
2481 AddTesselationPoint((*Sprinter), 2);
2482
2483 // add the lines
2484 AddTesselationLine(TPS[0], TPS[1], 0);
2485 AddTesselationLine(TPS[0], TPS[2], 1);
2486 AddTesselationLine(TPS[1], TPS[2], 2);
2487
2488 // add the triangles
2489 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2490 AddTesselationTriangle();
2491 BTS->GetCenter(&Center);
2492 Center.SubtractVector(&CandidateLine.OptCenter);
2493 BTS->SphereCenter.CopyVector(&CandidateLine.OptCenter);
2494 BTS->GetNormalVector(Center);
2495
2496 Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector << "." << endl;
2497 Runner = Sprinter;
2498 Sprinter++;
2499 Log() << Verbose(0) << "Current Runner is " << **Runner << "." << endl;
2500 if (Sprinter != connectedClosestPoints->end())
2501 Log() << Verbose(0) << " There are still more triangles to add." << endl;
2502 }
2503 delete(connectedClosestPoints);
2504};
2505
2506/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
2507 * We look whether the closest point on \a *Base with respect to the other baseline is outside
2508 * of the segment formed by both endpoints (concave) or not (convex).
2509 * \param *out output stream for debugging
2510 * \param *Base line to be flipped
2511 * \return NULL - convex, otherwise endpoint that makes it concave
2512 */
2513class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
2514{
2515 Info FunctionInfo(__func__);
2516 class BoundaryPointSet *Spot = NULL;
2517 class BoundaryLineSet *OtherBase;
2518 Vector *ClosestPoint;
2519
2520 int m=0;
2521 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2522 for (int j=0;j<3;j++) // all of their endpoints and baselines
2523 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2524 BPS[m++] = runner->second->endpoints[j];
2525 OtherBase = new class BoundaryLineSet(BPS,-1);
2526
2527 Log() << Verbose(1) << "INFO: Current base line is " << *Base << "." << endl;
2528 Log() << Verbose(1) << "INFO: Other base line is " << *OtherBase << "." << endl;
2529
2530 // get the closest point on each line to the other line
2531 ClosestPoint = GetClosestPointBetweenLine(Base, OtherBase);
2532
2533 // delete the temporary other base line
2534 delete(OtherBase);
2535
2536 // get the distance vector from Base line to OtherBase line
2537 Vector DistanceToIntersection[2], BaseLine;
2538 double distance[2];
2539 BaseLine.CopyVector(Base->endpoints[1]->node->node);
2540 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
2541 for (int i=0;i<2;i++) {
2542 DistanceToIntersection[i].CopyVector(ClosestPoint);
2543 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
2544 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
2545 }
2546 delete(ClosestPoint);
2547 if ((distance[0] * distance[1]) > 0) { // have same sign?
2548 Log() << Verbose(1) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
2549 if (distance[0] < distance[1]) {
2550 Spot = Base->endpoints[0];
2551 } else {
2552 Spot = Base->endpoints[1];
2553 }
2554 return Spot;
2555 } else { // different sign, i.e. we are in between
2556 Log() << Verbose(0) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
2557 return NULL;
2558 }
2559
2560};
2561
2562void Tesselation::PrintAllBoundaryPoints(ofstream *out) const
2563{
2564 Info FunctionInfo(__func__);
2565 // print all lines
2566 Log() << Verbose(0) << "Printing all boundary points for debugging:" << endl;
2567 for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
2568 Log() << Verbose(0) << *(PointRunner->second) << endl;
2569};
2570
2571void Tesselation::PrintAllBoundaryLines(ofstream *out) const
2572{
2573 Info FunctionInfo(__func__);
2574 // print all lines
2575 Log() << Verbose(0) << "Printing all boundary lines for debugging:" << endl;
2576 for (LineMap::const_iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
2577 Log() << Verbose(0) << *(LineRunner->second) << endl;
2578};
2579
2580void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
2581{
2582 Info FunctionInfo(__func__);
2583 // print all triangles
2584 Log() << Verbose(0) << "Printing all boundary triangles for debugging:" << endl;
2585 for (TriangleMap::const_iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
2586 Log() << Verbose(0) << *(TriangleRunner->second) << endl;
2587};
2588
2589/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
2590 * \param *out output stream for debugging
2591 * \param *Base line to be flipped
2592 * \return volume change due to flipping (0 - then no flipped occured)
2593 */
2594double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
2595{
2596 Info FunctionInfo(__func__);
2597 class BoundaryLineSet *OtherBase;
2598 Vector *ClosestPoint[2];
2599 double volume;
2600
2601 int m=0;
2602 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2603 for (int j=0;j<3;j++) // all of their endpoints and baselines
2604 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2605 BPS[m++] = runner->second->endpoints[j];
2606 OtherBase = new class BoundaryLineSet(BPS,-1);
2607
2608 Log() << Verbose(0) << "INFO: Current base line is " << *Base << "." << endl;
2609 Log() << Verbose(0) << "INFO: Other base line is " << *OtherBase << "." << endl;
2610
2611 // get the closest point on each line to the other line
2612 ClosestPoint[0] = GetClosestPointBetweenLine(Base, OtherBase);
2613 ClosestPoint[1] = GetClosestPointBetweenLine(OtherBase, Base);
2614
2615 // get the distance vector from Base line to OtherBase line
2616 Vector Distance;
2617 Distance.CopyVector(ClosestPoint[1]);
2618 Distance.SubtractVector(ClosestPoint[0]);
2619
2620 // calculate volume
2621 volume = CalculateVolumeofGeneralTetraeder(*Base->endpoints[1]->node->node, *OtherBase->endpoints[0]->node->node, *OtherBase->endpoints[1]->node->node, *Base->endpoints[0]->node->node);
2622
2623 // delete the temporary other base line and the closest points
2624 delete(ClosestPoint[0]);
2625 delete(ClosestPoint[1]);
2626 delete(OtherBase);
2627
2628 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2629 Log() << Verbose(0) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2630 return false;
2631 } else { // check for sign against BaseLineNormal
2632 Vector BaseLineNormal;
2633 BaseLineNormal.Zero();
2634 if (Base->triangles.size() < 2) {
2635 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2636 return 0.;
2637 }
2638 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2639 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2640 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2641 }
2642 BaseLineNormal.Scale(1./2.);
2643
2644 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2645 Log() << Verbose(0) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2646 // calculate volume summand as a general tetraeder
2647 return volume;
2648 } else { // Base higher than OtherBase -> do nothing
2649 Log() << Verbose(0) << "REJECT: Base line is higher: Nothing to do." << endl;
2650 return 0.;
2651 }
2652 }
2653};
2654
2655/** For a given baseline and its two connected triangles, flips the baseline.
2656 * I.e. we create the new baseline between the other two endpoints of these four
2657 * endpoints and reconstruct the two triangles accordingly.
2658 * \param *out output stream for debugging
2659 * \param *Base line to be flipped
2660 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2661 */
2662class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
2663{
2664 Info FunctionInfo(__func__);
2665 class BoundaryLineSet *OldLines[4], *NewLine;
2666 class BoundaryPointSet *OldPoints[2];
2667 Vector BaseLineNormal;
2668 int OldTriangleNrs[2], OldBaseLineNr;
2669 int i,m;
2670
2671 // calculate NormalVector for later use
2672 BaseLineNormal.Zero();
2673 if (Base->triangles.size() < 2) {
2674 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2675 return NULL;
2676 }
2677 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2678 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2679 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2680 }
2681 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2682
2683 // get the two triangles
2684 // gather four endpoints and four lines
2685 for (int j=0;j<4;j++)
2686 OldLines[j] = NULL;
2687 for (int j=0;j<2;j++)
2688 OldPoints[j] = NULL;
2689 i=0;
2690 m=0;
2691 Log() << Verbose(0) << "The four old lines are: ";
2692 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2693 for (int j=0;j<3;j++) // all of their endpoints and baselines
2694 if (runner->second->lines[j] != Base) { // pick not the central baseline
2695 OldLines[i++] = runner->second->lines[j];
2696 Log() << Verbose(0) << *runner->second->lines[j] << "\t";
2697 }
2698 Log() << Verbose(0) << endl;
2699 Log() << Verbose(0) << "The two old points are: ";
2700 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2701 for (int j=0;j<3;j++) // all of their endpoints and baselines
2702 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2703 OldPoints[m++] = runner->second->endpoints[j];
2704 Log() << Verbose(0) << *runner->second->endpoints[j] << "\t";
2705 }
2706 Log() << Verbose(0) << endl;
2707
2708 // check whether everything is in place to create new lines and triangles
2709 if (i<4) {
2710 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2711 return NULL;
2712 }
2713 for (int j=0;j<4;j++)
2714 if (OldLines[j] == NULL) {
2715 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2716 return NULL;
2717 }
2718 for (int j=0;j<2;j++)
2719 if (OldPoints[j] == NULL) {
2720 eLog() << Verbose(1) << "We have not gathered enough endpoints!" << endl;
2721 return NULL;
2722 }
2723
2724 // remove triangles and baseline removes itself
2725 Log() << Verbose(0) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2726 OldBaseLineNr = Base->Nr;
2727 m=0;
2728 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2729 Log() << Verbose(0) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
2730 OldTriangleNrs[m++] = runner->second->Nr;
2731 RemoveTesselationTriangle(runner->second);
2732 }
2733
2734 // construct new baseline (with same number as old one)
2735 BPS[0] = OldPoints[0];
2736 BPS[1] = OldPoints[1];
2737 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2738 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2739 Log() << Verbose(0) << "INFO: Created new baseline " << *NewLine << "." << endl;
2740
2741 // construct new triangles with flipped baseline
2742 i=-1;
2743 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2744 i=2;
2745 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2746 i=3;
2747 if (i!=-1) {
2748 BLS[0] = OldLines[0];
2749 BLS[1] = OldLines[i];
2750 BLS[2] = NewLine;
2751 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2752 BTS->GetNormalVector(BaseLineNormal);
2753 AddTesselationTriangle(OldTriangleNrs[0]);
2754 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
2755
2756 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
2757 BLS[1] = OldLines[1];
2758 BLS[2] = NewLine;
2759 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2760 BTS->GetNormalVector(BaseLineNormal);
2761 AddTesselationTriangle(OldTriangleNrs[1]);
2762 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
2763 } else {
2764 eLog() << Verbose(0) << "The four old lines do not connect, something's utterly wrong here!" << endl;
2765 return NULL;
2766 }
2767
2768 return NewLine;
2769};
2770
2771
2772/** Finds the second point of starting triangle.
2773 * \param *a first node
2774 * \param Oben vector indicating the outside
2775 * \param OptCandidate reference to recommended candidate on return
2776 * \param Storage[3] array storing angles and other candidate information
2777 * \param RADIUS radius of virtual sphere
2778 * \param *LC LinkedCell structure with neighbouring points
2779 */
2780void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC)
2781{
2782 Info FunctionInfo(__func__);
2783 Vector AngleCheck;
2784 class TesselPoint* Candidate = NULL;
2785 double norm = -1.;
2786 double angle = 0.;
2787 int N[NDIM];
2788 int Nlower[NDIM];
2789 int Nupper[NDIM];
2790
2791 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2792 for(int i=0;i<NDIM;i++) // store indices of this cell
2793 N[i] = LC->n[i];
2794 } else {
2795 eLog() << Verbose(1) << "Point " << *a << " is not found in cell " << LC->index << "." << endl;
2796 return;
2797 }
2798 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2799 for (int i=0;i<NDIM;i++) {
2800 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2801 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2802 }
2803 Log() << Verbose(0) << "LC Intervals from [" << N[0] << "<->" << LC->N[0] << ", " << N[1] << "<->" << LC->N[1] << ", " << N[2] << "<->" << LC->N[2] << "] :"
2804 << " [" << Nlower[0] << "," << Nupper[0] << "], " << " [" << Nlower[1] << "," << Nupper[1] << "], " << " [" << Nlower[2] << "," << Nupper[2] << "], " << endl;
2805
2806 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2807 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2808 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2809 const LinkedNodes *List = LC->GetCurrentCell();
2810 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2811 if (List != NULL) {
2812 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2813 Candidate = (*Runner);
2814 // check if we only have one unique point yet ...
2815 if (a != Candidate) {
2816 // Calculate center of the circle with radius RADIUS through points a and Candidate
2817 Vector OrthogonalizedOben, aCandidate, Center;
2818 double distance, scaleFactor;
2819
2820 OrthogonalizedOben.CopyVector(&Oben);
2821 aCandidate.CopyVector(a->node);
2822 aCandidate.SubtractVector(Candidate->node);
2823 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
2824 OrthogonalizedOben.Normalize();
2825 distance = 0.5 * aCandidate.Norm();
2826 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2827 OrthogonalizedOben.Scale(scaleFactor);
2828
2829 Center.CopyVector(Candidate->node);
2830 Center.AddVector(a->node);
2831 Center.Scale(0.5);
2832 Center.AddVector(&OrthogonalizedOben);
2833
2834 AngleCheck.CopyVector(&Center);
2835 AngleCheck.SubtractVector(a->node);
2836 norm = aCandidate.Norm();
2837 // second point shall have smallest angle with respect to Oben vector
2838 if (norm < RADIUS*2.) {
2839 angle = AngleCheck.Angle(&Oben);
2840 if (angle < Storage[0]) {
2841 //Log() << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2842 Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2843 OptCandidate = Candidate;
2844 Storage[0] = angle;
2845 //Log() << Verbose(1) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2846 } else {
2847 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
2848 }
2849 } else {
2850 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2851 }
2852 } else {
2853 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2854 }
2855 }
2856 } else {
2857 Log() << Verbose(0) << "Linked cell list is empty." << endl;
2858 }
2859 }
2860};
2861
2862
2863/** This recursive function finds a third point, to form a triangle with two given ones.
2864 * Note that this function is for the starting triangle.
2865 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2866 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2867 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2868 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2869 * us the "null" on this circle, the new center of the candidate point will be some way along this
2870 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2871 * by the normal vector of the base triangle that always points outwards by construction.
2872 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2873 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2874 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2875 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2876 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2877 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2878 * both.
2879 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2880 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2881 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2882 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2883 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2884 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2885 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2886 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2887 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2888 * @param CandidateLine CandidateForTesselation with the current base line and list of candidates and ShortestAngle
2889 * @param ThirdNode third point to avoid in search
2890 * @param RADIUS radius of sphere
2891 * @param *LC LinkedCell structure with neighbouring points
2892 */
2893void Tesselation::FindThirdPointForTesselation(Vector &NormalVector, Vector &SearchDirection, Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class TesselPoint * const ThirdNode, const double RADIUS, const LinkedCell *LC) const
2894{
2895 Info FunctionInfo(__func__);
2896 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2897 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2898 Vector SphereCenter;
2899 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2900 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2901 Vector NewNormalVector; // normal vector of the Candidate's triangle
2902 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2903 Vector RelativeOldSphereCenter;
2904 Vector NewPlaneCenter;
2905 double CircleRadius; // radius of this circle
2906 double radius;
2907 double otherradius;
2908 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2909 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2910 TesselPoint *Candidate = NULL;
2911
2912 Log() << Verbose(1) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
2913
2914 // construct center of circle
2915 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2916 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2917 CircleCenter.Scale(0.5);
2918
2919 // construct normal vector of circle
2920 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2921 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2922
2923 RelativeOldSphereCenter.CopyVector(&OldSphereCenter);
2924 RelativeOldSphereCenter.SubtractVector(&CircleCenter);
2925
2926 // calculate squared radius TesselPoint *ThirdNode,f circle
2927 radius = CirclePlaneNormal.NormSquared()/4.;
2928 if (radius < RADIUS*RADIUS) {
2929 CircleRadius = RADIUS*RADIUS - radius;
2930 CirclePlaneNormal.Normalize();
2931 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2932
2933 // test whether old center is on the band's plane
2934 if (fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
2935 eLog() << Verbose(1) << "Something's very wrong here: RelativeOldSphereCenter is not on the band's plane as desired by " << fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
2936 RelativeOldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
2937 }
2938 radius = RelativeOldSphereCenter.NormSquared();
2939 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2940 Log() << Verbose(1) << "INFO: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << "." << endl;
2941
2942 // check SearchDirection
2943 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2944 if (fabs(RelativeOldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2945 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
2946 }
2947
2948 // get cell for the starting point
2949 if (LC->SetIndexToVector(&CircleCenter)) {
2950 for(int i=0;i<NDIM;i++) // store indices of this cell
2951 N[i] = LC->n[i];
2952 //Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2953 } else {
2954 eLog() << Verbose(1) << "Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
2955 return;
2956 }
2957 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2958 //Log() << Verbose(1) << "LC Intervals:";
2959 for (int i=0;i<NDIM;i++) {
2960 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2961 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2962 //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2963 }
2964 //Log() << Verbose(0) << endl;
2965 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2966 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2967 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2968 const LinkedNodes *List = LC->GetCurrentCell();
2969 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2970 if (List != NULL) {
2971 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2972 Candidate = (*Runner);
2973
2974 // check for three unique points
2975 Log() << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " for BaseLine " << *CandidateLine.BaseLine << " with OldSphereCenter " << OldSphereCenter << "." << endl;
2976 if ((Candidate != CandidateLine.BaseLine->endpoints[0]->node) && (Candidate != CandidateLine.BaseLine->endpoints[1]->node) ){
2977
2978 // find center on the plane
2979 GetCenterofCircumcircle(&NewPlaneCenter, *CandidateLine.BaseLine->endpoints[0]->node->node, *CandidateLine.BaseLine->endpoints[1]->node->node, *Candidate->node);
2980 Log() << Verbose(1) << "INFO: NewPlaneCenter is " << NewPlaneCenter << "." << endl;
2981
2982 if (NewNormalVector.MakeNormalVector(CandidateLine.BaseLine->endpoints[0]->node->node, CandidateLine.BaseLine->endpoints[1]->node->node, Candidate->node)
2983 && (fabs(NewNormalVector.NormSquared()) > HULLEPSILON)
2984 ) {
2985 Log() << Verbose(1) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2986 radius = CandidateLine.BaseLine->endpoints[0]->node->node->DistanceSquared(&NewPlaneCenter);
2987 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2988 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2989 Log() << Verbose(1) << "INFO: Radius of CircumCenterCircle is " << radius << "." << endl;
2990 if (radius < RADIUS*RADIUS) {
2991 otherradius = CandidateLine.BaseLine->endpoints[1]->node->node->DistanceSquared(&NewPlaneCenter);
2992 if (fabs(radius - otherradius) > HULLEPSILON) {
2993 eLog() << Verbose(1) << "Distance to center of circumcircle is not the same from each corner of the triangle: " << fabs(radius-otherradius) << endl;
2994 }
2995 // construct both new centers
2996 NewSphereCenter.CopyVector(&NewPlaneCenter);
2997 OtherNewSphereCenter.CopyVector(&NewPlaneCenter);
2998 helper.CopyVector(&NewNormalVector);
2999 helper.Scale(sqrt(RADIUS*RADIUS - radius));
3000 Log() << Verbose(2) << "INFO: Distance of NewPlaneCenter " << NewPlaneCenter << " to either NewSphereCenter is " << helper.Norm() << " of vector " << helper << " with sphere radius " << RADIUS << "." << endl;
3001 NewSphereCenter.AddVector(&helper);
3002 Log() << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
3003 // OtherNewSphereCenter is created by the same vector just in the other direction
3004 helper.Scale(-1.);
3005 OtherNewSphereCenter.AddVector(&helper);
3006 Log() << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
3007
3008 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
3009 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
3010 alpha = min(alpha, Otheralpha);
3011
3012 // if there is a better candidate, drop the current list and add the new candidate
3013 // otherwise ignore the new candidate and keep the list
3014 if (CandidateLine.ShortestAngle > (alpha - HULLEPSILON)) {
3015 if (fabs(alpha - Otheralpha) > MYEPSILON) {
3016 CandidateLine.OptCenter.CopyVector(&NewSphereCenter);
3017 CandidateLine.OtherOptCenter.CopyVector(&OtherNewSphereCenter);
3018 } else {
3019 CandidateLine.OptCenter.CopyVector(&OtherNewSphereCenter);
3020 CandidateLine.OtherOptCenter.CopyVector(&NewSphereCenter);
3021 }
3022 // if there is an equal candidate, add it to the list without clearing the list
3023 if ((CandidateLine.ShortestAngle - HULLEPSILON) < alpha) {
3024 CandidateLine.pointlist.push_back(Candidate);
3025 Log() << Verbose(0) << "ACCEPT: We have found an equally good candidate: " << *(Candidate) << " with "
3026 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
3027 } else {
3028 // remove all candidates from the list and then the list itself
3029 CandidateLine.pointlist.clear();
3030 CandidateLine.pointlist.push_back(Candidate);
3031 Log() << Verbose(0) << "ACCEPT: We have found a better candidate: " << *(Candidate) << " with "
3032 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
3033 }
3034 CandidateLine.ShortestAngle = alpha;
3035 Log() << Verbose(0) << "INFO: There are " << CandidateLine.pointlist.size() << " candidates in the list now." << endl;
3036 } else {
3037 if ((Candidate != NULL) && (CandidateLine.pointlist.begin() != CandidateLine.pointlist.end())) {
3038 Log() << Verbose(1) << "REJECT: Old candidate " << *(Candidate) << " with " << CandidateLine.ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
3039 } else {
3040 Log() << Verbose(1) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
3041 }
3042 }
3043 } else {
3044 Log() << Verbose(1) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
3045 }
3046 } else {
3047 Log() << Verbose(1) << "REJECT: Three points from " << *CandidateLine.BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
3048 }
3049 } else {
3050 if (ThirdNode != NULL) {
3051 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
3052 } else {
3053 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << "." << endl;
3054 }
3055 }
3056 }
3057 }
3058 }
3059 } else {
3060 eLog() << Verbose(1) << "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
3061 }
3062 } else {
3063 if (ThirdNode != NULL)
3064 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
3065 else
3066 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " is too big!" << endl;
3067 }
3068
3069 Log() << Verbose(1) << "INFO: Sorting candidate list ..." << endl;
3070 if (CandidateLine.pointlist.size() > 1) {
3071 CandidateLine.pointlist.unique();
3072 CandidateLine.pointlist.sort(); //SortCandidates);
3073 }
3074};
3075
3076/** Finds the endpoint two lines are sharing.
3077 * \param *line1 first line
3078 * \param *line2 second line
3079 * \return point which is shared or NULL if none
3080 */
3081class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
3082{
3083 Info FunctionInfo(__func__);
3084 const BoundaryLineSet * lines[2] = { line1, line2 };
3085 class BoundaryPointSet *node = NULL;
3086 PointMap OrderMap;
3087 PointTestPair OrderTest;
3088 for (int i = 0; i < 2; i++)
3089 // for both lines
3090 for (int j = 0; j < 2; j++)
3091 { // for both endpoints
3092 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
3093 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
3094 if (!OrderTest.second)
3095 { // if insertion fails, we have common endpoint
3096 node = OrderTest.first->second;
3097 Log() << Verbose(1) << "Common endpoint of lines " << *line1
3098 << " and " << *line2 << " is: " << *node << "." << endl;
3099 j = 2;
3100 i = 2;
3101 break;
3102 }
3103 }
3104 return node;
3105};
3106
3107/** Finds the boundary points that are closest to a given Vector \a *x.
3108 * \param *out output stream for debugging
3109 * \param *x Vector to look from
3110 * \return map of BoundaryPointSet of closest points sorted by squared distance or NULL.
3111 */
3112DistanceToPointMap * Tesselation::FindClosestBoundaryPointsToVector(const Vector *x, const LinkedCell* LC) const
3113{
3114 Info FunctionInfo(__func__);
3115 PointMap::const_iterator FindPoint;
3116 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
3117
3118 if (LinesOnBoundary.empty()) {
3119 eLog() << Verbose(1) << "There is no tesselation structure to compare the point with, please create one first." << endl;
3120 return NULL;
3121 }
3122
3123 // gather all points close to the desired one
3124 LC->SetIndexToVector(x); // ignore status as we calculate bounds below sensibly
3125 for(int i=0;i<NDIM;i++) // store indices of this cell
3126 N[i] = LC->n[i];
3127 Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
3128
3129 DistanceToPointMap * points = new DistanceToPointMap;
3130 LC->GetNeighbourBounds(Nlower, Nupper);
3131 //Log() << Verbose(1) << endl;
3132 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
3133 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
3134 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
3135 const LinkedNodes *List = LC->GetCurrentCell();
3136 //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
3137 if (List != NULL) {
3138 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
3139 FindPoint = PointsOnBoundary.find((*Runner)->nr);
3140 if (FindPoint != PointsOnBoundary.end()) {
3141 points->insert(DistanceToPointPair (FindPoint->second->node->node->DistanceSquared(x), FindPoint->second) );
3142 Log() << Verbose(1) << "INFO: Putting " << *FindPoint->second << " into the list." << endl;
3143 }
3144 }
3145 } else {
3146 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
3147 }
3148 }
3149
3150 // check whether we found some points
3151 if (points->empty()) {
3152 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3153 delete(points);
3154 return NULL;
3155 }
3156 return points;
3157};
3158
3159/** Finds the boundary line that is closest to a given Vector \a *x.
3160 * \param *out output stream for debugging
3161 * \param *x Vector to look from
3162 * \return closest BoundaryLineSet or NULL in degenerate case.
3163 */
3164BoundaryLineSet * Tesselation::FindClosestBoundaryLineToVector(const Vector *x, const LinkedCell* LC) const
3165{
3166 Info FunctionInfo(__func__);
3167
3168 // get closest points
3169 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
3170 if (points == NULL) {
3171 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3172 return NULL;
3173 }
3174
3175 // for each point, check its lines, remember closest
3176 Log() << Verbose(1) << "Finding closest BoundaryLine to " << *x << " ... " << endl;
3177 BoundaryLineSet *ClosestLine = NULL;
3178 double MinDistance = -1.;
3179 Vector helper;
3180 Vector Center;
3181 Vector BaseLine;
3182 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3183 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3184 // calculate closest point on line to desired point
3185 helper.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3186 helper.AddVector((LineRunner->second)->endpoints[1]->node->node);
3187 helper.Scale(0.5);
3188 Center.CopyVector(x);
3189 Center.SubtractVector(&helper);
3190 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3191 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3192 Center.ProjectOntoPlane(&BaseLine);
3193 const double distance = Center.NormSquared();
3194 if ((ClosestLine == NULL) || (distance < MinDistance)) {
3195 // additionally calculate intersection on line (whether it's on the line section or not)
3196 helper.CopyVector(x);
3197 helper.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3198 helper.SubtractVector(&Center);
3199 const double lengthA = helper.ScalarProduct(&BaseLine);
3200 helper.CopyVector(x);
3201 helper.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3202 helper.SubtractVector(&Center);
3203 const double lengthB = helper.ScalarProduct(&BaseLine);
3204 if (lengthB*lengthA < 0) { // if have different sign
3205 ClosestLine = LineRunner->second;
3206 MinDistance = distance;
3207 Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl;
3208 } else {
3209 Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl;
3210 }
3211 } else {
3212 Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl;
3213 }
3214 }
3215 }
3216 delete(points);
3217 // check whether closest line is "too close" :), then it's inside
3218 if (ClosestLine == NULL) {
3219 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3220 return NULL;
3221 }
3222 return ClosestLine;
3223};
3224
3225
3226/** Finds the triangle that is closest to a given Vector \a *x.
3227 * \param *out output stream for debugging
3228 * \param *x Vector to look from
3229 * \return BoundaryTriangleSet of nearest triangle or NULL.
3230 */
3231TriangleList * Tesselation::FindClosestTrianglesToVector(const Vector *x, const LinkedCell* LC) const
3232{
3233 Info FunctionInfo(__func__);
3234
3235 // get closest points
3236 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
3237 if (points == NULL) {
3238 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3239 return NULL;
3240 }
3241
3242 // for each point, check its lines, remember closest
3243 Log() << Verbose(1) << "Finding closest BoundaryTriangle to " << *x << " ... " << endl;
3244 LineSet ClosestLines;
3245 double MinDistance = 1e+16;
3246 Vector BaseLineIntersection;
3247 Vector Center;
3248 Vector BaseLine;
3249 Vector BaseLineCenter;
3250 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3251 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3252
3253 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3254 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3255 const double lengthBase = BaseLine.NormSquared();
3256
3257 BaseLineIntersection.CopyVector(x);
3258 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3259 const double lengthEndA = BaseLineIntersection.NormSquared();
3260
3261 BaseLineIntersection.CopyVector(x);
3262 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3263 const double lengthEndB = BaseLineIntersection.NormSquared();
3264
3265 if ((lengthEndA > lengthBase) || (lengthEndB > lengthBase) || ((lengthEndA < MYEPSILON) || (lengthEndB < MYEPSILON))) { // intersection would be outside, take closer endpoint
3266 const double lengthEnd = Min(lengthEndA, lengthEndB);
3267 if (lengthEnd - MinDistance < -MYEPSILON) { // new best line
3268 ClosestLines.clear();
3269 ClosestLines.insert(LineRunner->second);
3270 MinDistance = lengthEnd;
3271 Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[0]->node << " is closer with " << lengthEnd << "." << endl;
3272 } else if (fabs(lengthEnd - MinDistance) < MYEPSILON) { // additional best candidate
3273 ClosestLines.insert(LineRunner->second);
3274 Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[1]->node << " is equally good with " << lengthEnd << "." << endl;
3275 } else { // line is worse
3276 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;
3277 }
3278 } else { // intersection is closer, calculate
3279 // calculate closest point on line to desired point
3280 BaseLineIntersection.CopyVector(x);
3281 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3282 Center.CopyVector(&BaseLineIntersection);
3283 Center.ProjectOntoPlane(&BaseLine);
3284 BaseLineIntersection.SubtractVector(&Center);
3285 const double distance = BaseLineIntersection.NormSquared();
3286 if (Center.NormSquared() > BaseLine.NormSquared()) {
3287 eLog() << Verbose(0) << "Algorithmic error: In second case we have intersection outside of baseline!" << endl;
3288 }
3289 if ((ClosestLines.empty()) || (distance < MinDistance)) {
3290 ClosestLines.insert(LineRunner->second);
3291 MinDistance = distance;
3292 Log() << Verbose(1) << "ACCEPT: Intersection in between endpoints, new closest line " << *LineRunner->second << " is " << *ClosestLines.begin() << " with projected distance " << MinDistance << "." << endl;
3293 } else {
3294 Log() << Verbose(2) << "REJECT: Point is further away from line " << *LineRunner->second << " than present closest line: " << distance << " >> " << MinDistance << "." << endl;
3295 }
3296 }
3297 }
3298 }
3299 delete(points);
3300
3301 // check whether closest line is "too close" :), then it's inside
3302 if (ClosestLines.empty()) {
3303 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3304 return NULL;
3305 }
3306 TriangleList * candidates = new TriangleList;
3307 for (LineSet::iterator LineRunner = ClosestLines.begin(); LineRunner != ClosestLines.end(); LineRunner++)
3308 for (TriangleMap::iterator Runner = (*LineRunner)->triangles.begin(); Runner != (*LineRunner)->triangles.end(); Runner++) {
3309 candidates->push_back(Runner->second);
3310 }
3311 return candidates;
3312};
3313
3314/** Finds closest triangle to a point.
3315 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
3316 * \param *out output stream for debugging
3317 * \param *x Vector to look from
3318 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
3319 */
3320class BoundaryTriangleSet * Tesselation::FindClosestTriangleToVector(const Vector *x, const LinkedCell* LC) const
3321{
3322 Info FunctionInfo(__func__);
3323 class BoundaryTriangleSet *result = NULL;
3324 TriangleList *triangles = FindClosestTrianglesToVector(x, LC);
3325 TriangleList candidates;
3326 Vector Center;
3327 Vector helper;
3328
3329 if ((triangles == NULL) || (triangles->empty()))
3330 return NULL;
3331
3332 // go through all and pick the one with the best alignment to x
3333 double MinAlignment = 2.*M_PI;
3334 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++) {
3335 (*Runner)->GetCenter(&Center);
3336 helper.CopyVector(x);
3337 helper.SubtractVector(&Center);
3338 const double Alignment = helper.Angle(&(*Runner)->NormalVector);
3339 if (Alignment < MinAlignment) {
3340 result = *Runner;
3341 MinAlignment = Alignment;
3342 Log() << Verbose(1) << "ACCEPT: Triangle " << *result << " is better aligned with " << MinAlignment << "." << endl;
3343 } else {
3344 Log() << Verbose(1) << "REJECT: Triangle " << *result << " is worse aligned with " << MinAlignment << "." << endl;
3345 }
3346 }
3347 delete(triangles);
3348
3349 return result;
3350};
3351
3352/** Checks whether the provided Vector is within the Tesselation structure.
3353 * Basically calls Tesselation::GetDistanceToSurface() and checks the sign of the return value.
3354 * @param point of which to check the position
3355 * @param *LC LinkedCell structure
3356 *
3357 * @return true if the point is inside the Tesselation structure, false otherwise
3358 */
3359bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const
3360{
3361 return (GetDistanceSquaredToSurface(Point, LC) > MYEPSILON);
3362}
3363
3364/** Returns the distance to the surface given by the tesselation.
3365 * Calls FindClosestTriangleToVector() and checks whether the resulting triangle's BoundaryTriangleSet#NormalVector points
3366 * towards or away from the given \a &Point. Additionally, we check whether it's normal to the normal vector, i.e. on the
3367 * closest triangle's plane. Then, we have to check whether \a Point is inside the triangle or not to determine whether it's
3368 * an inside or outside point. This is done by calling BoundaryTriangleSet::GetIntersectionInsideTriangle().
3369 * In the end we additionally find the point on the triangle who was smallest distance to \a Point:
3370 * -# Separate distance from point to center in vector in NormalDirection and on the triangle plane.
3371 * -# Check whether vector on triangle plane points inside the triangle or crosses triangle bounds.
3372 * -# If inside, take it to calculate closest distance
3373 * -# If not, take intersection with BoundaryLine as distance
3374 *
3375 * @note distance is squared despite it still contains a sign to determine in-/outside!
3376 *
3377 * @param point of which to check the position
3378 * @param *LC LinkedCell structure
3379 *
3380 * @return >0 if outside, ==0 if on surface, <0 if inside (Note that distance can be at most LinkedCell::RADIUS.)
3381 */
3382double Tesselation::GetDistanceSquaredToSurface(const Vector &Point, const LinkedCell* const LC) const
3383{
3384 Info FunctionInfo(__func__);
3385 class BoundaryTriangleSet *result = FindClosestTriangleToVector(&Point, LC);
3386 Vector Center;
3387 Vector helper;
3388 Vector DistanceToCenter;
3389 Vector Intersection;
3390 double distance = 0.;
3391
3392 if (result == NULL) {// is boundary point or only point in point cloud?
3393 Log() << Verbose(1) << Point << " is the only point in vicinity." << endl;
3394 return LC->RADIUS;
3395 } else {
3396 Log() << Verbose(1) << "INFO: Closest triangle found is " << *result << " with normal vector " << result->NormalVector << "." << endl;
3397 }
3398
3399 result->GetCenter(&Center);
3400 Log() << Verbose(2) << "INFO: Central point of the triangle is " << Center << "." << endl;
3401 DistanceToCenter.CopyVector(&Center);
3402 DistanceToCenter.SubtractVector(&Point);
3403 Log() << Verbose(2) << "INFO: Vector from point to test to center is " << DistanceToCenter << "." << endl;
3404
3405 // check whether we are on boundary
3406 if (fabs(DistanceToCenter.ScalarProduct(&result->NormalVector)) < MYEPSILON) {
3407 // calculate whether inside of triangle
3408 DistanceToCenter.CopyVector(&Point);
3409 Center.CopyVector(&Point);
3410 Center.SubtractVector(&result->NormalVector); // points towards MolCenter
3411 DistanceToCenter.AddVector(&result->NormalVector); // points outside
3412 Log() << Verbose(1) << "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << "." << endl;
3413 if (result->GetIntersectionInsideTriangle(&Center, &DistanceToCenter, &Intersection)) {
3414 Log() << Verbose(1) << Point << " is inner point: sufficiently close to boundary, " << Intersection << "." << endl;
3415 return 0.;
3416 } else {
3417 Log() << Verbose(1) << Point << " is NOT an inner point: on triangle plane but outside of triangle bounds." << endl;
3418 return false;
3419 }
3420 } else {
3421 // calculate smallest distance
3422 distance = result->GetClosestPointInsideTriangle(&Point, &Intersection);
3423 Log() << Verbose(1) << "Closest point on triangle is " << Intersection << "." << endl;
3424 distance = Min(distance, (LC->RADIUS*LC->RADIUS));
3425
3426 // then check direction to boundary
3427 if (DistanceToCenter.ScalarProduct(&result->NormalVector) > MYEPSILON) {
3428 Log() << Verbose(1) << Point << " is an inner point, " << distance << " below surface." << endl;
3429 return -distance;
3430 } else {
3431 Log() << Verbose(1) << Point << " is NOT an inner point, " << distance << " above surface." << endl;
3432 return +distance;
3433 }
3434 }
3435};
3436
3437/** Gets all points connected to the provided point by triangulation lines.
3438 *
3439 * @param *Point of which get all connected points
3440 *
3441 * @return set of the all points linked to the provided one
3442 */
3443TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
3444{
3445 Info FunctionInfo(__func__);
3446 TesselPointSet *connectedPoints = new TesselPointSet;
3447 class BoundaryPointSet *ReferencePoint = NULL;
3448 TesselPoint* current;
3449 bool takePoint = false;
3450
3451 // find the respective boundary point
3452 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
3453 if (PointRunner != PointsOnBoundary.end()) {
3454 ReferencePoint = PointRunner->second;
3455 } else {
3456 eLog() << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
3457 ReferencePoint = NULL;
3458 }
3459
3460 // little trick so that we look just through lines connect to the BoundaryPoint
3461 // OR fall-back to look through all lines if there is no such BoundaryPoint
3462 const LineMap *Lines;;
3463 if (ReferencePoint != NULL)
3464 Lines = &(ReferencePoint->lines);
3465 else
3466 Lines = &LinesOnBoundary;
3467 LineMap::const_iterator findLines = Lines->begin();
3468 while (findLines != Lines->end()) {
3469 takePoint = false;
3470
3471 if (findLines->second->endpoints[0]->Nr == Point->nr) {
3472 takePoint = true;
3473 current = findLines->second->endpoints[1]->node;
3474 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
3475 takePoint = true;
3476 current = findLines->second->endpoints[0]->node;
3477 }
3478
3479 if (takePoint) {
3480 Log() << Verbose(1) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
3481 connectedPoints->insert(current);
3482 }
3483
3484 findLines++;
3485 }
3486
3487 if (connectedPoints->empty()) { // if have not found any points
3488 eLog() << Verbose(1) << "We have not found any connected points to " << *Point<< "." << endl;
3489 return NULL;
3490 }
3491
3492 return connectedPoints;
3493};
3494
3495
3496/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3497 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3498 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3499 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3500 * triangle we are looking for.
3501 *
3502 * @param *out output stream for debugging
3503 * @param *SetOfNeighbours all points for which the angle should be calculated
3504 * @param *Point of which get all connected points
3505 * @param *Reference Reference vector for zero angle or NULL for no preference
3506 * @return list of the all points linked to the provided one
3507 */
3508TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3509{
3510 Info FunctionInfo(__func__);
3511 map<double, TesselPoint*> anglesOfPoints;
3512 TesselPointList *connectedCircle = new TesselPointList;
3513 Vector PlaneNormal;
3514 Vector AngleZero;
3515 Vector OrthogonalVector;
3516 Vector helper;
3517 const TesselPoint * const TrianglePoints[3] = {Point, NULL, NULL};
3518 TriangleList *triangles = NULL;
3519
3520 if (SetOfNeighbours == NULL) {
3521 eLog() << Verbose(2) << "Could not find any connected points!" << endl;
3522 delete(connectedCircle);
3523 return NULL;
3524 }
3525
3526 // calculate central point
3527 triangles = FindTriangles(TrianglePoints);
3528 if ((triangles != NULL) && (!triangles->empty())) {
3529 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
3530 PlaneNormal.AddVector(&(*Runner)->NormalVector);
3531 } else {
3532 eLog() << Verbose(0) << "Could not find any triangles for point " << *Point << "." << endl;
3533 performCriticalExit();
3534 }
3535 PlaneNormal.Scale(1.0/triangles->size());
3536 Log() << Verbose(1) << "INFO: Calculated PlaneNormal of all circle points is " << PlaneNormal << "." << endl;
3537 PlaneNormal.Normalize();
3538
3539 // construct one orthogonal vector
3540 if (Reference != NULL) {
3541 AngleZero.CopyVector(Reference);
3542 AngleZero.SubtractVector(Point->node);
3543 AngleZero.ProjectOntoPlane(&PlaneNormal);
3544 }
3545 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3546 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3547 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3548 AngleZero.SubtractVector(Point->node);
3549 AngleZero.ProjectOntoPlane(&PlaneNormal);
3550 if (AngleZero.NormSquared() < MYEPSILON) {
3551 eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
3552 performCriticalExit();
3553 }
3554 }
3555 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3556 if (AngleZero.NormSquared() > MYEPSILON)
3557 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3558 else
3559 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3560 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3561
3562 // go through all connected points and calculate angle
3563 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3564 helper.CopyVector((*listRunner)->node);
3565 helper.SubtractVector(Point->node);
3566 helper.ProjectOntoPlane(&PlaneNormal);
3567 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3568 Log() << Verbose(0) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
3569 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3570 }
3571
3572 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3573 connectedCircle->push_back(AngleRunner->second);
3574 }
3575
3576 return connectedCircle;
3577}
3578
3579/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3580 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3581 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3582 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3583 * triangle we are looking for.
3584 *
3585 * @param *SetOfNeighbours all points for which the angle should be calculated
3586 * @param *Point of which get all connected points
3587 * @param *Reference Reference vector for zero angle or NULL for no preference
3588 * @return list of the all points linked to the provided one
3589 */
3590TesselPointList * Tesselation::GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3591{
3592 Info FunctionInfo(__func__);
3593 map<double, TesselPoint*> anglesOfPoints;
3594 TesselPointList *connectedCircle = new TesselPointList;
3595 Vector center;
3596 Vector PlaneNormal;
3597 Vector AngleZero;
3598 Vector OrthogonalVector;
3599 Vector helper;
3600
3601 if (SetOfNeighbours == NULL) {
3602 eLog() << Verbose(2) << "Could not find any connected points!" << endl;
3603 delete(connectedCircle);
3604 return NULL;
3605 }
3606
3607 // check whether there's something to do
3608 if (SetOfNeighbours->size() < 3) {
3609 for (TesselPointSet::iterator TesselRunner = SetOfNeighbours->begin(); TesselRunner != SetOfNeighbours->end(); TesselRunner++)
3610 connectedCircle->push_back(*TesselRunner);
3611 return connectedCircle;
3612 }
3613
3614 Log() << Verbose(1) << "INFO: Point is " << *Point << " and Reference is " << *Reference << "." << endl;
3615 // calculate central point
3616
3617 TesselPointSet::const_iterator TesselA = SetOfNeighbours->begin();
3618 TesselPointSet::const_iterator TesselB = SetOfNeighbours->begin();
3619 TesselPointSet::const_iterator TesselC = SetOfNeighbours->begin();
3620 TesselB++;
3621 TesselC++;
3622 TesselC++;
3623 int counter = 0;
3624 while (TesselC != SetOfNeighbours->end()) {
3625 helper.MakeNormalVector((*TesselA)->node, (*TesselB)->node, (*TesselC)->node);
3626 Log() << Verbose(0) << "Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper << endl;
3627 counter++;
3628 TesselA++;
3629 TesselB++;
3630 TesselC++;
3631 PlaneNormal.AddVector(&helper);
3632 }
3633 //Log() << Verbose(0) << "Summed vectors " << center << "; number of points " << connectedPoints.size()
3634 // << "; scale factor " << counter;
3635 PlaneNormal.Scale(1.0/(double)counter);
3636// Log() << Verbose(1) << "INFO: Calculated center of all circle points is " << center << "." << endl;
3637//
3638// // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
3639// PlaneNormal.CopyVector(Point->node);
3640// PlaneNormal.SubtractVector(&center);
3641// PlaneNormal.Normalize();
3642 Log() << Verbose(1) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
3643
3644 // construct one orthogonal vector
3645 if (Reference != NULL) {
3646 AngleZero.CopyVector(Reference);
3647 AngleZero.SubtractVector(Point->node);
3648 AngleZero.ProjectOntoPlane(&PlaneNormal);
3649 }
3650 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3651 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3652 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3653 AngleZero.SubtractVector(Point->node);
3654 AngleZero.ProjectOntoPlane(&PlaneNormal);
3655 if (AngleZero.NormSquared() < MYEPSILON) {
3656 eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
3657 performCriticalExit();
3658 }
3659 }
3660 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3661 if (AngleZero.NormSquared() > MYEPSILON)
3662 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3663 else
3664 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3665 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3666
3667 // go through all connected points and calculate angle
3668 pair <map<double, TesselPoint*>::iterator, bool > InserterTest;
3669 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3670 helper.CopyVector((*listRunner)->node);
3671 helper.SubtractVector(Point->node);
3672 helper.ProjectOntoPlane(&PlaneNormal);
3673 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3674 if (angle > M_PI) // the correction is of no use here (and not desired)
3675 angle = 2.*M_PI - angle;
3676 Log() << Verbose(0) << "INFO: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << "." << endl;
3677 InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3678 if (!InserterTest.second) {
3679 eLog() << Verbose(0) << "GetCircleOfSetOfPoints() got two atoms with same angle: " << *((InserterTest.first)->second) << " and " << (*listRunner) << endl;
3680 performCriticalExit();
3681 }
3682 }
3683
3684 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3685 connectedCircle->push_back(AngleRunner->second);
3686 }
3687
3688 return connectedCircle;
3689}
3690
3691/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
3692 *
3693 * @param *out output stream for debugging
3694 * @param *Point of which get all connected points
3695 * @return list of the all points linked to the provided one
3696 */
3697list< TesselPointList *> * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
3698{
3699 Info FunctionInfo(__func__);
3700 map<double, TesselPoint*> anglesOfPoints;
3701 list< TesselPointList *> *ListOfPaths = new list< TesselPointList *>;
3702 TesselPointList *connectedPath = NULL;
3703 Vector center;
3704 Vector PlaneNormal;
3705 Vector AngleZero;
3706 Vector OrthogonalVector;
3707 Vector helper;
3708 class BoundaryPointSet *ReferencePoint = NULL;
3709 class BoundaryPointSet *CurrentPoint = NULL;
3710 class BoundaryTriangleSet *triangle = NULL;
3711 class BoundaryLineSet *CurrentLine = NULL;
3712 class BoundaryLineSet *StartLine = NULL;
3713
3714 // find the respective boundary point
3715 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
3716 if (PointRunner != PointsOnBoundary.end()) {
3717 ReferencePoint = PointRunner->second;
3718 } else {
3719 eLog() << Verbose(1) << "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
3720 return NULL;
3721 }
3722
3723 map <class BoundaryLineSet *, bool> TouchedLine;
3724 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
3725 map <class BoundaryLineSet *, bool>::iterator LineRunner;
3726 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
3727 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
3728 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
3729 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
3730 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
3731 }
3732 if (!ReferencePoint->lines.empty()) {
3733 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
3734 LineRunner = TouchedLine.find(runner->second);
3735 if (LineRunner == TouchedLine.end()) {
3736 eLog() << Verbose(1) << "I could not find " << *runner->second << " in the touched list." << endl;
3737 } else if (!LineRunner->second) {
3738 LineRunner->second = true;
3739 connectedPath = new TesselPointList;
3740 triangle = NULL;
3741 CurrentLine = runner->second;
3742 StartLine = CurrentLine;
3743 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3744 Log() << Verbose(1)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
3745 do {
3746 // push current one
3747 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3748 connectedPath->push_back(CurrentPoint->node);
3749
3750 // find next triangle
3751 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
3752 Log() << Verbose(1) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
3753 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
3754 triangle = Runner->second;
3755 TriangleRunner = TouchedTriangle.find(triangle);
3756 if (TriangleRunner != TouchedTriangle.end()) {
3757 if (!TriangleRunner->second) {
3758 TriangleRunner->second = true;
3759 Log() << Verbose(1) << "INFO: Connecting triangle is " << *triangle << "." << endl;
3760 break;
3761 } else {
3762 Log() << Verbose(1) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
3763 triangle = NULL;
3764 }
3765 } else {
3766 eLog() << Verbose(1) << "I could not find " << *triangle << " in the touched list." << endl;
3767 triangle = NULL;
3768 }
3769 }
3770 }
3771 if (triangle == NULL)
3772 break;
3773 // find next line
3774 for (int i=0;i<3;i++) {
3775 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
3776 CurrentLine = triangle->lines[i];
3777 Log() << Verbose(1) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
3778 break;
3779 }
3780 }
3781 LineRunner = TouchedLine.find(CurrentLine);
3782 if (LineRunner == TouchedLine.end())
3783 eLog() << Verbose(1) << "I could not find " << *CurrentLine << " in the touched list." << endl;
3784 else
3785 LineRunner->second = true;
3786 // find next point
3787 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3788
3789 } while (CurrentLine != StartLine);
3790 // last point is missing, as it's on start line
3791 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3792 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
3793 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
3794
3795 ListOfPaths->push_back(connectedPath);
3796 } else {
3797 Log() << Verbose(1) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
3798 }
3799 }
3800 } else {
3801 eLog() << Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl;
3802 }
3803
3804 return ListOfPaths;
3805}
3806
3807/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
3808 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
3809 * @param *out output stream for debugging
3810 * @param *Point of which get all connected points
3811 * @return list of the closed paths
3812 */
3813list<TesselPointList *> * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
3814{
3815 Info FunctionInfo(__func__);
3816 list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
3817 list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *>;
3818 TesselPointList *connectedPath = NULL;
3819 TesselPointList *newPath = NULL;
3820 int count = 0;
3821
3822
3823 TesselPointList::iterator CircleRunner;
3824 TesselPointList::iterator CircleStart;
3825
3826 for(list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
3827 connectedPath = *ListRunner;
3828
3829 Log() << Verbose(1) << "INFO: Current path is " << connectedPath << "." << endl;
3830
3831 // go through list, look for reappearance of starting Point and count
3832 CircleStart = connectedPath->begin();
3833
3834 // go through list, look for reappearance of starting Point and create list
3835 TesselPointList::iterator Marker = CircleStart;
3836 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
3837 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
3838 // we have a closed circle from Marker to new Marker
3839 Log() << Verbose(1) << count+1 << ". closed path consists of: ";
3840 newPath = new TesselPointList;
3841 TesselPointList::iterator CircleSprinter = Marker;
3842 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
3843 newPath->push_back(*CircleSprinter);
3844 Log() << Verbose(0) << (**CircleSprinter) << " <-> ";
3845 }
3846 Log() << Verbose(0) << ".." << endl;
3847 count++;
3848 Marker = CircleRunner;
3849
3850 // add to list
3851 ListofClosedPaths->push_back(newPath);
3852 }
3853 }
3854 }
3855 Log() << Verbose(1) << "INFO: " << count << " closed additional path(s) have been created." << endl;
3856
3857 // delete list of paths
3858 while (!ListofPaths->empty()) {
3859 connectedPath = *(ListofPaths->begin());
3860 ListofPaths->remove(connectedPath);
3861 delete(connectedPath);
3862 }
3863 delete(ListofPaths);
3864
3865 // exit
3866 return ListofClosedPaths;
3867};
3868
3869
3870/** Gets all belonging triangles for a given BoundaryPointSet.
3871 * \param *out output stream for debugging
3872 * \param *Point BoundaryPoint
3873 * \return pointer to allocated list of triangles
3874 */
3875TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
3876{
3877 Info FunctionInfo(__func__);
3878 TriangleSet *connectedTriangles = new TriangleSet;
3879
3880 if (Point == NULL) {
3881 eLog() << Verbose(1) << "Point given is NULL." << endl;
3882 } else {
3883 // go through its lines and insert all triangles
3884 for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
3885 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
3886 connectedTriangles->insert(TriangleRunner->second);
3887 }
3888 }
3889
3890 return connectedTriangles;
3891};
3892
3893
3894/** Removes a boundary point from the envelope while keeping it closed.
3895 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
3896 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
3897 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
3898 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
3899 * -# the surface is closed, when the path is empty
3900 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
3901 * \param *out output stream for debugging
3902 * \param *point point to be removed
3903 * \return volume added to the volume inside the tesselated surface by the removal
3904 */
3905double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point) {
3906 class BoundaryLineSet *line = NULL;
3907 class BoundaryTriangleSet *triangle = NULL;
3908 Vector OldPoint, NormalVector;
3909 double volume = 0;
3910 int count = 0;
3911
3912 if (point == NULL) {
3913 eLog() << Verbose(1) << "Cannot remove the point " << point << ", it's NULL!" << endl;
3914 return 0.;
3915 } else
3916 Log() << Verbose(0) << "Removing point " << *point << " from tesselated boundary ..." << endl;
3917
3918 // copy old location for the volume
3919 OldPoint.CopyVector(point->node->node);
3920
3921 // get list of connected points
3922 if (point->lines.empty()) {
3923 eLog() << Verbose(1) << "Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
3924 return 0.;
3925 }
3926
3927 list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
3928 TesselPointList *connectedPath = NULL;
3929
3930 // gather all triangles
3931 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3932 count+=LineRunner->second->triangles.size();
3933 TriangleMap Candidates;
3934 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3935 line = LineRunner->second;
3936 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3937 triangle = TriangleRunner->second;
3938 Candidates.insert( TrianglePair (triangle->Nr, triangle) );
3939 }
3940 }
3941
3942 // remove all triangles
3943 count=0;
3944 NormalVector.Zero();
3945 for (TriangleMap::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3946 Log() << Verbose(1) << "INFO: Removing triangle " << *(Runner->second) << "." << endl;
3947 NormalVector.SubtractVector(&Runner->second->NormalVector); // has to point inward
3948 RemoveTesselationTriangle(Runner->second);
3949 count++;
3950 }
3951 Log() << Verbose(1) << count << " triangles were removed." << endl;
3952
3953 list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
3954 list<TesselPointList *>::iterator ListRunner = ListAdvance;
3955 TriangleMap::iterator NumberRunner = Candidates.begin();
3956 TesselPointList::iterator StartNode, MiddleNode, EndNode;
3957 double angle;
3958 double smallestangle;
3959 Vector Point, Reference, OrthogonalVector;
3960 if (count > 2) { // less than three triangles, then nothing will be created
3961 class TesselPoint *TriangleCandidates[3];
3962 count = 0;
3963 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3964 if (ListAdvance != ListOfClosedPaths->end())
3965 ListAdvance++;
3966
3967 connectedPath = *ListRunner;
3968
3969 // re-create all triangles by going through connected points list
3970 LineList NewLines;
3971 for (;!connectedPath->empty();) {
3972 // search middle node with widest angle to next neighbours
3973 EndNode = connectedPath->end();
3974 smallestangle = 0.;
3975 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3976 Log() << Verbose(1) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3977 // construct vectors to next and previous neighbour
3978 StartNode = MiddleNode;
3979 if (StartNode == connectedPath->begin())
3980 StartNode = connectedPath->end();
3981 StartNode--;
3982 //Log() << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
3983 Point.CopyVector((*StartNode)->node);
3984 Point.SubtractVector((*MiddleNode)->node);
3985 StartNode = MiddleNode;
3986 StartNode++;
3987 if (StartNode == connectedPath->end())
3988 StartNode = connectedPath->begin();
3989 //Log() << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
3990 Reference.CopyVector((*StartNode)->node);
3991 Reference.SubtractVector((*MiddleNode)->node);
3992 OrthogonalVector.CopyVector((*MiddleNode)->node);
3993 OrthogonalVector.SubtractVector(&OldPoint);
3994 OrthogonalVector.MakeNormalVector(&Reference);
3995 angle = GetAngle(Point, Reference, OrthogonalVector);
3996 //if (angle < M_PI) // no wrong-sided triangles, please?
3997 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3998 smallestangle = angle;
3999 EndNode = MiddleNode;
4000 }
4001 }
4002 MiddleNode = EndNode;
4003 if (MiddleNode == connectedPath->end()) {
4004 eLog() << Verbose(0) << "CRITICAL: Could not find a smallest angle!" << endl;
4005 performCriticalExit();
4006 }
4007 StartNode = MiddleNode;
4008 if (StartNode == connectedPath->begin())
4009 StartNode = connectedPath->end();
4010 StartNode--;
4011 EndNode++;
4012 if (EndNode == connectedPath->end())
4013 EndNode = connectedPath->begin();
4014 Log() << Verbose(2) << "INFO: StartNode is " << **StartNode << "." << endl;
4015 Log() << Verbose(2) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
4016 Log() << Verbose(2) << "INFO: EndNode is " << **EndNode << "." << endl;
4017 Log() << Verbose(1) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
4018 TriangleCandidates[0] = *StartNode;
4019 TriangleCandidates[1] = *MiddleNode;
4020 TriangleCandidates[2] = *EndNode;
4021 triangle = GetPresentTriangle(TriangleCandidates);
4022 if (triangle != NULL) {
4023 eLog() << Verbose(0) << "New triangle already present, skipping!" << endl;
4024 StartNode++;
4025 MiddleNode++;
4026 EndNode++;
4027 if (StartNode == connectedPath->end())
4028 StartNode = connectedPath->begin();
4029 if (MiddleNode == connectedPath->end())
4030 MiddleNode = connectedPath->begin();
4031 if (EndNode == connectedPath->end())
4032 EndNode = connectedPath->begin();
4033 continue;
4034 }
4035 Log() << Verbose(3) << "Adding new triangle points."<< endl;
4036 AddTesselationPoint(*StartNode, 0);
4037 AddTesselationPoint(*MiddleNode, 1);
4038 AddTesselationPoint(*EndNode, 2);
4039 Log() << Verbose(3) << "Adding new triangle lines."<< endl;
4040 AddTesselationLine(TPS[0], TPS[1], 0);
4041 AddTesselationLine(TPS[0], TPS[2], 1);
4042 NewLines.push_back(BLS[1]);
4043 AddTesselationLine(TPS[1], TPS[2], 2);
4044 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4045 BTS->GetNormalVector(NormalVector);
4046 AddTesselationTriangle();
4047 // calculate volume summand as a general tetraeder
4048 volume += CalculateVolumeofGeneralTetraeder(*TPS[0]->node->node, *TPS[1]->node->node, *TPS[2]->node->node, OldPoint);
4049 // advance number
4050 count++;
4051
4052 // prepare nodes for next triangle
4053 StartNode = EndNode;
4054 Log() << Verbose(2) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
4055 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
4056 if (connectedPath->size() == 2) { // we are done
4057 connectedPath->remove(*StartNode); // remove the start node
4058 connectedPath->remove(*EndNode); // remove the end node
4059 break;
4060 } else if (connectedPath->size() < 2) { // something's gone wrong!
4061 eLog() << Verbose(0) << "CRITICAL: There are only two endpoints left!" << endl;
4062 performCriticalExit();
4063 } else {
4064 MiddleNode = StartNode;
4065 MiddleNode++;
4066 if (MiddleNode == connectedPath->end())
4067 MiddleNode = connectedPath->begin();
4068 EndNode = MiddleNode;
4069 EndNode++;
4070 if (EndNode == connectedPath->end())
4071 EndNode = connectedPath->begin();
4072 }
4073 }
4074 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
4075 if (NewLines.size() > 1) {
4076 LineList::iterator Candidate;
4077 class BoundaryLineSet *OtherBase = NULL;
4078 double tmp, maxgain;
4079 do {
4080 maxgain = 0;
4081 for(LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
4082 tmp = PickFarthestofTwoBaselines(*Runner);
4083 if (maxgain < tmp) {
4084 maxgain = tmp;
4085 Candidate = Runner;
4086 }
4087 }
4088 if (maxgain != 0) {
4089 volume += maxgain;
4090 Log() << Verbose(1) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
4091 OtherBase = FlipBaseline(*Candidate);
4092 NewLines.erase(Candidate);
4093 NewLines.push_back(OtherBase);
4094 }
4095 } while (maxgain != 0.);
4096 }
4097
4098 ListOfClosedPaths->remove(connectedPath);
4099 delete(connectedPath);
4100 }
4101 Log() << Verbose(0) << count << " triangles were created." << endl;
4102 } else {
4103 while (!ListOfClosedPaths->empty()) {
4104 ListRunner = ListOfClosedPaths->begin();
4105 connectedPath = *ListRunner;
4106 ListOfClosedPaths->remove(connectedPath);
4107 delete(connectedPath);
4108 }
4109 Log() << Verbose(0) << "No need to create any triangles." << endl;
4110 }
4111 delete(ListOfClosedPaths);
4112
4113 Log() << Verbose(0) << "Removed volume is " << volume << "." << endl;
4114
4115 return volume;
4116};
4117
4118
4119
4120/**
4121 * Finds triangles belonging to the three provided points.
4122 *
4123 * @param *Points[3] list, is expected to contain three points (NULL means wildcard)
4124 *
4125 * @return triangles which belong to the provided points, will be empty if there are none,
4126 * will usually be one, in case of degeneration, there will be two
4127 */
4128TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
4129{
4130 Info FunctionInfo(__func__);
4131 TriangleList *result = new TriangleList;
4132 LineMap::const_iterator FindLine;
4133 TriangleMap::const_iterator FindTriangle;
4134 class BoundaryPointSet *TrianglePoints[3];
4135 size_t NoOfWildcards = 0;
4136
4137 for (int i = 0; i < 3; i++) {
4138 if (Points[i] == NULL) {
4139 NoOfWildcards++;
4140 TrianglePoints[i] = NULL;
4141 } else {
4142 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->nr);
4143 if (FindPoint != PointsOnBoundary.end()) {
4144 TrianglePoints[i] = FindPoint->second;
4145 } else {
4146 TrianglePoints[i] = NULL;
4147 }
4148 }
4149 }
4150
4151 switch (NoOfWildcards) {
4152 case 0: // checks lines between the points in the Points for their adjacent triangles
4153 for (int i = 0; i < 3; i++) {
4154 if (TrianglePoints[i] != NULL) {
4155 for (int j = i+1; j < 3; j++) {
4156 if (TrianglePoints[j] != NULL) {
4157 for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr); // is a multimap!
4158 (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->nr);
4159 FindLine++) {
4160 for (FindTriangle = FindLine->second->triangles.begin();
4161 FindTriangle != FindLine->second->triangles.end();
4162 FindTriangle++) {
4163 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
4164 result->push_back(FindTriangle->second);
4165 }
4166 }
4167 }
4168 // Is it sufficient to consider one of the triangle lines for this.
4169 return result;
4170 }
4171 }
4172 }
4173 }
4174 break;
4175 case 1: // copy all triangles of the respective line
4176 {
4177 int i=0;
4178 for (; i < 3; i++)
4179 if (TrianglePoints[i] == NULL)
4180 break;
4181 for (FindLine = TrianglePoints[(i+1)%3]->lines.find(TrianglePoints[(i+2)%3]->node->nr); // is a multimap!
4182 (FindLine != TrianglePoints[(i+1)%3]->lines.end()) && (FindLine->first == TrianglePoints[(i+2)%3]->node->nr);
4183 FindLine++) {
4184 for (FindTriangle = FindLine->second->triangles.begin();
4185 FindTriangle != FindLine->second->triangles.end();
4186 FindTriangle++) {
4187 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
4188 result->push_back(FindTriangle->second);
4189 }
4190 }
4191 }
4192 break;
4193 }
4194 case 2: // copy all triangles of the respective point
4195 {
4196 int i=0;
4197 for (; i < 3; i++)
4198 if (TrianglePoints[i] != NULL)
4199 break;
4200 for (LineMap::const_iterator line = TrianglePoints[i]->lines.begin(); line != TrianglePoints[i]->lines.end(); line++)
4201 for (TriangleMap::const_iterator triangle = line->second->triangles.begin(); triangle != line->second->triangles.end(); triangle++)
4202 result->push_back(triangle->second);
4203 result->sort();
4204 result->unique();
4205 break;
4206 }
4207 case 3: // copy all triangles
4208 {
4209 for (TriangleMap::const_iterator triangle = TrianglesOnBoundary.begin(); triangle != TrianglesOnBoundary.end(); triangle++)
4210 result->push_back(triangle->second);
4211 break;
4212 }
4213 default:
4214 eLog() << Verbose(0) << "Number of wildcards is greater than 3, cannot happen!" << endl;
4215 performCriticalExit();
4216 break;
4217 }
4218
4219 return result;
4220}
4221
4222struct BoundaryLineSetCompare {
4223 bool operator() (const BoundaryLineSet * const a, const BoundaryLineSet * const b) {
4224 int lowerNra = -1;
4225 int lowerNrb = -1;
4226
4227 if (a->endpoints[0] < a->endpoints[1])
4228 lowerNra = 0;
4229 else
4230 lowerNra = 1;
4231
4232 if (b->endpoints[0] < b->endpoints[1])
4233 lowerNrb = 0;
4234 else
4235 lowerNrb = 1;
4236
4237 if (a->endpoints[lowerNra] < b->endpoints[lowerNrb])
4238 return true;
4239 else if (a->endpoints[lowerNra] > b->endpoints[lowerNrb])
4240 return false;
4241 else { // both lower-numbered endpoints are the same ...
4242 if (a->endpoints[(lowerNra+1)%2] < b->endpoints[(lowerNrb+1)%2])
4243 return true;
4244 else if (a->endpoints[(lowerNra+1)%2] > b->endpoints[(lowerNrb+1)%2])
4245 return false;
4246 }
4247 return false;
4248 };
4249};
4250
4251#define UniqueLines set < class BoundaryLineSet *, BoundaryLineSetCompare>
4252
4253/**
4254 * Finds all degenerated lines within the tesselation structure.
4255 *
4256 * @return map of keys of degenerated line pairs, each line occurs twice
4257 * in the list, once as key and once as value
4258 */
4259IndexToIndex * Tesselation::FindAllDegeneratedLines()
4260{
4261 Info FunctionInfo(__func__);
4262 UniqueLines AllLines;
4263 IndexToIndex * DegeneratedLines = new IndexToIndex;
4264
4265 // sanity check
4266 if (LinesOnBoundary.empty()) {
4267 eLog() << Verbose(2) << "FindAllDegeneratedTriangles() was called without any tesselation structure.";
4268 return DegeneratedLines;
4269 }
4270
4271 LineMap::iterator LineRunner1;
4272 pair< UniqueLines::iterator, bool> tester;
4273 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
4274 tester = AllLines.insert( LineRunner1->second );
4275 if (!tester.second) { // found degenerated line
4276 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr) );
4277 DegeneratedLines->insert ( pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr) );
4278 }
4279 }
4280
4281 AllLines.clear();
4282
4283 Log() << Verbose(0) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
4284 IndexToIndex::iterator it;
4285 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
4286 const LineMap::const_iterator Line1 = LinesOnBoundary.find((*it).first);
4287 const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
4288 if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
4289 Log() << Verbose(0) << *Line1->second << " => " << *Line2->second << endl;
4290 else
4291 eLog() << Verbose(1) << "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!" << endl;
4292 }
4293
4294 return DegeneratedLines;
4295}
4296
4297/**
4298 * Finds all degenerated triangles within the tesselation structure.
4299 *
4300 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
4301 * in the list, once as key and once as value
4302 */
4303IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
4304{
4305 Info FunctionInfo(__func__);
4306 IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
4307 IndexToIndex * DegeneratedTriangles = new IndexToIndex;
4308
4309 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
4310 LineMap::iterator Liner;
4311 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
4312
4313 for (IndexToIndex::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
4314 // run over both lines' triangles
4315 Liner = LinesOnBoundary.find(LineRunner->first);
4316 if (Liner != LinesOnBoundary.end())
4317 line1 = Liner->second;
4318 Liner = LinesOnBoundary.find(LineRunner->second);
4319 if (Liner != LinesOnBoundary.end())
4320 line2 = Liner->second;
4321 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
4322 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
4323 if ((TriangleRunner1->second != TriangleRunner2->second)
4324 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
4325 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
4326 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
4327 }
4328 }
4329 }
4330 }
4331 delete(DegeneratedLines);
4332
4333 Log() << Verbose(0) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
4334 IndexToIndex::iterator it;
4335 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
4336 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
4337
4338 return DegeneratedTriangles;
4339}
4340
4341/**
4342 * Purges degenerated triangles from the tesselation structure if they are not
4343 * necessary to keep a single point within the structure.
4344 */
4345void Tesselation::RemoveDegeneratedTriangles()
4346{
4347 Info FunctionInfo(__func__);
4348 IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
4349 TriangleMap::iterator finder;
4350 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
4351 int count = 0;
4352
4353 for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
4354 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
4355 ) {
4356 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
4357 if (finder != TrianglesOnBoundary.end())
4358 triangle = finder->second;
4359 else
4360 break;
4361 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
4362 if (finder != TrianglesOnBoundary.end())
4363 partnerTriangle = finder->second;
4364 else
4365 break;
4366
4367 bool trianglesShareLine = false;
4368 for (int i = 0; i < 3; ++i)
4369 for (int j = 0; j < 3; ++j)
4370 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
4371
4372 if (trianglesShareLine
4373 && (triangle->endpoints[1]->LinesCount > 2)
4374 && (triangle->endpoints[2]->LinesCount > 2)
4375 && (triangle->endpoints[0]->LinesCount > 2)
4376 ) {
4377 // check whether we have to fix lines
4378 BoundaryTriangleSet *Othertriangle = NULL;
4379 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
4380 TriangleMap::iterator TriangleRunner;
4381 for (int i = 0; i < 3; ++i)
4382 for (int j = 0; j < 3; ++j)
4383 if (triangle->lines[i] != partnerTriangle->lines[j]) {
4384 // get the other two triangles
4385 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
4386 if (TriangleRunner->second != triangle) {
4387 Othertriangle = TriangleRunner->second;
4388 }
4389 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
4390 if (TriangleRunner->second != partnerTriangle) {
4391 OtherpartnerTriangle = TriangleRunner->second;
4392 }
4393 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
4394 // the line of triangle receives the degenerated ones
4395 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
4396 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
4397 for (int k=0;k<3;k++)
4398 if (triangle->lines[i] == Othertriangle->lines[k]) {
4399 Othertriangle->lines[k] = partnerTriangle->lines[j];
4400 break;
4401 }
4402 // the line of partnerTriangle receives the non-degenerated ones
4403 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
4404 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
4405 partnerTriangle->lines[j] = triangle->lines[i];
4406 }
4407
4408 // erase the pair
4409 count += (int) DegeneratedTriangles->erase(triangle->Nr);
4410 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
4411 RemoveTesselationTriangle(triangle);
4412 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
4413 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
4414 RemoveTesselationTriangle(partnerTriangle);
4415 } else {
4416 Log() << Verbose(0) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
4417 << " and its partner " << *partnerTriangle << " because it is essential for at"
4418 << " least one of the endpoints to be kept in the tesselation structure." << endl;
4419 }
4420 }
4421 delete(DegeneratedTriangles);
4422 if (count > 0)
4423 LastTriangle = NULL;
4424
4425 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
4426}
4427
4428/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
4429 * We look for the closest point on the boundary, we look through its connected boundary lines and
4430 * seek the one with the minimum angle between its center point and the new point and this base line.
4431 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
4432 * \param *out output stream for debugging
4433 * \param *point point to add
4434 * \param *LC Linked Cell structure to find nearest point
4435 */
4436void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC)
4437{
4438 Info FunctionInfo(__func__);
4439 // find nearest boundary point
4440 class TesselPoint *BackupPoint = NULL;
4441 class TesselPoint *NearestPoint = FindClosestTesselPoint(point->node, BackupPoint, LC);
4442 class BoundaryPointSet *NearestBoundaryPoint = NULL;
4443 PointMap::iterator PointRunner;
4444
4445 if (NearestPoint == point)
4446 NearestPoint = BackupPoint;
4447 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
4448 if (PointRunner != PointsOnBoundary.end()) {
4449 NearestBoundaryPoint = PointRunner->second;
4450 } else {
4451 eLog() << Verbose(1) << "I cannot find the boundary point." << endl;
4452 return;
4453 }
4454 Log() << Verbose(0) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
4455
4456 // go through its lines and find the best one to split
4457 Vector CenterToPoint;
4458 Vector BaseLine;
4459 double angle, BestAngle = 0.;
4460 class BoundaryLineSet *BestLine = NULL;
4461 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
4462 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
4463 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
4464 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
4465 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
4466 CenterToPoint.Scale(0.5);
4467 CenterToPoint.SubtractVector(point->node);
4468 angle = CenterToPoint.Angle(&BaseLine);
4469 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
4470 BestAngle = angle;
4471 BestLine = Runner->second;
4472 }
4473 }
4474
4475 // remove one triangle from the chosen line
4476 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
4477 BestLine->triangles.erase(TempTriangle->Nr);
4478 int nr = -1;
4479 for (int i=0;i<3; i++) {
4480 if (TempTriangle->lines[i] == BestLine) {
4481 nr = i;
4482 break;
4483 }
4484 }
4485
4486 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
4487 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4488 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4489 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4490 AddTesselationPoint(point, 2);
4491 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4492 AddTesselationLine(TPS[0], TPS[1], 0);
4493 AddTesselationLine(TPS[0], TPS[2], 1);
4494 AddTesselationLine(TPS[1], TPS[2], 2);
4495 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4496 BTS->GetNormalVector(TempTriangle->NormalVector);
4497 BTS->NormalVector.Scale(-1.);
4498 Log() << Verbose(1) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
4499 AddTesselationTriangle();
4500
4501 // create other side of this triangle and close both new sides of the first created triangle
4502 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4503 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4504 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4505 AddTesselationPoint(point, 2);
4506 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4507 AddTesselationLine(TPS[0], TPS[1], 0);
4508 AddTesselationLine(TPS[0], TPS[2], 1);
4509 AddTesselationLine(TPS[1], TPS[2], 2);
4510 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4511 BTS->GetNormalVector(TempTriangle->NormalVector);
4512 Log() << Verbose(1) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
4513 AddTesselationTriangle();
4514
4515 // add removed triangle to the last open line of the second triangle
4516 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
4517 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
4518 if (BestLine == BTS->lines[i]){
4519 eLog() << Verbose(0) << "BestLine is same as found line, something's wrong here!" << endl;
4520 performCriticalExit();
4521 }
4522 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
4523 TempTriangle->lines[nr] = BTS->lines[i];
4524 break;
4525 }
4526 }
4527};
4528
4529/** Writes the envelope to file.
4530 * \param *out otuput stream for debugging
4531 * \param *filename basename of output file
4532 * \param *cloud PointCloud structure with all nodes
4533 */
4534void Tesselation::Output(const char *filename, const PointCloud * const cloud)
4535{
4536 Info FunctionInfo(__func__);
4537 ofstream *tempstream = NULL;
4538 string NameofTempFile;
4539 char NumberName[255];
4540
4541 if (LastTriangle != NULL) {
4542 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
4543 if (DoTecplotOutput) {
4544 string NameofTempFile(filename);
4545 NameofTempFile.append(NumberName);
4546 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4547 NameofTempFile.erase(npos, 1);
4548 NameofTempFile.append(TecplotSuffix);
4549 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4550 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4551 WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
4552 tempstream->close();
4553 tempstream->flush();
4554 delete(tempstream);
4555 }
4556
4557 if (DoRaster3DOutput) {
4558 string NameofTempFile(filename);
4559 NameofTempFile.append(NumberName);
4560 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4561 NameofTempFile.erase(npos, 1);
4562 NameofTempFile.append(Raster3DSuffix);
4563 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4564 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4565 WriteRaster3dFile(tempstream, this, cloud);
4566 IncludeSphereinRaster3D(tempstream, this, cloud);
4567 tempstream->close();
4568 tempstream->flush();
4569 delete(tempstream);
4570 }
4571 }
4572 if (DoTecplotOutput || DoRaster3DOutput)
4573 TriangleFilesWritten++;
4574};
4575
4576struct BoundaryPolygonSetCompare {
4577 bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const {
4578 if (s1->endpoints.size() < s2->endpoints.size())
4579 return true;
4580 else if (s1->endpoints.size() > s2->endpoints.size())
4581 return false;
4582 else { // equality of number of endpoints
4583 PointSet::const_iterator Walker1 = s1->endpoints.begin();
4584 PointSet::const_iterator Walker2 = s2->endpoints.begin();
4585 while ((Walker1 != s1->endpoints.end()) || (Walker2 != s2->endpoints.end())) {
4586 if ((*Walker1)->Nr < (*Walker2)->Nr)
4587 return true;
4588 else if ((*Walker1)->Nr > (*Walker2)->Nr)
4589 return false;
4590 Walker1++;
4591 Walker2++;
4592 }
4593 return false;
4594 }
4595 }
4596};
4597
4598#define UniquePolygonSet set < BoundaryPolygonSet *, BoundaryPolygonSetCompare>
4599
4600/** Finds all degenerated polygons and calls ReTesselateDegeneratedPolygon()/
4601 * \return number of polygons found
4602 */
4603int Tesselation::CorrectAllDegeneratedPolygons()
4604{
4605 Info FunctionInfo(__func__);
4606
4607 /// 2. Go through all BoundaryPointSet's, check their triangles' NormalVector
4608 IndexToIndex *DegeneratedTriangles = FindAllDegeneratedTriangles();
4609 set < BoundaryPointSet *> EndpointCandidateList;
4610 pair < set < BoundaryPointSet *>::iterator, bool > InsertionTester;
4611 pair < map < int, Vector *>::iterator, bool > TriangleInsertionTester;
4612 for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
4613 Log() << Verbose(0) << "Current point is " << *Runner->second << "." << endl;
4614 map < int, Vector *> TriangleVectors;
4615 // gather all NormalVectors
4616 Log() << Verbose(1) << "Gathering triangles ..." << endl;
4617 for (LineMap::const_iterator LineRunner = (Runner->second)->lines.begin(); LineRunner != (Runner->second)->lines.end(); LineRunner++)
4618 for (TriangleMap::const_iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
4619 if (DegeneratedTriangles->find(TriangleRunner->second->Nr) == DegeneratedTriangles->end()) {
4620 TriangleInsertionTester = TriangleVectors.insert( pair< int, Vector *> ((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)) );
4621 if (TriangleInsertionTester.second)
4622 Log() << Verbose(1) << " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list." << endl;
4623 } else {
4624 Log() << Verbose(1) << " NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one." << endl;
4625 }
4626 }
4627 // check whether there are two that are parallel
4628 Log() << Verbose(1) << "Finding two parallel triangles ..." << endl;
4629 for (map < int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
4630 for (map < int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
4631 if (VectorWalker != VectorRunner) { // skip equals
4632 const double SCP = VectorWalker->second->ScalarProduct(VectorRunner->second); // ScalarProduct should result in -1. for degenerated triangles
4633 Log() << Verbose(1) << "Checking " << *VectorWalker->second<< " against " << *VectorRunner->second << ": " << SCP << endl;
4634 if (fabs(SCP + 1.) < ParallelEpsilon) {
4635 InsertionTester = EndpointCandidateList.insert((Runner->second));
4636 if (InsertionTester.second)
4637 Log() << Verbose(0) << " Adding " << *Runner->second << " to endpoint candidate list." << endl;
4638 // and break out of both loops
4639 VectorWalker = TriangleVectors.end();
4640 VectorRunner = TriangleVectors.end();
4641 break;
4642 }
4643 }
4644 }
4645
4646 /// 3. Find connected endpoint candidates and put them into a polygon
4647 UniquePolygonSet ListofDegeneratedPolygons;
4648 BoundaryPointSet *Walker = NULL;
4649 BoundaryPointSet *OtherWalker = NULL;
4650 BoundaryPolygonSet *Current = NULL;
4651 stack <BoundaryPointSet*> ToCheckConnecteds;
4652 while (!EndpointCandidateList.empty()) {
4653 Walker = *(EndpointCandidateList.begin());
4654 if (Current == NULL) { // create a new polygon with current candidate
4655 Log() << Verbose(0) << "Starting new polygon set at point " << *Walker << endl;
4656 Current = new BoundaryPolygonSet;
4657 Current->endpoints.insert(Walker);
4658 EndpointCandidateList.erase(Walker);
4659 ToCheckConnecteds.push(Walker);
4660 }
4661
4662 // go through to-check stack
4663 while (!ToCheckConnecteds.empty()) {
4664 Walker = ToCheckConnecteds.top(); // fetch ...
4665 ToCheckConnecteds.pop(); // ... and remove
4666 for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
4667 OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
4668 Log() << Verbose(1) << "Checking " << *OtherWalker << endl;
4669 set < BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
4670 if (Finder != EndpointCandidateList.end()) { // found a connected partner
4671 Log() << Verbose(1) << " Adding to polygon." << endl;
4672 Current->endpoints.insert(OtherWalker);
4673 EndpointCandidateList.erase(Finder); // remove from candidates
4674 ToCheckConnecteds.push(OtherWalker); // but check its partners too
4675 } else {
4676 Log() << Verbose(1) << " is not connected to " << *Walker << endl;
4677 }
4678 }
4679 }
4680
4681 Log() << Verbose(0) << "Final polygon is " << *Current << endl;
4682 ListofDegeneratedPolygons.insert(Current);
4683 Current = NULL;
4684 }
4685
4686 const int counter = ListofDegeneratedPolygons.size();
4687
4688 Log() << Verbose(0) << "The following " << counter << " degenerated polygons have been found: " << endl;
4689 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
4690 Log() << Verbose(0) << " " << **PolygonRunner << endl;
4691
4692 /// 4. Go through all these degenerated polygons
4693 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++) {
4694 stack <int> TriangleNrs;
4695 Vector NormalVector;
4696 /// 4a. Gather all triangles of this polygon
4697 TriangleSet *T = (*PolygonRunner)->GetAllContainedTrianglesFromEndpoints();
4698
4699 // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
4700 if (T->size() == 2) {
4701 Log() << Verbose(1) << " Skipping degenerated polygon, is just a (already simply degenerated) triangle." << endl;
4702 delete(T);
4703 continue;
4704 }
4705
4706 // check whether number is even
4707 // If this case occurs, we have to think about it!
4708 // The Problem is probably due to two degenerated polygons being connected by a bridging, non-degenerated polygon, as somehow one node has
4709 // connections to either polygon ...
4710 if (T->size() % 2 != 0) {
4711 eLog() << Verbose(0) << " degenerated polygon contains an odd number of triangles, probably contains bridging non-degenerated ones, too!" << endl;
4712 performCriticalExit();
4713 }
4714
4715 TriangleSet::iterator TriangleWalker = T->begin(); // is the inner iterator
4716 /// 4a. Get NormalVector for one side (this is "front")
4717 NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
4718 Log() << Verbose(1) << "\"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector << endl;
4719 TriangleWalker++;
4720 TriangleSet::iterator TriangleSprinter = TriangleWalker; // is the inner advanced iterator
4721 /// 4b. Remove all triangles whose NormalVector is in opposite direction (i.e. "back")
4722 BoundaryTriangleSet *triangle = NULL;
4723 while (TriangleSprinter != T->end()) {
4724 TriangleWalker = TriangleSprinter;
4725 triangle = *TriangleWalker;
4726 TriangleSprinter++;
4727 Log() << Verbose(1) << "Current triangle to test for removal: " << *triangle << endl;
4728 if (triangle->NormalVector.ScalarProduct(&NormalVector) < 0) { // if from other side, then delete and remove from list
4729 Log() << Verbose(1) << " Removing ... " << endl;
4730 TriangleNrs.push(triangle->Nr);
4731 T->erase(TriangleWalker);
4732 RemoveTesselationTriangle(triangle);
4733 } else
4734 Log() << Verbose(1) << " Keeping ... " << endl;
4735 }
4736 /// 4c. Copy all "front" triangles but with inverse NormalVector
4737 TriangleWalker = T->begin();
4738 while (TriangleWalker != T->end()) { // go through all front triangles
4739 Log() << Verbose(1) << " Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector << endl;
4740 for (int i = 0; i < 3; i++)
4741 AddTesselationPoint((*TriangleWalker)->endpoints[i]->node, i);
4742 AddTesselationLine(TPS[0], TPS[1], 0);
4743 AddTesselationLine(TPS[0], TPS[2], 1);
4744 AddTesselationLine(TPS[1], TPS[2], 2);
4745 if (TriangleNrs.empty())
4746 eLog() << Verbose(0) << "No more free triangle numbers!" << endl;
4747 BTS = new BoundaryTriangleSet(BLS, TriangleNrs.top()); // copy triangle ...
4748 AddTesselationTriangle(); // ... and add
4749 TriangleNrs.pop();
4750 BTS->NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
4751 BTS->NormalVector.Scale(-1.);
4752 TriangleWalker++;
4753 }
4754 if (!TriangleNrs.empty()) {
4755 eLog() << Verbose(0) << "There have been less triangles created than removed!" << endl;
4756 }
4757 delete(T); // remove the triangleset
4758 }
4759
4760 IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
4761 Log() << Verbose(0) << "Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:" << endl;
4762 IndexToIndex::iterator it;
4763 for (it = SimplyDegeneratedTriangles->begin(); it != SimplyDegeneratedTriangles->end(); it++)
4764 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
4765 delete(SimplyDegeneratedTriangles);
4766
4767 /// 5. exit
4768 UniquePolygonSet::iterator PolygonRunner;
4769 while (!ListofDegeneratedPolygons.empty()) {
4770 PolygonRunner = ListofDegeneratedPolygons.begin();
4771 delete(*PolygonRunner);
4772 ListofDegeneratedPolygons.erase(PolygonRunner);
4773 }
4774
4775 return counter;
4776};
Note: See TracBrowser for help on using the repository browser.