source: src/Tesselation/tesselation.cpp@ da1e92

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 da1e92 was 418b5e, checked in by Frederik Heber <heber@…>, 13 years ago

Added verbosity to some tesselation functions.

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