source: src/tesselation.cpp@ 05a97c

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

Repaired GetMAxId() method of molecule

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