source: src/tesselation.cpp@ 5b9bba

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 5b9bba was e359a8, checked in by Frederik Heber <heber@…>, 15 years ago

Fixing ticket #18.

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