source: src/tesselation.cpp@ 717e0c

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 Candidate_v1.7.0 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 717e0c was 717e0c, checked in by Frederik Heber <heber@…>, 16 years ago

Verbosity corrected for ERROR and WARNING

  • present ERROR and WARNING prefixes removed and placed by eLog() and respective Verbosity().
  • -v... is scanned for number of 'v's and verbosity is set accordingly
  • standard verbosity is now 0.

Signed-off-by: Frederik Heber <heber@…>

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