source: src/tesselation.cpp@ c66537

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

Added copyright note to each .cpp file and an extensive one to builder.cpp.

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