source: src/tesselation.cpp@ 262bae

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 262bae was 262bae, checked in by Frederik Heber <heber@…>, 15 years ago

First compiling version of CorrectDegeneratedPolygons.

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