source: src/tesselation.cpp@ 273382

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 273382 was 273382, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Prepared interface of Vector Class for transition to VectorComposites

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