source: src/tesselation.cpp@ 75a80f

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

Shortened constructors [Meyers, "Effective C++" item 12]

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