source: src/tesselation.cpp@ 73b510

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 73b510 was 125b3c, checked in by Frederik Heber <heber@…>, 15 years ago

Non-convex tesselation seems to be working.

Seems like it has been working already. Only, we had some stupid test code still present after fixing the CorrectAllDegeneratedPolygons().

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