source: src/tesselation.cpp@ ab1932

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

Merge branch 'TesselationRefactoring' into ConcaveHull

Conflicts:

molecuilder/src/boundary.cpp
molecuilder/src/boundary.hpp
molecuilder/src/linkedcell.cpp
molecuilder/src/linkedcell.hpp
molecuilder/src/molecules.hpp

All of Saskia Metzler's new function were transfered from boundary.cpp to tesselation.cpp and the changes due to TesselPoint, LinkedCell and so on incorporated.

  • Property mode set to 100644
File size: 95.9 KB
Line 
1/*
2 * tesselation.cpp
3 *
4 * Created on: Aug 3, 2009
5 * Author: heber
6 */
7
8#include "tesselation.hpp"
9
10// ======================================== Points on Boundary =================================
11
12BoundaryPointSet::BoundaryPointSet()
13{
14 LinesCount = 0;
15 Nr = -1;
16}
17;
18
19BoundaryPointSet::BoundaryPointSet(TesselPoint *Walker)
20{
21 node = Walker;
22 LinesCount = 0;
23 Nr = Walker->nr;
24}
25;
26
27BoundaryPointSet::~BoundaryPointSet()
28{
29 cout << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
30 if (!lines.empty())
31 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some lines." << endl;
32 node = NULL;
33}
34;
35
36void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
37{
38 cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
39 << endl;
40 if (line->endpoints[0] == this)
41 {
42 lines.insert(LinePair(line->endpoints[1]->Nr, line));
43 }
44 else
45 {
46 lines.insert(LinePair(line->endpoints[0]->Nr, line));
47 }
48 LinesCount++;
49}
50;
51
52ostream &
53operator <<(ostream &ost, BoundaryPointSet &a)
54{
55 ost << "[" << a.Nr << "|" << a.node->Name << "]";
56 return ost;
57}
58;
59
60// ======================================== Lines on Boundary =================================
61
62BoundaryLineSet::BoundaryLineSet()
63{
64 for (int i = 0; i < 2; i++)
65 endpoints[i] = NULL;
66 TrianglesCount = 0;
67 Nr = -1;
68}
69;
70
71BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], int number)
72{
73 // set number
74 Nr = number;
75 // set endpoints in ascending order
76 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
77 // add this line to the hash maps of both endpoints
78 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
79 Point[1]->AddLine(this); //
80 // clear triangles list
81 TrianglesCount = 0;
82 cout << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
83}
84;
85
86BoundaryLineSet::~BoundaryLineSet()
87{
88 int Numbers[2];
89 Numbers[0] = endpoints[1]->Nr;
90 Numbers[1] = endpoints[0]->Nr;
91 for (int i = 0; i < 2; i++) {
92 cout << Verbose(5) << "Erasing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
93 // 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
94 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
95 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
96 if ((*Runner).second == this) {
97 endpoints[i]->lines.erase(Runner);
98 break;
99 }
100 if (endpoints[i]->lines.empty()) {
101 cout << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
102 if (endpoints[i] != NULL) {
103 delete(endpoints[i]);
104 endpoints[i] = NULL;
105 } else
106 cerr << "ERROR: Endpoint " << i << " has already been free'd." << endl;
107 } else
108 cout << Verbose(5) << *endpoints[i] << " has still lines it's attached to." << endl;
109 }
110 if (!triangles.empty())
111 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some triangles." << endl;
112}
113;
114
115void
116BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
117{
118 cout << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "."
119 << endl;
120 triangles.insert(TrianglePair(triangle->Nr, triangle));
121 TrianglesCount++;
122}
123;
124
125/** Checks whether we have a common endpoint with given \a *line.
126 * \param *line other line to test
127 * \return true - common endpoint present, false - not connected
128 */
129bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
130{
131 if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
132 return true;
133 else
134 return false;
135};
136
137/** Checks whether the adjacent triangles of a baseline are convex or not.
138 * We sum the two angles of each normal vector with a ficticious normnal vector from this baselinbe pointing outwards.
139 * If greater/equal M_PI than we are convex.
140 * \param *out output stream for debugging
141 * \return true - triangles are convex, false - concave or less than two triangles connected
142 */
143bool BoundaryLineSet::CheckConvexityCriterion(ofstream *out)
144{
145 Vector BaseLineNormal;
146 double angle = 0;
147 // get the two triangles
148 if (TrianglesCount != 2) {
149 *out << Verbose(1) << "ERROR: Baseline " << this << " is connect to less than two triangles, Tesselation incomplete!" << endl;
150 return false;
151 }
152 // have a normal vector on the base line pointing outwards
153 BaseLineNormal.Zero();
154 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++)
155 BaseLineNormal.AddVector(&runner->second->NormalVector);
156 BaseLineNormal.Normalize();
157 // and calculate the sum of the angles with this normal vector and each of the triangle ones'
158 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++)
159 angle += BaseLineNormal.Angle(&runner->second->NormalVector);
160
161 if ((angle - M_PI) > -MYEPSILON)
162 return true;
163 else
164 return false;
165}
166
167/** Checks whether point is any of the two endpoints this line contains.
168 * \param *point point to test
169 * \return true - point is of the line, false - is not
170 */
171bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
172{
173 for(int i=0;i<2;i++)
174 if (point == endpoints[i])
175 return true;
176 return false;
177};
178
179ostream &
180operator <<(ostream &ost, BoundaryLineSet &a)
181{
182 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << "," << a.endpoints[1]->node->Name << "]";
183 return ost;
184}
185;
186
187// ======================================== Triangles on Boundary =================================
188
189
190BoundaryTriangleSet::BoundaryTriangleSet()
191{
192 for (int i = 0; i < 3; i++)
193 {
194 endpoints[i] = NULL;
195 lines[i] = NULL;
196 }
197 Nr = -1;
198}
199;
200
201BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
202{
203 // set number
204 Nr = number;
205 // set lines
206 cout << Verbose(5) << "New triangle " << Nr << ":" << endl;
207 for (int i = 0; i < 3; i++)
208 {
209 lines[i] = line[i];
210 lines[i]->AddTriangle(this);
211 }
212 // get ascending order of endpoints
213 map<int, class BoundaryPointSet *> OrderMap;
214 for (int i = 0; i < 3; i++)
215 // for all three lines
216 for (int j = 0; j < 2; j++)
217 { // for both endpoints
218 OrderMap.insert(pair<int, class BoundaryPointSet *> (
219 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
220 // and we don't care whether insertion fails
221 }
222 // set endpoints
223 int Counter = 0;
224 cout << Verbose(6) << " with end points ";
225 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
226 != OrderMap.end(); runner++)
227 {
228 endpoints[Counter] = runner->second;
229 cout << " " << *endpoints[Counter];
230 Counter++;
231 }
232 if (Counter < 3)
233 {
234 cerr << "ERROR! We have a triangle with only two distinct endpoints!"
235 << endl;
236 //exit(1);
237 }
238 cout << "." << endl;
239}
240;
241
242BoundaryTriangleSet::~BoundaryTriangleSet()
243{
244 for (int i = 0; i < 3; i++) {
245 cout << Verbose(5) << "Erasing triangle Nr." << Nr << endl;
246 lines[i]->triangles.erase(Nr);
247 if (lines[i]->triangles.empty()) {
248 if (lines[i] != NULL) {
249 cout << Verbose(5) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
250 delete (lines[i]);
251 lines[i] = NULL;
252 } else
253 cerr << "ERROR: This line " << i << " has already been free'd." << endl;
254 } else
255 cout << Verbose(5) << *lines[i] << " is still attached to another triangle." << endl;
256 }
257}
258;
259
260/** Calculates the normal vector for this triangle.
261 * Is made unique by comparison with \a OtherVector to point in the other direction.
262 * \param &OtherVector direction vector to make normal vector unique.
263 */
264void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
265{
266 // get normal vector
267 NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
268
269 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
270 if (NormalVector.Projection(&OtherVector) > 0)
271 NormalVector.Scale(-1.);
272};
273
274/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
275 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
276 * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
277 * The latter is done as follows: if it's really outside, then for any endpoint of the triangle and it's opposite
278 * base line, the intersection between the line from endpoint to intersection and the base line will have a Vector::NormSquared()
279 * smaller than the first line.
280 * \param *out output stream for debugging
281 * \param *MolCenter offset vector of line
282 * \param *x second endpoint of line, minus \a *MolCenter is directional vector of line
283 * \param *Intersection intersection on plane on return
284 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
285 */
286bool BoundaryTriangleSet::GetIntersectionInsideTriangle(ofstream *out, Vector *MolCenter, Vector *x, Vector *Intersection)
287{
288 Vector CrossPoint;
289 Vector helper;
290 int i=0;
291
292 if (Intersection->GetIntersectionWithPlane(out, &NormalVector, endpoints[0]->node->node, MolCenter, x)) {
293 *out << Verbose(1) << "Alas! [Bronstein] failed - at least numerically - the intersection is not on the plane!" << endl;
294 return false;
295 }
296
297 // Calculate cross point between one baseline and the line from the third endpoint to intersection
298 do {
299 CrossPoint.GetIntersectionOfTwoLinesOnPlane(out, endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection);
300 helper.CopyVector(endpoints[(i+1)%3]->node->node);
301 helper.SubtractVector(endpoints[i%3]->node->node);
302 i++;
303 if (i>3)
304 break;
305 } while (CrossPoint.NormSquared() < MYEPSILON);
306 if (i>3) {
307 *out << Verbose(1) << "ERROR: Could not find any cross points, something's utterly wrong here!" << endl;
308 exit(255);
309 }
310 CrossPoint.SubtractVector(endpoints[i%3]->node->node);
311
312 // check whether intersection is inside or not by comparing length of intersection and length of cross point
313 if ((CrossPoint.NormSquared() - helper.NormSquared()) > -MYEPSILON) { // inside
314 return true;
315 } else { // outside!
316 Intersection->Zero();
317 return false;
318 }
319};
320
321/** Checks whether lines is any of the three boundary lines this triangle contains.
322 * \param *line line to test
323 * \return true - line is of the triangle, false - is not
324 */
325bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
326{
327 for(int i=0;i<3;i++)
328 if (line == lines[i])
329 return true;
330 return false;
331};
332
333/** Checks whether point is any of the three endpoints this triangle contains.
334 * \param *point point to test
335 * \return true - point is of the triangle, false - is not
336 */
337bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
338{
339 for(int i=0;i<3;i++)
340 if (point == endpoints[i])
341 return true;
342 return false;
343};
344
345/** Checks whether three given \a *Points coincide with triangle's endpoints.
346 * \param *Points[3] pointer to BoundaryPointSet
347 * \return true - is the very triangle, false - is not
348 */
349bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
350{
351 return (((endpoints[0] == Points[0])
352 || (endpoints[0] == Points[1])
353 || (endpoints[0] == Points[2])
354 ) && (
355 (endpoints[1] == Points[0])
356 || (endpoints[1] == Points[1])
357 || (endpoints[1] == Points[2])
358 ) && (
359 (endpoints[2] == Points[0])
360 || (endpoints[2] == Points[1])
361 || (endpoints[2] == Points[2])
362 ));
363};
364
365ostream &
366operator <<(ostream &ost, BoundaryTriangleSet &a)
367{
368 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << ","
369 << a.endpoints[1]->node->Name << "," << a.endpoints[2]->node->Name << "]";
370 return ost;
371}
372;
373
374// =========================================================== class TESSELPOINT ===========================================
375
376/** Constructor of class TesselPoint.
377 */
378TesselPoint::TesselPoint()
379{
380 node = NULL;
381 nr = -1;
382 Name = NULL;
383};
384
385/** Destructor for class TesselPoint.
386 */
387TesselPoint::~TesselPoint()
388{
389 Free((void **)&Name, "TesselPoint::~TesselPoint: *Name");
390};
391
392/** Prints LCNode to screen.
393 */
394ostream & operator << (ostream &ost, const TesselPoint &a)
395{
396 ost << "[" << (a.Name) << "|" << &a << "]";
397 return ost;
398};
399
400
401// =========================================================== class POINTCLOUD ============================================
402
403/** Constructor of class PointCloud.
404 */
405PointCloud::PointCloud()
406{
407
408};
409
410/** Destructor for class PointCloud.
411 */
412PointCloud::~PointCloud()
413{
414
415};
416
417// ============================ CandidateForTesselation =============================
418
419/** Constructor of class CandidateForTesselation.
420 */
421CandidateForTesselation::CandidateForTesselation(TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) {
422 point = candidate;
423 BaseLine = line;
424 OptCenter.CopyVector(&OptCandidateCenter);
425 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
426};
427
428/** Destructor for class CandidateForTesselation.
429 */
430CandidateForTesselation::~CandidateForTesselation() {
431 point = NULL;
432 BaseLine = NULL;
433};
434
435// =========================================================== class TESSELATION ===========================================
436
437/** Constructor of class Tesselation.
438 */
439Tesselation::Tesselation()
440{
441 PointsOnBoundaryCount = 0;
442 LinesOnBoundaryCount = 0;
443 TrianglesOnBoundaryCount = 0;
444}
445;
446
447/** Destructor of class Tesselation.
448 * We have to free all points, lines and triangles.
449 */
450Tesselation::~Tesselation()
451{
452 cout << Verbose(1) << "Free'ing TesselStruct ... " << endl;
453 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
454 if (runner->second != NULL) {
455 delete (runner->second);
456 runner->second = NULL;
457 } else
458 cerr << "ERROR: The triangle " << runner->first << " has already been free'd." << endl;
459 }
460}
461;
462
463/** Gueses first starting triangle of the convex envelope.
464 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
465 * \param *out output stream for debugging
466 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
467 */
468void
469Tesselation::GuessStartingTriangle(ofstream *out)
470{
471 // 4b. create a starting triangle
472 // 4b1. create all distances
473 DistanceMultiMap DistanceMMap;
474 double distance, tmp;
475 Vector PlaneVector, TrialVector;
476 PointMap::iterator A, B, C; // three nodes of the first triangle
477 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
478
479 // with A chosen, take each pair B,C and sort
480 if (A != PointsOnBoundary.end())
481 {
482 B = A;
483 B++;
484 for (; B != PointsOnBoundary.end(); B++)
485 {
486 C = B;
487 C++;
488 for (; C != PointsOnBoundary.end(); C++)
489 {
490 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
491 distance = tmp * tmp;
492 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
493 distance += tmp * tmp;
494 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
495 distance += tmp * tmp;
496 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
497 }
498 }
499 }
500 // // listing distances
501 // *out << Verbose(1) << "Listing DistanceMMap:";
502 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
503 // *out << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
504 // }
505 // *out << endl;
506 // 4b2. pick three baselines forming a triangle
507 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
508 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
509 for (; baseline != DistanceMMap.end(); baseline++)
510 {
511 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
512 // 2. next, we have to check whether all points reside on only one side of the triangle
513 // 3. construct plane vector
514 PlaneVector.MakeNormalVector(A->second->node->node,
515 baseline->second.first->second->node->node,
516 baseline->second.second->second->node->node);
517 *out << Verbose(2) << "Plane vector of candidate triangle is ";
518 PlaneVector.Output(out);
519 *out << endl;
520 // 4. loop over all points
521 double sign = 0.;
522 PointMap::iterator checker = PointsOnBoundary.begin();
523 for (; checker != PointsOnBoundary.end(); checker++)
524 {
525 // (neglecting A,B,C)
526 if ((checker == A) || (checker == baseline->second.first) || (checker
527 == baseline->second.second))
528 continue;
529 // 4a. project onto plane vector
530 TrialVector.CopyVector(checker->second->node->node);
531 TrialVector.SubtractVector(A->second->node->node);
532 distance = TrialVector.Projection(&PlaneVector);
533 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
534 continue;
535 *out << Verbose(3) << "Projection of " << checker->second->node->Name
536 << " yields distance of " << distance << "." << endl;
537 tmp = distance / fabs(distance);
538 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
539 if ((sign != 0) && (tmp != sign))
540 {
541 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
542 *out << Verbose(2) << "Current candidates: "
543 << A->second->node->Name << ","
544 << baseline->second.first->second->node->Name << ","
545 << baseline->second.second->second->node->Name << " leaves "
546 << checker->second->node->Name << " outside the convex hull."
547 << endl;
548 break;
549 }
550 else
551 { // note the sign for later
552 *out << Verbose(2) << "Current candidates: "
553 << A->second->node->Name << ","
554 << baseline->second.first->second->node->Name << ","
555 << baseline->second.second->second->node->Name << " leave "
556 << checker->second->node->Name << " inside the convex hull."
557 << endl;
558 sign = tmp;
559 }
560 // 4d. Check whether the point is inside the triangle (check distance to each node
561 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
562 int innerpoint = 0;
563 if ((tmp < A->second->node->node->DistanceSquared(
564 baseline->second.first->second->node->node)) && (tmp
565 < A->second->node->node->DistanceSquared(
566 baseline->second.second->second->node->node)))
567 innerpoint++;
568 tmp = checker->second->node->node->DistanceSquared(
569 baseline->second.first->second->node->node);
570 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
571 A->second->node->node)) && (tmp
572 < baseline->second.first->second->node->node->DistanceSquared(
573 baseline->second.second->second->node->node)))
574 innerpoint++;
575 tmp = checker->second->node->node->DistanceSquared(
576 baseline->second.second->second->node->node);
577 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
578 baseline->second.first->second->node->node)) && (tmp
579 < baseline->second.second->second->node->node->DistanceSquared(
580 A->second->node->node)))
581 innerpoint++;
582 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
583 if (innerpoint == 3)
584 break;
585 }
586 // 5. come this far, all on same side? Then break 1. loop and construct triangle
587 if (checker == PointsOnBoundary.end())
588 {
589 *out << "Looks like we have a candidate!" << endl;
590 break;
591 }
592 }
593 if (baseline != DistanceMMap.end())
594 {
595 BPS[0] = baseline->second.first->second;
596 BPS[1] = baseline->second.second->second;
597 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
598 BPS[0] = A->second;
599 BPS[1] = baseline->second.second->second;
600 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
601 BPS[0] = baseline->second.first->second;
602 BPS[1] = A->second;
603 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
604
605 // 4b3. insert created triangle
606 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
607 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
608 TrianglesOnBoundaryCount++;
609 for (int i = 0; i < NDIM; i++)
610 {
611 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
612 LinesOnBoundaryCount++;
613 }
614
615 *out << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
616 }
617 else
618 {
619 *out << Verbose(1) << "No starting triangle found." << endl;
620 exit(255);
621 }
622}
623;
624
625/** Tesselates the convex envelope of a cluster from a single starting triangle.
626 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
627 * 2 triangles. Hence, we go through all current lines:
628 * -# if the lines contains to only one triangle
629 * -# We search all points in the boundary
630 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
631 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
632 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
633 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
634 * \param *out output stream for debugging
635 * \param *configuration for IsAngstroem
636 * \param *cloud cluster of points
637 */
638void Tesselation::TesselateOnBoundary(ofstream *out, PointCloud *cloud)
639{
640 bool flag;
641 PointMap::iterator winner;
642 class BoundaryPointSet *peak = NULL;
643 double SmallestAngle, TempAngle;
644 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
645 LineMap::iterator LineChecker[2];
646
647 Center = cloud->GetCenter(out);
648 // create a first tesselation with the given BoundaryPoints
649 do {
650 flag = false;
651 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
652 if (baseline->second->TrianglesCount == 1) {
653 // 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)
654 SmallestAngle = M_PI;
655
656 // get peak point with respect to this base line's only triangle
657 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
658 *out << Verbose(2) << "Current baseline is between " << *(baseline->second) << "." << endl;
659 for (int i = 0; i < 3; i++)
660 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
661 peak = BTS->endpoints[i];
662 *out << Verbose(3) << " and has peak " << *peak << "." << endl;
663
664 // prepare some auxiliary vectors
665 Vector BaseLineCenter, BaseLine;
666 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
667 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
668 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
669 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
670 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
671
672 // offset to center of triangle
673 CenterVector.Zero();
674 for (int i = 0; i < 3; i++)
675 CenterVector.AddVector(BTS->endpoints[i]->node->node);
676 CenterVector.Scale(1. / 3.);
677 *out << Verbose(4) << "CenterVector of base triangle is " << CenterVector << endl;
678
679 // normal vector of triangle
680 NormalVector.CopyVector(Center);
681 NormalVector.SubtractVector(&CenterVector);
682 BTS->GetNormalVector(NormalVector);
683 NormalVector.CopyVector(&BTS->NormalVector);
684 *out << Verbose(4) << "NormalVector of base triangle is " << NormalVector << endl;
685
686 // vector in propagation direction (out of triangle)
687 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
688 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
689 TempVector.CopyVector(&CenterVector);
690 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
691 //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
692 if (PropagationVector.Projection(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
693 PropagationVector.Scale(-1.);
694 *out << Verbose(4) << "PropagationVector of base triangle is " << PropagationVector << endl;
695 winner = PointsOnBoundary.end();
696
697 // loop over all points and calculate angle between normal vector of new and present triangle
698 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
699 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
700 *out << Verbose(3) << "Target point is " << *(target->second) << ":" << endl;
701
702 // first check direction, so that triangles don't intersect
703 VirtualNormalVector.CopyVector(target->second->node->node);
704 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
705 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
706 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
707 *out << Verbose(4) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
708 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
709 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
710 continue;
711 } else
712 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
713
714 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
715 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
716 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
717 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->TrianglesCount == 2))) {
718 *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->TrianglesCount << " triangles." << endl;
719 continue;
720 }
721 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->TrianglesCount == 2))) {
722 *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->TrianglesCount << " triangles." << endl;
723 continue;
724 }
725
726 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
727 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)))) {
728 *out << Verbose(4) << "Current target is peak!" << endl;
729 continue;
730 }
731
732 // check for linear dependence
733 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
734 TempVector.SubtractVector(target->second->node->node);
735 helper.CopyVector(baseline->second->endpoints[1]->node->node);
736 helper.SubtractVector(target->second->node->node);
737 helper.ProjectOntoPlane(&TempVector);
738 if (fabs(helper.NormSquared()) < MYEPSILON) {
739 *out << Verbose(4) << "Chosen set of vectors is linear dependent." << endl;
740 continue;
741 }
742
743 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
744 flag = true;
745 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
746 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
747 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
748 TempVector.AddVector(target->second->node->node);
749 TempVector.Scale(1./3.);
750 TempVector.SubtractVector(Center);
751 // make it always point outward
752 if (VirtualNormalVector.Projection(&TempVector) < 0)
753 VirtualNormalVector.Scale(-1.);
754 // calculate angle
755 TempAngle = NormalVector.Angle(&VirtualNormalVector);
756 *out << Verbose(4) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
757 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
758 SmallestAngle = TempAngle;
759 winner = target;
760 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
761 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
762 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
763 helper.CopyVector(target->second->node->node);
764 helper.SubtractVector(&BaseLineCenter);
765 helper.ProjectOntoPlane(&BaseLine);
766 // ...the one with the smaller angle is the better candidate
767 TempVector.CopyVector(target->second->node->node);
768 TempVector.SubtractVector(&BaseLineCenter);
769 TempVector.ProjectOntoPlane(&VirtualNormalVector);
770 TempAngle = TempVector.Angle(&helper);
771 TempVector.CopyVector(winner->second->node->node);
772 TempVector.SubtractVector(&BaseLineCenter);
773 TempVector.ProjectOntoPlane(&VirtualNormalVector);
774 if (TempAngle < TempVector.Angle(&helper)) {
775 TempAngle = NormalVector.Angle(&VirtualNormalVector);
776 SmallestAngle = TempAngle;
777 winner = target;
778 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
779 } else
780 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
781 } else
782 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
783 }
784 } // end of loop over all boundary points
785
786 // 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
787 if (winner != PointsOnBoundary.end()) {
788 *out << Verbose(2) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
789 // create the lins of not yet present
790 BLS[0] = baseline->second;
791 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
792 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
793 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
794 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
795 BPS[0] = baseline->second->endpoints[0];
796 BPS[1] = winner->second;
797 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
798 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
799 LinesOnBoundaryCount++;
800 } else
801 BLS[1] = LineChecker[0]->second;
802 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
803 BPS[0] = baseline->second->endpoints[1];
804 BPS[1] = winner->second;
805 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
806 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
807 LinesOnBoundaryCount++;
808 } else
809 BLS[2] = LineChecker[1]->second;
810 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
811 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
812 TrianglesOnBoundaryCount++;
813 } else {
814 *out << Verbose(1) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
815 }
816
817 // 5d. If the set of lines is not yet empty, go to 5. and continue
818 } else
819 *out << Verbose(2) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->TrianglesCount << "." << endl;
820 } while (flag);
821
822 // exit
823 delete(Center);
824};
825
826/** Inserts all atoms outside of the tesselated surface into it by adding new triangles.
827 * \param *out output stream for debugging
828 * \param *cloud cluster of points
829 * \return true - all straddling points insert, false - something went wrong
830 */
831bool Tesselation::InsertStraddlingPoints(ofstream *out, PointCloud *cloud)
832{
833 Vector Intersection;
834 TesselPoint *Walker = NULL;
835 Vector *Center = cloud->GetCenter(out);
836
837 cloud->GoToFirst();
838 while (!cloud->IsLast()) { // we only have to go once through all points, as boundary can become only bigger
839 Walker = cloud->GetPoint();
840 // get the next triangle
841 BTS = FindClosestTriangleToPoint(out, Walker->node);
842 if (BTS == NULL) {
843 *out << Verbose(1) << "ERROR: No triangle closest to " << Walker << " was found." << endl;
844 return false;
845 }
846 // get the intersection point
847 if (BTS->GetIntersectionInsideTriangle(out, Center, Walker->node, &Intersection)) {
848 // we have the intersection, check whether in- or outside of boundary
849 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
850 // inside, next!
851 *out << Verbose(4) << Walker << " is inside wrt triangle " << BTS << "." << endl;
852 } else {
853 // outside!
854 *out << Verbose(3) << Walker << " is outside wrt triangle " << BTS << "." << endl;
855 class BoundaryLineSet *OldLines[3], *NewLines[3];
856 class BoundaryPointSet *OldPoints[3], *NewPoint;
857 // store the three old lines and old points
858 for (int i=0;i<3;i++) {
859 OldLines[i] = BTS->lines[i];
860 OldPoints[i] = BTS->endpoints[i];
861 }
862 // add Walker to boundary points
863 AddPoint(Walker);
864 if (BPS[0] == NULL)
865 NewPoint = BPS[0];
866 else
867 continue;
868 // remove triangle
869 TrianglesOnBoundary.erase(BTS->Nr);
870 // create three new boundary lines
871 for (int i=0;i<3;i++) {
872 BPS[0] = NewPoint;
873 BPS[1] = OldPoints[i];
874 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
875 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
876 LinesOnBoundaryCount++;
877 }
878 // create three new triangle with new point
879 for (int i=0;i<3;i++) { // find all baselines
880 BLS[0] = OldLines[i];
881 int n = 1;
882 for (int j=0;j<3;j++) {
883 if (NewLines[j]->IsConnectedTo(BLS[0])) {
884 if (n>2) {
885 *out << Verbose(1) << "ERROR: " << BLS[0] << " connects to all of the new lines?!" << endl;
886 return false;
887 } else
888 BLS[n++] = NewLines[j];
889 }
890 }
891 // create the triangle
892 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
893 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
894 TrianglesOnBoundaryCount++;
895 }
896 }
897 } else { // something is wrong with FindClosestTriangleToPoint!
898 *out << Verbose(1) << "ERROR: The closest triangle did not produce an intersection!" << endl;
899 return false;
900 }
901 cloud->GoToNext();
902 }
903
904 // exit
905 delete(Center);
906 return true;
907};
908
909/** Adds an atom to the tesselation::PointsOnBoundary list.
910 * \param *Walker atom to add
911 */
912void
913Tesselation::AddPoint(TesselPoint *Walker)
914{
915 PointTestPair InsertUnique;
916 BPS[0] = new class BoundaryPointSet(Walker);
917 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[0]));
918 if (InsertUnique.second) // if new point was not present before, increase counter
919 PointsOnBoundaryCount++;
920 else {
921 delete(BPS[0]);
922 BPS[0] = NULL;
923 }
924}
925;
926
927/** Adds point to Tesselation::PointsOnBoundary if not yet present.
928 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
929 * @param Candidate point to add
930 * @param n index for this point in Tesselation::TPS array
931 */
932void
933Tesselation::AddTrianglePoint(TesselPoint* Candidate, int n)
934{
935 PointTestPair InsertUnique;
936 TPS[n] = new class BoundaryPointSet(Candidate);
937 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
938 if (InsertUnique.second) { // if new point was not present before, increase counter
939 PointsOnBoundaryCount++;
940 } else {
941 delete TPS[n];
942 cout << Verbose(3) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
943 TPS[n] = (InsertUnique.first)->second;
944 }
945}
946;
947
948/** Function tries to add line from current Points in BPS to BoundaryLineSet.
949 * If successful it raises the line count and inserts the new line into the BLS,
950 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
951 * @param *a first endpoint
952 * @param *b second endpoint
953 * @param n index of Tesselation::BLS giving the line with both endpoints
954 */
955void Tesselation::AddTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n) {
956 bool insertNewLine = true;
957
958 if (a->lines.find(b->node->nr) != a->lines.end()) {
959 LineMap::iterator FindLine;
960 pair<LineMap::iterator,LineMap::iterator> FindPair;
961 FindPair = a->lines.equal_range(b->node->nr);
962
963 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
964 // If there is a line with less than two attached triangles, we don't need a new line.
965 if (FindLine->second->TrianglesCount < 2) {
966 insertNewLine = false;
967 cout << Verbose(3) << "Using existing line " << *FindLine->second << endl;
968
969 BPS[0] = FindLine->second->endpoints[0];
970 BPS[1] = FindLine->second->endpoints[1];
971 BLS[n] = FindLine->second;
972
973 break;
974 }
975 }
976 }
977
978 if (insertNewLine) {
979 AlwaysAddTriangleLine(a, b, n);
980 }
981}
982;
983
984/**
985 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
986 * Raises the line count and inserts the new line into the BLS.
987 *
988 * @param *a first endpoint
989 * @param *b second endpoint
990 * @param n index of Tesselation::BLS giving the line with both endpoints
991 */
992void Tesselation::AlwaysAddTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n)
993{
994 cout << Verbose(3) << "Adding line between " << *(a->node) << " and " << *(b->node) << "." << endl;
995 BPS[0] = a;
996 BPS[1] = b;
997 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
998 // add line to global map
999 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1000 // increase counter
1001 LinesOnBoundaryCount++;
1002};
1003
1004/** Function tries to add Triangle just created to Triangle and remarks if already existent (Failure of algorithm).
1005 * Furthermore it adds the triangle to all of its lines, in order to recognize those which are saturated later.
1006 */
1007void
1008Tesselation::AddTriangle()
1009{
1010 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1011
1012 // add triangle to global map
1013 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1014 TrianglesOnBoundaryCount++;
1015
1016 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1017}
1018;
1019
1020
1021
1022/** Checks whether the triangle consisting of the three atoms is already present.
1023 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1024 * lines. If any of the three edges already has two triangles attached, false is
1025 * returned.
1026 * \param *out output stream for debugging
1027 * \param *Candidates endpoints of the triangle candidate
1028 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1029 * triangles exist which is the maximum for three points
1030 */
1031int Tesselation::CheckPresenceOfTriangle(ofstream *out, TesselPoint *Candidates[3]) {
1032 int adjacentTriangleCount = 0;
1033 class BoundaryPointSet *Points[3];
1034
1035 *out << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1036 // builds a triangle point set (Points) of the end points
1037 for (int i = 0; i < 3; i++) {
1038 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1039 if (FindPoint != PointsOnBoundary.end()) {
1040 Points[i] = FindPoint->second;
1041 } else {
1042 Points[i] = NULL;
1043 }
1044 }
1045
1046 // checks lines between the points in the Points for their adjacent triangles
1047 for (int i = 0; i < 3; i++) {
1048 if (Points[i] != NULL) {
1049 for (int j = i; j < 3; j++) {
1050 if (Points[j] != NULL) {
1051 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1052 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1053 TriangleMap *triangles = &FindLine->second->triangles;
1054 *out << Verbose(3) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1055 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1056 if (FindTriangle->second->IsPresentTupel(Points)) {
1057 adjacentTriangleCount++;
1058 }
1059 }
1060 *out << Verbose(3) << "end." << endl;
1061 }
1062 // Only one of the triangle lines must be considered for the triangle count.
1063 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1064 return adjacentTriangleCount;
1065 }
1066 }
1067 }
1068 }
1069
1070 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1071 *out << Verbose(2) << "End of CheckPresenceOfTriangle" << endl;
1072 return adjacentTriangleCount;
1073};
1074
1075
1076/** Finds the starting triangle for find_non_convex_border().
1077 * Looks at the outermost atom per axis, then Find_second_point_for_Tesselation()
1078 * for the second and Find_next_suitable_point_via_Angle_of_Sphere() for the third
1079 * point are called.
1080 * \param *out output stream for debugging
1081 * \param RADIUS radius of virtual rolling sphere
1082 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1083 */
1084void Tesselation::Find_starting_triangle(ofstream *out, const double RADIUS, LinkedCell *LC)
1085{
1086 cout << Verbose(1) << "Begin of Find_starting_triangle\n";
1087 int i = 0;
1088 LinkedNodes *List = NULL;
1089 TesselPoint* FirstPoint = NULL;
1090 TesselPoint* SecondPoint = NULL;
1091 TesselPoint* MaxAtom[NDIM];
1092 double max_coordinate[NDIM];
1093 Vector Oben;
1094 Vector helper;
1095 Vector Chord;
1096 Vector SearchDirection;
1097
1098 Oben.Zero();
1099
1100 for (i = 0; i < 3; i++) {
1101 MaxAtom[i] = NULL;
1102 max_coordinate[i] = -1;
1103 }
1104
1105 // 1. searching topmost atom with respect to each axis
1106 for (int i=0;i<NDIM;i++) { // each axis
1107 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1108 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1109 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1110 List = LC->GetCurrentCell();
1111 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1112 if (List != NULL) {
1113 for (LinkedNodes::iterator Runner = List->begin();Runner != List->end();Runner++) {
1114 if ((*Runner)->node->x[i] > max_coordinate[i]) {
1115 cout << Verbose(2) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1116 max_coordinate[i] = (*Runner)->node->x[i];
1117 MaxAtom[i] = (*Runner);
1118 }
1119 }
1120 } else {
1121 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1122 }
1123 }
1124 }
1125
1126 cout << Verbose(2) << "Found maximum coordinates: ";
1127 for (int i=0;i<NDIM;i++)
1128 cout << i << ": " << *MaxAtom[i] << "\t";
1129 cout << endl;
1130
1131 BTS = NULL;
1132 CandidateList *Opt_Candidates = new CandidateList();
1133 for (int k=0;k<NDIM;k++) {
1134 Oben.x[k] = 1.;
1135 FirstPoint = MaxAtom[k];
1136 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1137
1138 double ShortestAngle;
1139 TesselPoint* Opt_Candidate = NULL;
1140 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.
1141
1142 Find_second_point_for_Tesselation(FirstPoint, NULL, Oben, Opt_Candidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1143 SecondPoint = Opt_Candidate;
1144 if (SecondPoint == NULL) // have we found a second point?
1145 continue;
1146 else
1147 cout << Verbose(1) << "Found second point is at " << *SecondPoint->node << ".\n";
1148
1149 helper.CopyVector(FirstPoint->node);
1150 helper.SubtractVector(SecondPoint->node);
1151 helper.Normalize();
1152 Oben.ProjectOntoPlane(&helper);
1153 Oben.Normalize();
1154 helper.VectorProduct(&Oben);
1155 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1156
1157 Chord.CopyVector(FirstPoint->node); // bring into calling function
1158 Chord.SubtractVector(SecondPoint->node);
1159 double radius = Chord.ScalarProduct(&Chord);
1160 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1161 helper.CopyVector(&Oben);
1162 helper.Scale(CircleRadius);
1163 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
1164
1165 // look in one direction of baseline for initial candidate
1166 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
1167
1168 // adding point 1 and point 2 and the line between them
1169 AddTrianglePoint(FirstPoint, 0);
1170 AddTrianglePoint(SecondPoint, 1);
1171 AddTriangleLine(TPS[0], TPS[1], 0);
1172
1173 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
1174 Find_third_point_for_Tesselation(
1175 Oben, SearchDirection, helper, BLS[0], NULL, *&Opt_Candidates, &ShortestAngle, RADIUS, LC
1176 );
1177 cout << Verbose(1) << "List of third Points is ";
1178 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1179 cout << " " << *(*it)->point;
1180 }
1181 cout << endl;
1182
1183 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1184 // add third triangle point
1185 AddTrianglePoint((*it)->point, 2);
1186 // add the second and third line
1187 AddTriangleLine(TPS[1], TPS[2], 1);
1188 AddTriangleLine(TPS[0], TPS[2], 2);
1189 // ... and triangles to the Maps of the Tesselation class
1190 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1191 AddTriangle();
1192 // ... and calculate its normal vector (with correct orientation)
1193 (*it)->OptCenter.Scale(-1.);
1194 cout << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
1195 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
1196 cout << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
1197 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
1198
1199 // if we do not reach the end with the next step of iteration, we need to setup a new first line
1200 if (it != Opt_Candidates->end()--) {
1201 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
1202 SecondPoint = (*it)->point;
1203 // adding point 1 and point 2 and the line between them
1204 AddTrianglePoint(FirstPoint, 0);
1205 AddTrianglePoint(SecondPoint, 1);
1206 AddTriangleLine(TPS[0], TPS[1], 0);
1207 }
1208 cout << Verbose(2) << "Projection is " << BTS->NormalVector.Projection(&Oben) << "." << endl;
1209 }
1210 if (BTS != NULL) // we have created one starting triangle
1211 break;
1212 else {
1213 // remove all candidates from the list and then the list itself
1214 class CandidateForTesselation *remover = NULL;
1215 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1216 remover = *it;
1217 delete(remover);
1218 }
1219 Opt_Candidates->clear();
1220 }
1221 }
1222
1223 // remove all candidates from the list and then the list itself
1224 class CandidateForTesselation *remover = NULL;
1225 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1226 remover = *it;
1227 delete(remover);
1228 }
1229 delete(Opt_Candidates);
1230 cout << Verbose(1) << "End of Find_starting_triangle\n";
1231};
1232
1233
1234/** This function finds a triangle to a line, adjacent to an existing one.
1235 * @param out output stream for debugging
1236 * @param Line current baseline to search from
1237 * @param T current triangle which \a Line is edge of
1238 * @param RADIUS radius of the rolling ball
1239 * @param N number of found triangles
1240 * @param *LC LinkedCell structure with neighbouring atoms
1241 */
1242bool Tesselation::Find_next_suitable_triangle(ofstream *out, BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, int N, LinkedCell *LC)
1243{
1244 cout << Verbose(0) << "Begin of Find_next_suitable_triangle\n";
1245 bool result = true;
1246 CandidateList *Opt_Candidates = new CandidateList();
1247
1248 Vector CircleCenter;
1249 Vector CirclePlaneNormal;
1250 Vector OldSphereCenter;
1251 Vector SearchDirection;
1252 Vector helper;
1253 TesselPoint *ThirdNode = NULL;
1254 LineMap::iterator testline;
1255 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1256 double radius, CircleRadius;
1257
1258 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
1259 for (int i=0;i<3;i++)
1260 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
1261 ThirdNode = T.endpoints[i]->node;
1262
1263 // construct center of circle
1264 CircleCenter.CopyVector(Line.endpoints[0]->node->node);
1265 CircleCenter.AddVector(Line.endpoints[1]->node->node);
1266 CircleCenter.Scale(0.5);
1267
1268 // construct normal vector of circle
1269 CirclePlaneNormal.CopyVector(Line.endpoints[0]->node->node);
1270 CirclePlaneNormal.SubtractVector(Line.endpoints[1]->node->node);
1271
1272 // calculate squared radius of circle
1273 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1274 if (radius/4. < RADIUS*RADIUS) {
1275 CircleRadius = RADIUS*RADIUS - radius/4.;
1276 CirclePlaneNormal.Normalize();
1277 cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1278
1279 // construct old center
1280 GetCenterofCircumcircle(&OldSphereCenter, T.endpoints[0]->node->node, T.endpoints[1]->node->node, T.endpoints[2]->node->node);
1281 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
1282 radius = Line.endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
1283 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1284 OldSphereCenter.AddVector(&helper);
1285 OldSphereCenter.SubtractVector(&CircleCenter);
1286 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
1287
1288 // construct SearchDirection
1289 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
1290 helper.CopyVector(Line.endpoints[0]->node->node);
1291 helper.SubtractVector(ThirdNode->node);
1292 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
1293 SearchDirection.Scale(-1.);
1294 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
1295 SearchDirection.Normalize();
1296 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1297 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
1298 // rotated the wrong way!
1299 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
1300 }
1301
1302 // add third point
1303 Find_third_point_for_Tesselation(
1304 T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, Opt_Candidates,
1305 &ShortestAngle, RADIUS, LC
1306 );
1307
1308 } else {
1309 cout << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
1310 }
1311
1312 if (Opt_Candidates->begin() == Opt_Candidates->end()) {
1313 cerr << "WARNING: Could not find a suitable candidate." << endl;
1314 return false;
1315 }
1316 cout << Verbose(1) << "Third Points are ";
1317 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1318 cout << " " << *(*it)->point;
1319 }
1320 cout << endl;
1321
1322 BoundaryLineSet *BaseRay = &Line;
1323 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1324 cout << Verbose(1) << " Third point candidate is " << *(*it)->point
1325 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
1326 cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
1327
1328 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
1329 TesselPoint *AtomCandidates[3];
1330 AtomCandidates[0] = (*it)->point;
1331 AtomCandidates[1] = BaseRay->endpoints[0]->node;
1332 AtomCandidates[2] = BaseRay->endpoints[1]->node;
1333 int existentTrianglesCount = CheckPresenceOfTriangle(out, AtomCandidates);
1334
1335 BTS = NULL;
1336 // If there is no triangle, add it regularly.
1337 if (existentTrianglesCount == 0) {
1338 AddTrianglePoint((*it)->point, 0);
1339 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
1340 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
1341
1342 AddTriangleLine(TPS[0], TPS[1], 0);
1343 AddTriangleLine(TPS[0], TPS[2], 1);
1344 AddTriangleLine(TPS[1], TPS[2], 2);
1345
1346 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1347 AddTriangle();
1348 (*it)->OptCenter.Scale(-1.);
1349 BTS->GetNormalVector((*it)->OptCenter);
1350 (*it)->OptCenter.Scale(-1.);
1351
1352 cout << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1353 << " for this triangle ... " << endl;
1354 //cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
1355 } else if (existentTrianglesCount == 1) { // If there is a planar region within the structure, we need this triangle a second time.
1356 AddTrianglePoint((*it)->point, 0);
1357 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
1358 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
1359
1360 // 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)
1361 // i.e. at least one of the three lines must be present with TriangleCount <= 1
1362 if (CheckLineCriteriaforDegeneratedTriangle(TPS)) {
1363 AddTriangleLine(TPS[0], TPS[1], 0);
1364 AddTriangleLine(TPS[0], TPS[2], 1);
1365 AddTriangleLine(TPS[1], TPS[2], 2);
1366
1367 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1368 AddTriangle();
1369
1370 (*it)->OtherOptCenter.Scale(-1.);
1371 BTS->GetNormalVector((*it)->OtherOptCenter);
1372 (*it)->OtherOptCenter.Scale(-1.);
1373
1374 cout << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1375 << " for this triangle ... " << endl;
1376 cout << Verbose(1) << "We have "<< BaseRay->TrianglesCount << " for line " << BaseRay << "." << endl;
1377 } else {
1378 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1379 cout << *(*it)->point << ", ";
1380 cout << *BaseRay->endpoints[0]->node << " and ";
1381 cout << *BaseRay->endpoints[1]->node << " ";
1382 cout << "exists and is not added, as it does not seem helpful!" << endl;
1383 result = false;
1384 }
1385 } else {
1386 cout << Verbose(1) << "This triangle consisting of ";
1387 cout << *(*it)->point << ", ";
1388 cout << *BaseRay->endpoints[0]->node << " and ";
1389 cout << *BaseRay->endpoints[1]->node << " ";
1390 cout << "is invalid!" << endl;
1391 result = false;
1392 }
1393
1394 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
1395 BaseRay = BLS[0];
1396 }
1397
1398 // remove all candidates from the list and then the list itself
1399 class CandidateForTesselation *remover = NULL;
1400 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1401 remover = *it;
1402 delete(remover);
1403 }
1404 delete(Opt_Candidates);
1405 cout << Verbose(0) << "End of Find_next_suitable_triangle\n";
1406 return result;
1407};
1408
1409
1410/** Goes over all baselines and checks whether adjacent triangles and convex to each other.
1411 * \param *out output stream for debugging
1412 * \return true - all baselines were corrected, false - there are still concave pieces
1413 */
1414bool Tesselation::CorrectConcaveBaselines(ofstream *out)
1415{
1416 class BoundaryTriangleSet *triangle[2];
1417 class BoundaryLineSet *OldLines[4], *NewLine;
1418 class BoundaryPointSet *OldPoints[2];
1419 Vector BaseLineNormal;
1420 class BoundaryLineSet *Base = NULL;
1421 int OldTriangles[2], OldBaseLine;
1422 int i;
1423 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++) {
1424 Base = baseline->second;
1425
1426 // check convexity
1427 if (Base->CheckConvexityCriterion(out)) { // triangles are convex
1428 *out << Verbose(3) << Base << " has two convex triangles." << endl;
1429 } else { // not convex!
1430 // get the two triangles
1431 i=0;
1432 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1433 triangle[i++] = runner->second;
1434 // gather four endpoints and four lines
1435 for (int j=0;j<4;j++)
1436 OldLines[j] = NULL;
1437 for (int j=0;j<2;j++)
1438 OldPoints[j] = NULL;
1439 i=0;
1440 for (int m=0;m<2;m++) { // go over both triangles
1441 for (int j=0;j<3;j++) { // all of their endpoints and baselines
1442 if (triangle[m]->lines[j] != Base) // pick not the central baseline
1443 OldLines[i++] = triangle[m]->lines[j];
1444 if (!Base->ContainsBoundaryPoint(triangle[m]->endpoints[j])) // and neither of its endpoints
1445 OldPoints[m] = triangle[m]->endpoints[j];
1446 }
1447 }
1448 if (i<4) {
1449 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
1450 return false;
1451 }
1452 for (int j=0;j<4;j++)
1453 if (OldLines[j] == NULL) {
1454 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
1455 return false;
1456 }
1457 for (int j=0;j<2;j++)
1458 if (OldPoints[j] == NULL) {
1459 *out << Verbose(1) << "ERROR: We have not gathered enough endpoints!" << endl;
1460 return false;
1461 }
1462
1463 // remove triangles
1464 for (int j=0;j<2;j++) {
1465 OldTriangles[j] = triangle[j]->Nr;
1466 TrianglesOnBoundary.erase(OldTriangles[j]);
1467 triangle[j] = NULL;
1468 }
1469
1470 // remove baseline
1471 OldBaseLine = Base->Nr;
1472 LinesOnBoundary.erase(OldBaseLine);
1473 Base = NULL;
1474
1475 // construct new baseline (with same number as old one)
1476 BPS[0] = OldPoints[0];
1477 BPS[1] = OldPoints[1];
1478 NewLine = new class BoundaryLineSet(BPS, OldBaseLine);
1479 LinesOnBoundary.insert(LinePair(OldBaseLine, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
1480
1481 // construct new triangles with flipped baseline
1482 i=-1;
1483 if (BLS[0]->IsConnectedTo(OldLines[2]))
1484 i=2;
1485 if (BLS[0]->IsConnectedTo(OldLines[2]))
1486 i=3;
1487 if (i!=-1) {
1488 BLS[0] = OldLines[0];
1489 BLS[1] = OldLines[i];
1490 BLS[2] = NewLine;
1491 BTS = new class BoundaryTriangleSet(BLS, OldTriangles[0]);
1492 TrianglesOnBoundary.insert(TrianglePair(OldTriangles[0], BTS));
1493
1494 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
1495 BLS[1] = OldLines[1];
1496 BLS[2] = NewLine;
1497 BTS = new class BoundaryTriangleSet(BLS, OldTriangles[1]);
1498 TrianglesOnBoundary.insert(TrianglePair(OldTriangles[1], BTS));
1499 } else {
1500 *out << Verbose(1) << "The four old lines do not connect, something's utterly wrong here!" << endl;
1501 return false;
1502 }
1503 }
1504 }
1505 return true;
1506};
1507
1508
1509/** States whether point is in- or outside of a tesselated surface.
1510 * \param *pointer point to be checked
1511 * \return true - is inside, false - is outside
1512 */
1513bool Tesselation::IsInside(Vector *pointer)
1514{
1515
1516 // hier kommt dann Saskias Routine hin...
1517
1518 return true;
1519};
1520
1521
1522/** Finds the closest triangle to a given point.
1523 * \param *out output stream for debugging
1524 * \param *x second endpoint of line
1525 * \return pointer triangle that is closest, NULL if none was found
1526 */
1527class BoundaryTriangleSet * Tesselation::FindClosestTriangleToPoint(ofstream *out, Vector *x)
1528{
1529 class BoundaryTriangleSet *triangle = NULL;
1530
1531 // hier kommt dann Saskias Routine hin...
1532
1533 return triangle;
1534};
1535
1536
1537/** Finds the second point of starting triangle.
1538 * \param *a first node
1539 * \param *Candidate pointer to candidate node on return
1540 * \param Oben vector indicating the outside
1541 * \param Opt_Candidate reference to recommended candidate on return
1542 * \param Storage[3] array storing angles and other candidate information
1543 * \param RADIUS radius of virtual sphere
1544 * \param *LC LinkedCell structure with neighbouring atoms
1545 */
1546void Tesselation::Find_second_point_for_Tesselation(TesselPoint* a, TesselPoint* Candidate, Vector Oben, TesselPoint*& Opt_Candidate, double Storage[3], double RADIUS, LinkedCell *LC)
1547{
1548 cout << Verbose(2) << "Begin of Find_second_point_for_Tesselation" << endl;
1549 Vector AngleCheck;
1550 double norm = -1., angle;
1551 LinkedNodes *List = NULL;
1552 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
1553
1554 if (LC->SetIndexToNode(a)) { // get cell for the starting atom
1555 for(int i=0;i<NDIM;i++) // store indices of this cell
1556 N[i] = LC->n[i];
1557 } else {
1558 cerr << "ERROR: Atom " << *a << " is not found in cell " << LC->index << "." << endl;
1559 return;
1560 }
1561 // then go through the current and all neighbouring cells and check the contained atoms for possible candidates
1562 cout << Verbose(3) << "LC Intervals from [";
1563 for (int i=0;i<NDIM;i++) {
1564 cout << " " << N[i] << "<->" << LC->N[i];
1565 }
1566 cout << "] :";
1567 for (int i=0;i<NDIM;i++) {
1568 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
1569 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
1570 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
1571 }
1572 cout << endl;
1573
1574
1575 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
1576 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
1577 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
1578 List = LC->GetCurrentCell();
1579 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1580 if (List != NULL) {
1581 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
1582 Candidate = (*Runner);
1583 // check if we only have one unique point yet ...
1584 if (a != Candidate) {
1585 // Calculate center of the circle with radius RADIUS through points a and Candidate
1586 Vector OrthogonalizedOben, a_Candidate, Center;
1587 double distance, scaleFactor;
1588
1589 OrthogonalizedOben.CopyVector(&Oben);
1590 a_Candidate.CopyVector(a->node);
1591 a_Candidate.SubtractVector(Candidate->node);
1592 OrthogonalizedOben.ProjectOntoPlane(&a_Candidate);
1593 OrthogonalizedOben.Normalize();
1594 distance = 0.5 * a_Candidate.Norm();
1595 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
1596 OrthogonalizedOben.Scale(scaleFactor);
1597
1598 Center.CopyVector(Candidate->node);
1599 Center.AddVector(a->node);
1600 Center.Scale(0.5);
1601 Center.AddVector(&OrthogonalizedOben);
1602
1603 AngleCheck.CopyVector(&Center);
1604 AngleCheck.SubtractVector(a->node);
1605 norm = a_Candidate.Norm();
1606 // second point shall have smallest angle with respect to Oben vector
1607 if (norm < RADIUS*2.) {
1608 angle = AngleCheck.Angle(&Oben);
1609 if (angle < Storage[0]) {
1610 //cout << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
1611 cout << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
1612 Opt_Candidate = Candidate;
1613 Storage[0] = angle;
1614 //cout << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
1615 } else {
1616 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *Opt_Candidate << endl;
1617 }
1618 } else {
1619 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
1620 }
1621 } else {
1622 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
1623 }
1624 }
1625 } else {
1626 cout << Verbose(3) << "Linked cell list is empty." << endl;
1627 }
1628 }
1629 cout << Verbose(2) << "End of Find_second_point_for_Tesselation" << endl;
1630};
1631
1632
1633/** This recursive function finds a third point, to form a triangle with two given ones.
1634 * Note that this function is for the starting triangle.
1635 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
1636 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
1637 * the center of the sphere is still fixed up to a single parameter. The band of possible values
1638 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
1639 * us the "null" on this circle, the new center of the candidate point will be some way along this
1640 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
1641 * by the normal vector of the base triangle that always points outwards by construction.
1642 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
1643 * We construct the normal vector that defines the plane this circle lies in, it is just in the
1644 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
1645 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
1646 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
1647 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
1648 * both.
1649 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
1650 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
1651 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
1652 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
1653 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
1654 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
1655 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa Find_starting_triangle())
1656 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
1657 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
1658 * @param BaseLine BoundaryLineSet with the current base line
1659 * @param ThirdNode third atom to avoid in search
1660 * @param candidates list of equally good candidates to return
1661 * @param ShortestAngle the current path length on this circle band for the current Opt_Candidate
1662 * @param RADIUS radius of sphere
1663 * @param *LC LinkedCell structure with neighbouring atoms
1664 */
1665void Tesselation::Find_third_point_for_Tesselation(Vector NormalVector, Vector SearchDirection, Vector OldSphereCenter, class BoundaryLineSet *BaseLine, class TesselPoint *ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, LinkedCell *LC)
1666{
1667 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
1668 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
1669 Vector SphereCenter;
1670 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
1671 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
1672 Vector NewNormalVector; // normal vector of the Candidate's triangle
1673 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
1674 LinkedNodes *List = NULL;
1675 double CircleRadius; // radius of this circle
1676 double radius;
1677 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
1678 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
1679 TesselPoint *Candidate = NULL;
1680 CandidateForTesselation *optCandidate = NULL;
1681
1682 cout << Verbose(1) << "Begin of Find_third_point_for_Tesselation" << endl;
1683
1684 //cout << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
1685
1686 // construct center of circle
1687 CircleCenter.CopyVector(BaseLine->endpoints[0]->node->node);
1688 CircleCenter.AddVector(BaseLine->endpoints[1]->node->node);
1689 CircleCenter.Scale(0.5);
1690
1691 // construct normal vector of circle
1692 CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
1693 CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
1694
1695 // calculate squared radius TesselPoint *ThirdNode,f circle
1696 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1697 if (radius/4. < RADIUS*RADIUS) {
1698 CircleRadius = RADIUS*RADIUS - radius/4.;
1699 CirclePlaneNormal.Normalize();
1700 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1701
1702 // test whether old center is on the band's plane
1703 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
1704 cerr << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
1705 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
1706 }
1707 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
1708 if (fabs(radius - CircleRadius) < HULLEPSILON) {
1709
1710 // check SearchDirection
1711 //cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1712 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
1713 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
1714 }
1715
1716 // get cell for the starting atom
1717 if (LC->SetIndexToVector(&CircleCenter)) {
1718 for(int i=0;i<NDIM;i++) // store indices of this cell
1719 N[i] = LC->n[i];
1720 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
1721 } else {
1722 cerr << "ERROR: Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
1723 return;
1724 }
1725 // then go through the current and all neighbouring cells and check the contained atoms for possible candidates
1726 //cout << Verbose(2) << "LC Intervals:";
1727 for (int i=0;i<NDIM;i++) {
1728 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
1729 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
1730 //cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
1731 }
1732 //cout << endl;
1733 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
1734 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
1735 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
1736 List = LC->GetCurrentCell();
1737 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1738 if (List != NULL) {
1739 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
1740 Candidate = (*Runner);
1741
1742 // check for three unique points
1743 //cout << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->x << "." << endl;
1744 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
1745
1746 // construct both new centers
1747 GetCenterofCircumcircle(&NewSphereCenter, BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node);
1748 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
1749
1750 if ((NewNormalVector.MakeNormalVector(BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node))
1751 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
1752 ) {
1753 helper.CopyVector(&NewNormalVector);
1754 //cout << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
1755 radius = BaseLine->endpoints[0]->node->node->DistanceSquared(&NewSphereCenter);
1756 if (radius < RADIUS*RADIUS) {
1757 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1758 //cout << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
1759 NewSphereCenter.AddVector(&helper);
1760 NewSphereCenter.SubtractVector(&CircleCenter);
1761 //cout << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
1762
1763 // OtherNewSphereCenter is created by the same vector just in the other direction
1764 helper.Scale(-1.);
1765 OtherNewSphereCenter.AddVector(&helper);
1766 OtherNewSphereCenter.SubtractVector(&CircleCenter);
1767 //cout << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
1768
1769 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
1770 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
1771 alpha = min(alpha, Otheralpha);
1772 // if there is a better candidate, drop the current list and add the new candidate
1773 // otherwise ignore the new candidate and keep the list
1774 if (*ShortestAngle > (alpha - HULLEPSILON)) {
1775 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
1776 if (fabs(alpha - Otheralpha) > MYEPSILON) {
1777 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
1778 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
1779 } else {
1780 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
1781 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
1782 }
1783 // if there is an equal candidate, add it to the list without clearing the list
1784 if ((*ShortestAngle - HULLEPSILON) < alpha) {
1785 candidates->push_back(optCandidate);
1786 cout << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
1787 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
1788 } else {
1789 // remove all candidates from the list and then the list itself
1790 class CandidateForTesselation *remover = NULL;
1791 for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
1792 remover = *it;
1793 delete(remover);
1794 }
1795 candidates->clear();
1796 candidates->push_back(optCandidate);
1797 cout << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
1798 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
1799 }
1800 *ShortestAngle = alpha;
1801 //cout << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
1802 } else {
1803 if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
1804 //cout << Verbose(2) << "REJECT: Old candidate: " << *(optCandidate->point) << " is better than " << alpha << " with " << *ShortestAngle << "." << endl;
1805 } else {
1806 //cout << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
1807 }
1808 }
1809
1810 } else {
1811 //cout << Verbose(2) << "REJECT: NewSphereCenter " << NewSphereCenter << " is too far away: " << radius << "." << endl;
1812 }
1813 } else {
1814 //cout << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
1815 }
1816 } else {
1817 if (ThirdNode != NULL) {
1818 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
1819 } else {
1820 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
1821 }
1822 }
1823 }
1824 }
1825 }
1826 } else {
1827 cerr << Verbose(2) << "ERROR: The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
1828 }
1829 } else {
1830 if (ThirdNode != NULL)
1831 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
1832 else
1833 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
1834 }
1835
1836 //cout << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
1837 if (candidates->size() > 1) {
1838 candidates->unique();
1839 candidates->sort(sortCandidates);
1840 }
1841
1842 cout << Verbose(1) << "End of Find_third_point_for_Tesselation" << endl;
1843};
1844
1845/** Finds the endpoint two lines are sharing.
1846 * \param *line1 first line
1847 * \param *line2 second line
1848 * \return point which is shared or NULL if none
1849 */
1850class BoundaryPointSet *Tesselation::GetCommonEndpoint(class BoundaryLineSet * line1, class BoundaryLineSet * line2)
1851{
1852 class BoundaryLineSet * lines[2] =
1853 { line1, line2 };
1854 class BoundaryPointSet *node = NULL;
1855 map<int, class BoundaryPointSet *> OrderMap;
1856 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
1857 for (int i = 0; i < 2; i++)
1858 // for both lines
1859 for (int j = 0; j < 2; j++)
1860 { // for both endpoints
1861 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
1862 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
1863 if (!OrderTest.second)
1864 { // if insertion fails, we have common endpoint
1865 node = OrderTest.first->second;
1866 cout << Verbose(5) << "Common endpoint of lines " << *line1
1867 << " and " << *line2 << " is: " << *node << "." << endl;
1868 j = 2;
1869 i = 2;
1870 break;
1871 }
1872 }
1873 return node;
1874};
1875
1876/** Checks for a new special triangle whether one of its edges is already present with one one triangle connected.
1877 * This enforces that special triangles (i.e. degenerated ones) should at last close the open-edge frontier and not
1878 * make it bigger (i.e. closing one (the baseline) and opening two new ones).
1879 * \param TPS[3] nodes of the triangle
1880 * \return true - there is such a line (i.e. creation of degenerated triangle is valid), false - no such line (don't create)
1881 */
1882bool CheckLineCriteriaforDegeneratedTriangle(class BoundaryPointSet *nodes[3])
1883{
1884 bool result = false;
1885 int counter = 0;
1886
1887 // check all three points
1888 for (int i=0;i<3;i++)
1889 for (int j=i+1; j<3; j++) {
1890 if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) { // there already is a line
1891 LineMap::iterator FindLine;
1892 pair<LineMap::iterator,LineMap::iterator> FindPair;
1893 FindPair = nodes[i]->lines.equal_range(nodes[j]->node->nr);
1894 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
1895 // If there is a line with less than two attached triangles, we don't need a new line.
1896 if (FindLine->second->TrianglesCount < 2) {
1897 counter++;
1898 break; // increase counter only once per edge
1899 }
1900 }
1901 } else { // no line
1902 cout << Verbose(1) << "ERROR: The line between " << nodes[i] << " and " << nodes[j] << " is not yet present, hence no need for a degenerate triangle!" << endl;
1903 result = true;
1904 }
1905 }
1906 if (counter > 1) {
1907 cout << Verbose(2) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl;
1908 result = true;
1909 }
1910 return result;
1911};
1912
1913
1914/** Sort function for the candidate list.
1915 */
1916bool sortCandidates(CandidateForTesselation* candidate1, CandidateForTesselation* candidate2)
1917{
1918 Vector BaseLineVector, OrthogonalVector, helper;
1919 if (candidate1->BaseLine != candidate2->BaseLine) { // sanity check
1920 cout << Verbose(0) << "ERROR: sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
1921 //return false;
1922 exit(1);
1923 }
1924 // create baseline vector
1925 BaseLineVector.CopyVector(candidate1->BaseLine->endpoints[1]->node->node);
1926 BaseLineVector.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
1927 BaseLineVector.Normalize();
1928
1929 // create normal in-plane vector to cope with acos() non-uniqueness on [0,2pi] (note that is pointing in the "right" direction already, hence ">0" test!)
1930 helper.CopyVector(candidate1->BaseLine->endpoints[0]->node->node);
1931 helper.SubtractVector(candidate1->point->node);
1932 OrthogonalVector.CopyVector(&helper);
1933 helper.VectorProduct(&BaseLineVector);
1934 OrthogonalVector.SubtractVector(&helper);
1935 OrthogonalVector.Normalize();
1936
1937 // calculate both angles and correct with in-plane vector
1938 helper.CopyVector(candidate1->point->node);
1939 helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
1940 double phi = BaseLineVector.Angle(&helper);
1941 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
1942 phi = 2.*M_PI - phi;
1943 }
1944 helper.CopyVector(candidate2->point->node);
1945 helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
1946 double psi = BaseLineVector.Angle(&helper);
1947 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
1948 psi = 2.*M_PI - psi;
1949 }
1950
1951 cout << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
1952 cout << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
1953
1954 // return comparison
1955 return phi < psi;
1956};
1957
1958
1959/**
1960 * Checks whether the provided atom is within the tesselation structure.
1961 *
1962 * @param *Atom of which to check the position
1963 * @param tesselation structure
1964 *
1965 * @return true if the atom is inside the tesselation structure, false otherwise
1966 */
1967bool IsInnerPoint(TesselPoint *Atom, class Tesselation *Tess, LinkedCell* LC)
1968{
1969 if (Tess->LinesOnBoundary.begin() == Tess->LinesOnBoundary.end()) {
1970 cout << Verbose(0) << "Error: There is no tesselation structure to compare the point with, "
1971 << "please create one first.";
1972 exit(1);
1973 }
1974
1975 class TesselPoint *trianglePoints[3];
1976 trianglePoints[0] = findClosestAtom(Atom, LC);
1977 // check whether closest atom is "too close" :), then it's inside
1978 if (trianglePoints[0]->node->DistanceSquared(Atom->node) < MYEPSILON)
1979 return true;
1980 list<TesselPoint*> *connectedClosestPoints = Tess->getClosestConnectedAtoms(trianglePoints[0], Atom);
1981 trianglePoints[1] = connectedClosestPoints->front();
1982 trianglePoints[2] = connectedClosestPoints->back();
1983 for (int i=0;i<3;i++) {
1984 if (trianglePoints[i] == NULL) {
1985 cout << Verbose(1) << "IsInnerPoint encounters serious error, point " << i << " not found." << endl;
1986 }
1987
1988 cout << Verbose(1) << "List of possible atoms:" << endl;
1989 cout << *trianglePoints[i] << endl;
1990
1991// for(list<TesselPoint*>::iterator runner = connectedClosestPoints->begin(); runner != connectedClosestPoints->end(); runner++)
1992// cout << Verbose(2) << *(*runner) << endl;
1993 }
1994 delete(connectedClosestPoints);
1995
1996 list<BoundaryTriangleSet*> *triangles = Tess->FindTriangles(trianglePoints);
1997
1998 if (triangles->empty()) {
1999 cout << Verbose(0) << "Error: There is no nearest triangle. Please check the tesselation structure.";
2000 exit(1);
2001 }
2002
2003 Vector helper;
2004 helper.CopyVector(Atom->node);
2005
2006 // Only in case of degeneration, there will be two different scalar products.
2007 // If at least one scalar product is positive, the point is considered to be outside.
2008 bool status = (helper.ScalarProduct(&triangles->front()->NormalVector) < 0)
2009 && (helper.ScalarProduct(&triangles->back()->NormalVector) < 0);
2010 delete(triangles);
2011 return status;
2012}
2013
2014/**
2015 * Finds the atom which is closest to the provided one.
2016 *
2017 * @param atom to which to find the closest other atom
2018 * @param linked cell structure
2019 *
2020 * @return atom which is closest to the provided one
2021 */
2022TesselPoint* findClosestAtom(const TesselPoint* Atom, LinkedCell* LC)
2023{
2024 LinkedNodes *List = NULL;
2025 TesselPoint* closestAtom = NULL;
2026 double distance = 1e16;
2027 Vector helper;
2028 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2029
2030 LC->SetIndexToVector(Atom->node); // ignore status as we calculate bounds below sensibly
2031 for(int i=0;i<NDIM;i++) // store indices of this cell
2032 N[i] = LC->n[i];
2033 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2034
2035 LC->GetNeighbourBounds(Nlower, Nupper);
2036 //cout << endl;
2037 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2038 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2039 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2040 List = LC->GetCurrentCell();
2041 //cout << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
2042 if (List != NULL) {
2043 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2044 helper.CopyVector(Atom->node);
2045 helper.SubtractVector((*Runner)->node);
2046 double currentNorm = helper. Norm();
2047 if (currentNorm < distance) {
2048 distance = currentNorm;
2049 closestAtom = (*Runner);
2050 }
2051 }
2052 } else {
2053 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << ","
2054 << LC->n[2] << " is invalid!" << endl;
2055 }
2056 }
2057
2058 return closestAtom;
2059}
2060
2061/**
2062 * Gets all atoms connected to the provided atom by triangulation lines.
2063 *
2064 * @param atom of which get all connected atoms
2065 * @param atom to be checked whether it is an inner atom
2066 *
2067 * @return list of the two atoms linked to the provided one and closest to the atom to be checked,
2068 */
2069list<TesselPoint*> * Tesselation::getClosestConnectedAtoms(TesselPoint* Atom, TesselPoint* AtomToCheck)
2070{
2071 list<TesselPoint*> connectedAtoms;
2072 map<double, TesselPoint*> anglesOfAtoms;
2073 map<double, TesselPoint*>::iterator runner;
2074 LineMap::iterator findLines = LinesOnBoundary.begin();
2075 list<TesselPoint*>::iterator listRunner;
2076 Vector center, planeNorm, currentPoint, OrthogonalVector, helper;
2077 TesselPoint* current;
2078 bool takeAtom = false;
2079
2080 planeNorm.CopyVector(Atom->node);
2081 planeNorm.SubtractVector(AtomToCheck->node);
2082 planeNorm.Normalize();
2083
2084 while (findLines != LinesOnBoundary.end()) {
2085 takeAtom = false;
2086
2087 if (findLines->second->endpoints[0]->Nr == Atom->nr) {
2088 takeAtom = true;
2089 current = findLines->second->endpoints[1]->node;
2090 } else if (findLines->second->endpoints[1]->Nr == Atom->nr) {
2091 takeAtom = true;
2092 current = findLines->second->endpoints[0]->node;
2093 }
2094
2095 if (takeAtom) {
2096 connectedAtoms.push_back(current);
2097 currentPoint.CopyVector(current->node);
2098 currentPoint.ProjectOntoPlane(&planeNorm);
2099 center.AddVector(&currentPoint);
2100 }
2101
2102 findLines++;
2103 }
2104
2105 cout << "Summed vectors " << center << "; number of atoms " << connectedAtoms.size()
2106 << "; scale factor " << 1.0/connectedAtoms.size();
2107
2108 center.Scale(1.0/connectedAtoms.size());
2109 listRunner = connectedAtoms.begin();
2110
2111 cout << " calculated center " << center << endl;
2112
2113 // construct one orthogonal vector
2114 helper.CopyVector(AtomToCheck->node);
2115 helper.ProjectOntoPlane(&planeNorm);
2116 OrthogonalVector.MakeNormalVector(&center, &helper, (*listRunner)->node);
2117 while (listRunner != connectedAtoms.end()) {
2118 double angle = getAngle(*((*listRunner)->node), *(AtomToCheck->node), center, OrthogonalVector);
2119 cout << "Calculated angle " << angle << " for atom " << **listRunner << endl;
2120 anglesOfAtoms.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
2121 listRunner++;
2122 }
2123
2124 list<TesselPoint*> *result = new list<TesselPoint*>;
2125 runner = anglesOfAtoms.begin();
2126 cout << "First value is " << *runner->second << endl;
2127 result->push_back(runner->second);
2128 runner = anglesOfAtoms.end();
2129 runner--;
2130 cout << "Second value is " << *runner->second << endl;
2131 result->push_back(runner->second);
2132
2133 cout << "List of closest atoms has " << result->size() << " elements, which are "
2134 << *(result->front()) << " and " << *(result->back()) << endl;
2135
2136 return result;
2137}
2138
2139/**
2140 * Finds triangles belonging to the three provided atoms.
2141 *
2142 * @param atom list, is expected to contain three atoms
2143 *
2144 * @return triangles which belong to the provided atoms, will be empty if there are none,
2145 * will usually be one, in case of degeneration, there will be two
2146 */
2147list<BoundaryTriangleSet*> *Tesselation::FindTriangles(TesselPoint* Points[3])
2148{
2149 list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
2150 LineMap::iterator FindLine;
2151 PointMap::iterator FindPoint;
2152 TriangleMap::iterator FindTriangle;
2153 class BoundaryPointSet *TrianglePoints[3];
2154
2155 for (int i = 0; i < 3; i++) {
2156 FindPoint = PointsOnBoundary.find(Points[i]->nr);
2157 if (FindPoint != PointsOnBoundary.end()) {
2158 TrianglePoints[i] = FindPoint->second;
2159 } else {
2160 TrianglePoints[i] = NULL;
2161 }
2162 }
2163
2164 // checks lines between the points in the Points for their adjacent triangles
2165 for (int i = 0; i < 3; i++) {
2166 if (TrianglePoints[i] != NULL) {
2167 for (int j = i; j < 3; j++) {
2168 if (TrianglePoints[j] != NULL) {
2169 FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr);
2170 if (FindLine != TrianglePoints[i]->lines.end()) {
2171 for (; FindLine->first == TrianglePoints[j]->node->nr; FindLine++) {
2172 FindTriangle = FindLine->second->triangles.begin();
2173 for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
2174 if ((
2175 (FindTriangle->second->endpoints[0] == TrianglePoints[0])
2176 || (FindTriangle->second->endpoints[0] == TrianglePoints[1])
2177 || (FindTriangle->second->endpoints[0] == TrianglePoints[2])
2178 ) && (
2179 (FindTriangle->second->endpoints[1] == TrianglePoints[0])
2180 || (FindTriangle->second->endpoints[1] == TrianglePoints[1])
2181 || (FindTriangle->second->endpoints[1] == TrianglePoints[2])
2182 ) && (
2183 (FindTriangle->second->endpoints[2] == TrianglePoints[0])
2184 || (FindTriangle->second->endpoints[2] == TrianglePoints[1])
2185 || (FindTriangle->second->endpoints[2] == TrianglePoints[2])
2186 )
2187 ) {
2188 result->push_back(FindTriangle->second);
2189 }
2190 }
2191 }
2192 // Is it sufficient to consider one of the triangle lines for this.
2193 return result;
2194
2195 }
2196 }
2197 }
2198 }
2199 }
2200
2201 return result;
2202}
2203
2204/**
2205 * Gets the angle between a point and a reference relative to the provided center.
2206 *
2207 * @param point to calculate the angle for
2208 * @param reference to which to calculate the angle
2209 * @param center for which to calculate the angle between the vectors
2210 * @param OrthogonalVector helps discern between [0,pi] and [pi,2pi] in acos()
2211 *
2212 * @return angle between point and reference
2213 */
2214double getAngle(Vector point, Vector reference, Vector center, Vector OrthogonalVector)
2215{
2216 Vector ReferenceVector, helper;
2217 cout << Verbose(2) << reference << " is our reference " << endl;
2218 cout << Verbose(2) << center << " is our center " << endl;
2219 // create baseline vector
2220 ReferenceVector.CopyVector(&reference);
2221 ReferenceVector.SubtractVector(&center);
2222 if (ReferenceVector.IsNull())
2223 return M_PI;
2224
2225 // calculate both angles and correct with in-plane vector
2226 helper.CopyVector(&point);
2227 helper.SubtractVector(&center);
2228 if (helper.IsNull())
2229 return M_PI;
2230 double phi = ReferenceVector.Angle(&helper);
2231 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2232 phi = 2.*M_PI - phi;
2233 }
2234
2235 cout << Verbose(2) << point << " has angle " << phi << endl;
2236
2237 return phi;
2238}
2239
2240/**
2241 * Checks whether the provided point is within the tesselation structure.
2242 *
2243 * This is a wrapper function for IsInnerAtom, so it can be used with a simple
2244 * vector, too.
2245 *
2246 * @param point of which to check the position
2247 * @param tesselation structure
2248 *
2249 * @return true if the point is inside the tesselation structure, false otherwise
2250 */
2251bool IsInnerPoint(Vector Point, class Tesselation *Tess, LinkedCell* LC)
2252{
2253 TesselPoint *temp_atom = new TesselPoint;
2254 bool status = false;
2255 temp_atom->node->CopyVector(&Point);
2256
2257 status = IsInnerPoint(temp_atom, Tess, LC);
2258 delete(temp_atom);
2259
2260 return status;
2261}
2262
Note: See TracBrowser for help on using the repository browser.