source: src/tesselation.cpp@ b64313

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

FIX: Made AtomCount a Cacheable so that the number of atoms in a molecule will always be correct

All unittests working.
All Complete testcases fail.

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