source: src/tesselation.cpp@ 57066a

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 57066a was 57066a, checked in by Frederik Heber <heber@…>, 16 years ago

Various fixes and attempt to get convex hull working.

Moved tesselation writing to tesselation.cpp

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