source: src/Tesselation/tesselation.cpp@ 2a3124

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

VERBOSE: Removed lots of Info objects in tesselation classes member 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 TriangleIntersectionList Intersections(Point, this, LC);
2574 return Intersections.IsInside();
2575}
2576
2577/** Returns the distance to the surface given by the tesselation.
2578 * Calls FindClosestTriangleToVector() and checks whether the resulting triangle's BoundaryTriangleSet#NormalVector points
2579 * towards or away from the given \a &Point. Additionally, we check whether it's normal to the normal vector, i.e. on the
2580 * closest triangle's plane. Then, we have to check whether \a Point is inside the triangle or not to determine whether it's
2581 * an inside or outside point. This is done by calling BoundaryTriangleSet::GetIntersectionInsideTriangle().
2582 * In the end we additionally find the point on the triangle who was smallest distance to \a Point:
2583 * -# Separate distance from point to center in vector in NormalDirection and on the triangle plane.
2584 * -# Check whether vector on triangle plane points inside the triangle or crosses triangle bounds.
2585 * -# If inside, take it to calculate closest distance
2586 * -# If not, take intersection with BoundaryLine as distance
2587 *
2588 * @note distance is squared despite it still contains a sign to determine in-/outside!
2589 *
2590 * @param point of which to check the position
2591 * @param *LC LinkedCell_deprecated structure
2592 *
2593 * @return >0 if outside, ==0 if on surface, <0 if inside
2594 */
2595double Tesselation::GetDistanceSquaredToTriangle(const Vector &Point, const BoundaryTriangleSet* const triangle) const
2596{
2597 Info FunctionInfo(__func__);
2598 Vector Center;
2599 Vector helper;
2600 Vector DistanceToCenter;
2601 Vector Intersection;
2602 double distance = 0.;
2603
2604 if (triangle == NULL) {// is boundary point or only point in point cloud?
2605 LOG(1, "No triangle given!");
2606 return -1.;
2607 } else {
2608 LOG(1, "INFO: Closest triangle found is " << *triangle << " with normal vector " << triangle->NormalVector << ".");
2609 }
2610
2611 triangle->GetCenter(Center);
2612 LOG(2, "INFO: Central point of the triangle is " << Center << ".");
2613 DistanceToCenter = Center - Point;
2614 LOG(2, "INFO: Vector from point to test to center is " << DistanceToCenter << ".");
2615
2616 // check whether we are on boundary
2617 if (fabs(DistanceToCenter.ScalarProduct(triangle->NormalVector)) < MYEPSILON) {
2618 // calculate whether inside of triangle
2619 DistanceToCenter = Point + triangle->NormalVector; // points outside
2620 Center = Point - triangle->NormalVector; // points towards MolCenter
2621 LOG(1, "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << ".");
2622 if (triangle->GetIntersectionInsideTriangle(Center, DistanceToCenter, Intersection)) {
2623 LOG(1, Point << " is inner point: sufficiently close to boundary, " << Intersection << ".");
2624 return 0.;
2625 } else {
2626 LOG(1, Point << " is NOT an inner point: on triangle plane but outside of triangle bounds.");
2627 return false;
2628 }
2629 } else {
2630 // calculate smallest distance
2631 distance = triangle->GetClosestPointInsideTriangle(Point, Intersection);
2632 LOG(1, "Closest point on triangle is " << Intersection << ".");
2633
2634 // then check direction to boundary
2635 if (DistanceToCenter.ScalarProduct(triangle->NormalVector) > MYEPSILON) {
2636 LOG(1, Point << " is an inner point, " << distance << " below surface.");
2637 return -distance;
2638 } else {
2639 LOG(1, Point << " is NOT an inner point, " << distance << " above surface.");
2640 return +distance;
2641 }
2642 }
2643}
2644;
2645
2646/** Calculates minimum distance from \a&Point to a tesselated surface.
2647 * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
2648 * \param &Point point to calculate distance from
2649 * \param *LC needed for finding closest points fast
2650 * \return distance squared to closest point on surface
2651 */
2652double Tesselation::GetDistanceToSurface(const Vector &Point, const LinkedCell_deprecated* const LC) const
2653{
2654 Info FunctionInfo(__func__);
2655 TriangleIntersectionList Intersections(Point, this, LC);
2656
2657 return Intersections.GetSmallestDistance();
2658}
2659;
2660
2661/** Calculates minimum distance from \a&Point to a tesselated surface.
2662 * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
2663 * \param &Point point to calculate distance from
2664 * \param *LC needed for finding closest points fast
2665 * \return distance squared to closest point on surface
2666 */
2667BoundaryTriangleSet * Tesselation::GetClosestTriangleOnSurface(const Vector &Point, const LinkedCell_deprecated* const LC) const
2668{
2669 Info FunctionInfo(__func__);
2670 TriangleIntersectionList Intersections(Point, this, LC);
2671
2672 return Intersections.GetClosestTriangle();
2673}
2674;
2675
2676/** Gets all points connected to the provided point by triangulation lines.
2677 *
2678 * @param *Point of which get all connected points
2679 *
2680 * @return set of the all points linked to the provided one
2681 */
2682TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
2683{
2684 Info FunctionInfo(__func__);
2685 TesselPointSet *connectedPoints = new TesselPointSet;
2686 class BoundaryPointSet *ReferencePoint = NULL;
2687 TesselPoint* current;
2688 bool takePoint = false;
2689 // find the respective boundary point
2690 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->getNr());
2691 if (PointRunner != PointsOnBoundary.end()) {
2692 ReferencePoint = PointRunner->second;
2693 } else {
2694 ELOG(2, "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << ".");
2695 ReferencePoint = NULL;
2696 }
2697
2698 // little trick so that we look just through lines connect to the BoundaryPoint
2699 // OR fall-back to look through all lines if there is no such BoundaryPoint
2700 const LineMap *Lines;
2701 ;
2702 if (ReferencePoint != NULL)
2703 Lines = &(ReferencePoint->lines);
2704 else
2705 Lines = &LinesOnBoundary;
2706 LineMap::const_iterator findLines = Lines->begin();
2707 while (findLines != Lines->end()) {
2708 takePoint = false;
2709
2710 if (findLines->second->endpoints[0]->Nr == Point->getNr()) {
2711 takePoint = true;
2712 current = findLines->second->endpoints[1]->node;
2713 } else if (findLines->second->endpoints[1]->Nr == Point->getNr()) {
2714 takePoint = true;
2715 current = findLines->second->endpoints[0]->node;
2716 }
2717
2718 if (takePoint) {
2719 LOG(1, "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted.");
2720 connectedPoints->insert(current);
2721 }
2722
2723 findLines++;
2724 }
2725
2726 if (connectedPoints->empty()) { // if have not found any points
2727 ELOG(1, "We have not found any connected points to " << *Point << ".");
2728 return NULL;
2729 }
2730
2731 return connectedPoints;
2732}
2733;
2734
2735/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2736 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2737 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2738 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2739 * triangle we are looking for.
2740 *
2741 * @param *out output stream for debugging
2742 * @param *SetOfNeighbours all points for which the angle should be calculated
2743 * @param *Point of which get all connected points
2744 * @param *Reference Reference vector for zero angle or NULL for no preference
2745 * @return list of the all points linked to the provided one
2746 */
2747TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector &Reference) const
2748{
2749 Info FunctionInfo(__func__);
2750 map<double, TesselPoint*> anglesOfPoints;
2751 TesselPointList *connectedCircle = new TesselPointList;
2752 Vector PlaneNormal;
2753 Vector AngleZero;
2754 Vector OrthogonalVector;
2755 Vector helper;
2756 const TesselPoint * const TrianglePoints[3] = { Point, NULL, NULL };
2757 TriangleList *triangles = NULL;
2758
2759 if (SetOfNeighbours == NULL) {
2760 ELOG(2, "Could not find any connected points!");
2761 delete (connectedCircle);
2762 return NULL;
2763 }
2764
2765 // calculate central point
2766 triangles = FindTriangles(TrianglePoints);
2767 if ((triangles != NULL) && (!triangles->empty())) {
2768 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
2769 PlaneNormal += (*Runner)->NormalVector;
2770 } else {
2771 ELOG(0, "Could not find any triangles for point " << *Point << ".");
2772 performCriticalExit();
2773 }
2774 PlaneNormal.Scale(1.0 / triangles->size());
2775 LOG(1, "INFO: Calculated PlaneNormal of all circle points is " << PlaneNormal << ".");
2776 PlaneNormal.Normalize();
2777
2778 // construct one orthogonal vector
2779 AngleZero = (Reference) - (Point->getPosition());
2780 AngleZero.ProjectOntoPlane(PlaneNormal);
2781 if ((AngleZero.NormSquared() < MYEPSILON)) {
2782 LOG(1, "Using alternatively " << (*SetOfNeighbours->begin())->getPosition() << " as angle 0 referencer.");
2783 AngleZero = ((*SetOfNeighbours->begin())->getPosition()) - (Point->getPosition());
2784 AngleZero.ProjectOntoPlane(PlaneNormal);
2785 if (AngleZero.NormSquared() < MYEPSILON) {
2786 ELOG(0, "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!");
2787 performCriticalExit();
2788 }
2789 }
2790 LOG(1, "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << ".");
2791 if (AngleZero.NormSquared() > MYEPSILON)
2792 OrthogonalVector = Plane(PlaneNormal, AngleZero,0).getNormal();
2793 else
2794 OrthogonalVector.MakeNormalTo(PlaneNormal);
2795 LOG(1, "INFO: OrthogonalVector on plane is " << OrthogonalVector << ".");
2796
2797 // go through all connected points and calculate angle
2798 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
2799 helper = ((*listRunner)->getPosition()) - (Point->getPosition());
2800 helper.ProjectOntoPlane(PlaneNormal);
2801 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
2802 LOG(0, "INFO: Calculated angle is " << angle << " for point " << **listRunner << ".");
2803 anglesOfPoints.insert(pair<double, TesselPoint*> (angle, (*listRunner)));
2804 }
2805
2806 for (map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
2807 connectedCircle->push_back(AngleRunner->second);
2808 }
2809
2810 return connectedCircle;
2811}
2812
2813/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2814 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2815 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2816 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2817 * triangle we are looking for.
2818 *
2819 * @param *SetOfNeighbours all points for which the angle should be calculated
2820 * @param *Point of which get all connected points
2821 * @param *Reference Reference vector for zero angle or (0,0,0) for no preference
2822 * @return list of the all points linked to the provided one
2823 */
2824TesselPointList * Tesselation::GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector &Reference) const
2825{
2826 Info FunctionInfo(__func__);
2827 map<double, TesselPoint*> anglesOfPoints;
2828 TesselPointList *connectedCircle = new TesselPointList;
2829 Vector center;
2830 Vector PlaneNormal;
2831 Vector AngleZero;
2832 Vector OrthogonalVector;
2833 Vector helper;
2834
2835 if (SetOfNeighbours == NULL) {
2836 ELOG(2, "Could not find any connected points!");
2837 delete (connectedCircle);
2838 return NULL;
2839 }
2840
2841 // check whether there's something to do
2842 if (SetOfNeighbours->size() < 3) {
2843 for (TesselPointSet::iterator TesselRunner = SetOfNeighbours->begin(); TesselRunner != SetOfNeighbours->end(); TesselRunner++)
2844 connectedCircle->push_back(*TesselRunner);
2845 return connectedCircle;
2846 }
2847
2848 LOG(1, "INFO: Point is " << *Point << " and Reference is " << Reference << ".");
2849 // calculate central point
2850 TesselPointSet::const_iterator TesselA = SetOfNeighbours->begin();
2851 TesselPointSet::const_iterator TesselB = SetOfNeighbours->begin();
2852 TesselPointSet::const_iterator TesselC = SetOfNeighbours->begin();
2853 TesselB++;
2854 TesselC++;
2855 TesselC++;
2856 int counter = 0;
2857 while (TesselC != SetOfNeighbours->end()) {
2858 helper = Plane(((*TesselA)->getPosition()),
2859 ((*TesselB)->getPosition()),
2860 ((*TesselC)->getPosition())).getNormal();
2861 LOG(0, "Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper);
2862 counter++;
2863 TesselA++;
2864 TesselB++;
2865 TesselC++;
2866 PlaneNormal += helper;
2867 }
2868 //LOG(0, "Summed vectors " << center << "; number of points " << connectedPoints.size() << "; scale factor " << counter);
2869 PlaneNormal.Scale(1.0 / (double) counter);
2870 // LOG(1, "INFO: Calculated center of all circle points is " << center << ".");
2871 //
2872 // // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
2873 // PlaneNormal.CopyVector(Point->node);
2874 // PlaneNormal.SubtractVector(&center);
2875 // PlaneNormal.Normalize();
2876 LOG(1, "INFO: Calculated plane normal of circle is " << PlaneNormal << ".");
2877
2878 // construct one orthogonal vector
2879 if (!Reference.IsZero()) {
2880 AngleZero = (Reference) - (Point->getPosition());
2881 AngleZero.ProjectOntoPlane(PlaneNormal);
2882 }
2883 if ((Reference.IsZero()) || (AngleZero.NormSquared() < MYEPSILON )) {
2884 LOG(1, "Using alternatively " << (*SetOfNeighbours->begin())->getPosition() << " as angle 0 referencer.");
2885 AngleZero = ((*SetOfNeighbours->begin())->getPosition()) - (Point->getPosition());
2886 AngleZero.ProjectOntoPlane(PlaneNormal);
2887 if (AngleZero.NormSquared() < MYEPSILON) {
2888 ELOG(0, "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!");
2889 performCriticalExit();
2890 }
2891 }
2892 LOG(1, "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << ".");
2893 if (AngleZero.NormSquared() > MYEPSILON)
2894 OrthogonalVector = Plane(PlaneNormal, AngleZero,0).getNormal();
2895 else
2896 OrthogonalVector.MakeNormalTo(PlaneNormal);
2897 LOG(1, "INFO: OrthogonalVector on plane is " << OrthogonalVector << ".");
2898
2899 // go through all connected points and calculate angle
2900 pair<map<double, TesselPoint*>::iterator, bool> InserterTest;
2901 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
2902 helper = ((*listRunner)->getPosition()) - (Point->getPosition());
2903 helper.ProjectOntoPlane(PlaneNormal);
2904 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
2905 if (angle > M_PI) // the correction is of no use here (and not desired)
2906 angle = 2. * M_PI - angle;
2907 LOG(0, "INFO: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << ".");
2908 InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*> (angle, (*listRunner)));
2909 if (!InserterTest.second) {
2910 ELOG(0, "GetCircleOfSetOfPoints() got two atoms with same angle: " << *((InserterTest.first)->second) << " and " << (*listRunner));
2911 performCriticalExit();
2912 }
2913 }
2914
2915 for (map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
2916 connectedCircle->push_back(AngleRunner->second);
2917 }
2918
2919 return connectedCircle;
2920}
2921
2922/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
2923 *
2924 * @param *out output stream for debugging
2925 * @param *Point of which get all connected points
2926 * @return list of the all points linked to the provided one
2927 */
2928ListOfTesselPointList * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
2929{
2930 Info FunctionInfo(__func__);
2931 map<double, TesselPoint*> anglesOfPoints;
2932 list<TesselPointList *> *ListOfPaths = new list<TesselPointList *> ;
2933 TesselPointList *connectedPath = NULL;
2934 Vector center;
2935 Vector PlaneNormal;
2936 Vector AngleZero;
2937 Vector OrthogonalVector;
2938 Vector helper;
2939 class BoundaryPointSet *ReferencePoint = NULL;
2940 class BoundaryPointSet *CurrentPoint = NULL;
2941 class BoundaryTriangleSet *triangle = NULL;
2942 class BoundaryLineSet *CurrentLine = NULL;
2943 class BoundaryLineSet *StartLine = NULL;
2944 // find the respective boundary point
2945 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->getNr());
2946 if (PointRunner != PointsOnBoundary.end()) {
2947 ReferencePoint = PointRunner->second;
2948 } else {
2949 ELOG(1, "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << ".");
2950 return NULL;
2951 }
2952
2953 map<class BoundaryLineSet *, bool> TouchedLine;
2954 map<class BoundaryTriangleSet *, bool> TouchedTriangle;
2955 map<class BoundaryLineSet *, bool>::iterator LineRunner;
2956 map<class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
2957 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
2958 TouchedLine.insert(pair<class BoundaryLineSet *, bool> (Runner->second, false));
2959 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
2960 TouchedTriangle.insert(pair<class BoundaryTriangleSet *, bool> (Sprinter->second, false));
2961 }
2962 if (!ReferencePoint->lines.empty()) {
2963 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
2964 LineRunner = TouchedLine.find(runner->second);
2965 if (LineRunner == TouchedLine.end()) {
2966 ELOG(1, "I could not find " << *runner->second << " in the touched list.");
2967 } else if (!LineRunner->second) {
2968 LineRunner->second = true;
2969 connectedPath = new TesselPointList;
2970 triangle = NULL;
2971 CurrentLine = runner->second;
2972 StartLine = CurrentLine;
2973 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
2974 LOG(1, "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << ".");
2975 do {
2976 // push current one
2977 LOG(1, "INFO: Putting " << *CurrentPoint << " at end of path.");
2978 connectedPath->push_back(CurrentPoint->node);
2979
2980 // find next triangle
2981 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
2982 LOG(1, "INFO: Inspecting triangle " << *Runner->second << ".");
2983 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
2984 triangle = Runner->second;
2985 TriangleRunner = TouchedTriangle.find(triangle);
2986 if (TriangleRunner != TouchedTriangle.end()) {
2987 if (!TriangleRunner->second) {
2988 TriangleRunner->second = true;
2989 LOG(1, "INFO: Connecting triangle is " << *triangle << ".");
2990 break;
2991 } else {
2992 LOG(1, "INFO: Skipping " << *triangle << ", as we have already visited it.");
2993 triangle = NULL;
2994 }
2995 } else {
2996 ELOG(1, "I could not find " << *triangle << " in the touched list.");
2997 triangle = NULL;
2998 }
2999 }
3000 }
3001 if (triangle == NULL)
3002 break;
3003 // find next line
3004 for (int i = 0; i < 3; i++) {
3005 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
3006 CurrentLine = triangle->lines[i];
3007 LOG(1, "INFO: Connecting line is " << *CurrentLine << ".");
3008 break;
3009 }
3010 }
3011 LineRunner = TouchedLine.find(CurrentLine);
3012 if (LineRunner == TouchedLine.end())
3013 ELOG(1, "I could not find " << *CurrentLine << " in the touched list.");
3014 else
3015 LineRunner->second = true;
3016 // find next point
3017 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3018
3019 } while (CurrentLine != StartLine);
3020 // last point is missing, as it's on start line
3021 LOG(1, "INFO: Putting " << *CurrentPoint << " at end of path.");
3022 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
3023 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
3024
3025 ListOfPaths->push_back(connectedPath);
3026 } else {
3027 LOG(1, "INFO: Skipping " << *runner->second << ", as we have already visited it.");
3028 }
3029 }
3030 } else {
3031 ELOG(1, "There are no lines attached to " << *ReferencePoint << ".");
3032 }
3033
3034 return ListOfPaths;
3035}
3036
3037/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
3038 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
3039 * @param *out output stream for debugging
3040 * @param *Point of which get all connected points
3041 * @return list of the closed paths
3042 */
3043ListOfTesselPointList * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
3044{
3045 Info FunctionInfo(__func__);
3046 list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
3047 list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *> ;
3048 TesselPointList *connectedPath = NULL;
3049 TesselPointList *newPath = NULL;
3050 int count = 0;
3051 TesselPointList::iterator CircleRunner;
3052 TesselPointList::iterator CircleStart;
3053
3054 for (list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
3055 connectedPath = *ListRunner;
3056
3057 LOG(1, "INFO: Current path is " << connectedPath << ".");
3058
3059 // go through list, look for reappearance of starting Point and count
3060 CircleStart = connectedPath->begin();
3061 // go through list, look for reappearance of starting Point and create list
3062 TesselPointList::iterator Marker = CircleStart;
3063 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
3064 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
3065 // we have a closed circle from Marker to new Marker
3066 if (DoLog(1)) {
3067 std::stringstream output;
3068 output << count + 1 << ". closed path consists of: ";
3069 for (TesselPointList::iterator CircleSprinter = Marker;
3070 CircleSprinter != CircleRunner;
3071 CircleSprinter++)
3072 output << (**CircleSprinter) << " <-> ";
3073 LOG(1, output.str());
3074 }
3075 newPath = new TesselPointList;
3076 TesselPointList::iterator CircleSprinter = Marker;
3077 for (; CircleSprinter != CircleRunner; CircleSprinter++)
3078 newPath->push_back(*CircleSprinter);
3079 count++;
3080 Marker = CircleRunner;
3081
3082 // add to list
3083 ListofClosedPaths->push_back(newPath);
3084 }
3085 }
3086 }
3087 LOG(1, "INFO: " << count << " closed additional path(s) have been created.");
3088
3089 // delete list of paths
3090 while (!ListofPaths->empty()) {
3091 connectedPath = *(ListofPaths->begin());
3092 ListofPaths->remove(connectedPath);
3093 delete (connectedPath);
3094 }
3095 delete (ListofPaths);
3096
3097 // exit
3098 return ListofClosedPaths;
3099}
3100;
3101
3102/** Gets all belonging triangles for a given BoundaryPointSet.
3103 * \param *out output stream for debugging
3104 * \param *Point BoundaryPoint
3105 * \return pointer to allocated list of triangles
3106 */
3107TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
3108{
3109 Info FunctionInfo(__func__);
3110 TriangleSet *connectedTriangles = new TriangleSet;
3111
3112 if (Point == NULL) {
3113 ELOG(1, "Point given is NULL.");
3114 } else {
3115 // go through its lines and insert all triangles
3116 for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
3117 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
3118 connectedTriangles->insert(TriangleRunner->second);
3119 }
3120 }
3121
3122 return connectedTriangles;
3123}
3124;
3125
3126/** Removes a boundary point from the envelope while keeping it closed.
3127 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
3128 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
3129 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
3130 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
3131 * -# the surface is closed, when the path is empty
3132 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
3133 * \param *out output stream for debugging
3134 * \param *point point to be removed
3135 * \return volume added to the volume inside the tesselated surface by the removal
3136 */
3137double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point)
3138{
3139 class BoundaryLineSet *line = NULL;
3140 class BoundaryTriangleSet *triangle = NULL;
3141 Vector OldPoint, NormalVector;
3142 double volume = 0;
3143 int count = 0;
3144
3145 if (point == NULL) {
3146 ELOG(1, "Cannot remove the point " << point << ", it's NULL!");
3147 return 0.;
3148 } else
3149 LOG(0, "Removing point " << *point << " from tesselated boundary ...");
3150
3151 // copy old location for the volume
3152 OldPoint = (point->node->getPosition());
3153
3154 // get list of connected points
3155 if (point->lines.empty()) {
3156 ELOG(1, "Cannot remove the point " << *point << ", it's connected to no lines!");
3157 return 0.;
3158 }
3159
3160 list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
3161 TesselPointList *connectedPath = NULL;
3162
3163 // gather all triangles
3164 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3165 count += LineRunner->second->triangles.size();
3166 TriangleMap Candidates;
3167 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3168 line = LineRunner->second;
3169 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3170 triangle = TriangleRunner->second;
3171 Candidates.insert(TrianglePair(triangle->Nr, triangle));
3172 }
3173 }
3174
3175 // remove all triangles
3176 count = 0;
3177 NormalVector.Zero();
3178 for (TriangleMap::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3179 LOG(1, "INFO: Removing triangle " << *(Runner->second) << ".");
3180 NormalVector -= Runner->second->NormalVector; // has to point inward
3181 RemoveTesselationTriangle(Runner->second);
3182 count++;
3183 }
3184 LOG(1, count << " triangles were removed.");
3185
3186 list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
3187 list<TesselPointList *>::iterator ListRunner = ListAdvance;
3188 TriangleMap::iterator NumberRunner = Candidates.begin();
3189 TesselPointList::iterator StartNode, MiddleNode, EndNode;
3190 double angle;
3191 double smallestangle;
3192 Vector Point, Reference, OrthogonalVector;
3193 if (count > 2) { // less than three triangles, then nothing will be created
3194 class TesselPoint *TriangleCandidates[3];
3195 count = 0;
3196 for (; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3197 if (ListAdvance != ListOfClosedPaths->end())
3198 ListAdvance++;
3199
3200 connectedPath = *ListRunner;
3201 // re-create all triangles by going through connected points list
3202 LineList NewLines;
3203 for (; !connectedPath->empty();) {
3204 // search middle node with widest angle to next neighbours
3205 EndNode = connectedPath->end();
3206 smallestangle = 0.;
3207 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3208 LOG(1, "INFO: MiddleNode is " << **MiddleNode << ".");
3209 // construct vectors to next and previous neighbour
3210 StartNode = MiddleNode;
3211 if (StartNode == connectedPath->begin())
3212 StartNode = connectedPath->end();
3213 StartNode--;
3214 //LOG(3, "INFO: StartNode is " << **StartNode << ".");
3215 Point = ((*StartNode)->getPosition()) - ((*MiddleNode)->getPosition());
3216 StartNode = MiddleNode;
3217 StartNode++;
3218 if (StartNode == connectedPath->end())
3219 StartNode = connectedPath->begin();
3220 //LOG(3, "INFO: EndNode is " << **StartNode << ".");
3221 Reference = ((*StartNode)->getPosition()) - ((*MiddleNode)->getPosition());
3222 OrthogonalVector = ((*MiddleNode)->getPosition()) - OldPoint;
3223 OrthogonalVector.MakeNormalTo(Reference);
3224 angle = GetAngle(Point, Reference, OrthogonalVector);
3225 //if (angle < M_PI) // no wrong-sided triangles, please?
3226 if (fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3227 smallestangle = angle;
3228 EndNode = MiddleNode;
3229 }
3230 }
3231 MiddleNode = EndNode;
3232 if (MiddleNode == connectedPath->end()) {
3233 ELOG(0, "CRITICAL: Could not find a smallest angle!");
3234 performCriticalExit();
3235 }
3236 StartNode = MiddleNode;
3237 if (StartNode == connectedPath->begin())
3238 StartNode = connectedPath->end();
3239 StartNode--;
3240 EndNode++;
3241 if (EndNode == connectedPath->end())
3242 EndNode = connectedPath->begin();
3243 LOG(2, "INFO: StartNode is " << **StartNode << ".");
3244 LOG(2, "INFO: MiddleNode is " << **MiddleNode << ".");
3245 LOG(2, "INFO: EndNode is " << **EndNode << ".");
3246 LOG(1, "INFO: Attempting to create triangle " << (*StartNode)->getName() << ", " << (*MiddleNode)->getName() << " and " << (*EndNode)->getName() << ".");
3247 TriangleCandidates[0] = *StartNode;
3248 TriangleCandidates[1] = *MiddleNode;
3249 TriangleCandidates[2] = *EndNode;
3250 triangle = GetPresentTriangle(TriangleCandidates);
3251 if (triangle != NULL) {
3252 ELOG(0, "New triangle already present, skipping!");
3253 StartNode++;
3254 MiddleNode++;
3255 EndNode++;
3256 if (StartNode == connectedPath->end())
3257 StartNode = connectedPath->begin();
3258 if (MiddleNode == connectedPath->end())
3259 MiddleNode = connectedPath->begin();
3260 if (EndNode == connectedPath->end())
3261 EndNode = connectedPath->begin();
3262 continue;
3263 }
3264 LOG(3, "Adding new triangle points.");
3265 AddTesselationPoint(*StartNode, 0);
3266 AddTesselationPoint(*MiddleNode, 1);
3267 AddTesselationPoint(*EndNode, 2);
3268 LOG(3, "Adding new triangle lines.");
3269 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
3270 AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
3271 NewLines.push_back(BLS[1]);
3272 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
3273 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3274 BTS->GetNormalVector(NormalVector);
3275 AddTesselationTriangle();
3276 // calculate volume summand as a general tetraeder
3277 volume += CalculateVolumeofGeneralTetraeder(TPS[0]->node->getPosition(), TPS[1]->node->getPosition(), TPS[2]->node->getPosition(), OldPoint);
3278 // advance number
3279 count++;
3280
3281 // prepare nodes for next triangle
3282 StartNode = EndNode;
3283 LOG(2, "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << ".");
3284 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3285 if (connectedPath->size() == 2) { // we are done
3286 connectedPath->remove(*StartNode); // remove the start node
3287 connectedPath->remove(*EndNode); // remove the end node
3288 break;
3289 } else if (connectedPath->size() < 2) { // something's gone wrong!
3290 ELOG(0, "CRITICAL: There are only two endpoints left!");
3291 performCriticalExit();
3292 } else {
3293 MiddleNode = StartNode;
3294 MiddleNode++;
3295 if (MiddleNode == connectedPath->end())
3296 MiddleNode = connectedPath->begin();
3297 EndNode = MiddleNode;
3298 EndNode++;
3299 if (EndNode == connectedPath->end())
3300 EndNode = connectedPath->begin();
3301 }
3302 }
3303 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
3304 if (NewLines.size() > 1) {
3305 LineList::iterator Candidate;
3306 class BoundaryLineSet *OtherBase = NULL;
3307 double tmp, maxgain;
3308 do {
3309 maxgain = 0;
3310 for (LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
3311 tmp = PickFarthestofTwoBaselines(*Runner);
3312 if (maxgain < tmp) {
3313 maxgain = tmp;
3314 Candidate = Runner;
3315 }
3316 }
3317 if (maxgain != 0) {
3318 volume += maxgain;
3319 LOG(1, "Flipping baseline with highest volume" << **Candidate << ".");
3320 OtherBase = FlipBaseline(*Candidate);
3321 NewLines.erase(Candidate);
3322 NewLines.push_back(OtherBase);
3323 }
3324 } while (maxgain != 0.);
3325 }
3326
3327 ListOfClosedPaths->remove(connectedPath);
3328 delete (connectedPath);
3329 }
3330 LOG(0, count << " triangles were created.");
3331 } else {
3332 while (!ListOfClosedPaths->empty()) {
3333 ListRunner = ListOfClosedPaths->begin();
3334 connectedPath = *ListRunner;
3335 ListOfClosedPaths->remove(connectedPath);
3336 delete (connectedPath);
3337 }
3338 LOG(0, "No need to create any triangles.");
3339 }
3340 delete (ListOfClosedPaths);
3341
3342 LOG(0, "Removed volume is " << volume << ".");
3343
3344 return volume;
3345}
3346;
3347
3348/**
3349 * Finds triangles belonging to the three provided points.
3350 *
3351 * @param *Points[3] list, is expected to contain three points (NULL means wildcard)
3352 *
3353 * @return triangles which belong to the provided points, will be empty if there are none,
3354 * will usually be one, in case of degeneration, there will be two
3355 */
3356TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
3357{
3358 Info FunctionInfo(__func__);
3359 TriangleList *result = new TriangleList;
3360 LineMap::const_iterator FindLine;
3361 TriangleMap::const_iterator FindTriangle;
3362 class BoundaryPointSet *TrianglePoints[3];
3363 size_t NoOfWildcards = 0;
3364
3365 for (int i = 0; i < 3; i++) {
3366 if (Points[i] == NULL) {
3367 NoOfWildcards++;
3368 TrianglePoints[i] = NULL;
3369 } else {
3370 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->getNr());
3371 if (FindPoint != PointsOnBoundary.end()) {
3372 TrianglePoints[i] = FindPoint->second;
3373 } else {
3374 TrianglePoints[i] = NULL;
3375 }
3376 }
3377 }
3378
3379 switch (NoOfWildcards) {
3380 case 0: // checks lines between the points in the Points for their adjacent triangles
3381 for (int i = 0; i < 3; i++) {
3382 if (TrianglePoints[i] != NULL) {
3383 for (int j = i + 1; j < 3; j++) {
3384 if (TrianglePoints[j] != NULL) {
3385 for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->getNr()); // is a multimap!
3386 (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->getNr()); FindLine++) {
3387 for (FindTriangle = FindLine->second->triangles.begin(); FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
3388 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3389 result->push_back(FindTriangle->second);
3390 }
3391 }
3392 }
3393 // Is it sufficient to consider one of the triangle lines for this.
3394 return result;
3395 }
3396 }
3397 }
3398 }
3399 break;
3400 case 1: // copy all triangles of the respective line
3401 {
3402 int i = 0;
3403 for (; i < 3; i++)
3404 if (TrianglePoints[i] == NULL)
3405 break;
3406 for (FindLine = TrianglePoints[(i + 1) % 3]->lines.find(TrianglePoints[(i + 2) % 3]->node->getNr()); // is a multimap!
3407 (FindLine != TrianglePoints[(i + 1) % 3]->lines.end()) && (FindLine->first == TrianglePoints[(i + 2) % 3]->node->getNr()); FindLine++) {
3408 for (FindTriangle = FindLine->second->triangles.begin(); FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
3409 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3410 result->push_back(FindTriangle->second);
3411 }
3412 }
3413 }
3414 break;
3415 }
3416 case 2: // copy all triangles of the respective point
3417 {
3418 int i = 0;
3419 for (; i < 3; i++)
3420 if (TrianglePoints[i] != NULL)
3421 break;
3422 for (LineMap::const_iterator line = TrianglePoints[i]->lines.begin(); line != TrianglePoints[i]->lines.end(); line++)
3423 for (TriangleMap::const_iterator triangle = line->second->triangles.begin(); triangle != line->second->triangles.end(); triangle++)
3424 result->push_back(triangle->second);
3425 result->sort();
3426 result->unique();
3427 break;
3428 }
3429 case 3: // copy all triangles
3430 {
3431 for (TriangleMap::const_iterator triangle = TrianglesOnBoundary.begin(); triangle != TrianglesOnBoundary.end(); triangle++)
3432 result->push_back(triangle->second);
3433 break;
3434 }
3435 default:
3436 ELOG(0, "Number of wildcards is greater than 3, cannot happen!");
3437 performCriticalExit();
3438 break;
3439 }
3440
3441 return result;
3442}
3443
3444struct BoundaryLineSetCompare
3445{
3446 bool operator()(const BoundaryLineSet * const a, const BoundaryLineSet * const b)
3447 {
3448 int lowerNra = -1;
3449 int lowerNrb = -1;
3450
3451 if (a->endpoints[0] < a->endpoints[1])
3452 lowerNra = 0;
3453 else
3454 lowerNra = 1;
3455
3456 if (b->endpoints[0] < b->endpoints[1])
3457 lowerNrb = 0;
3458 else
3459 lowerNrb = 1;
3460
3461 if (a->endpoints[lowerNra] < b->endpoints[lowerNrb])
3462 return true;
3463 else if (a->endpoints[lowerNra] > b->endpoints[lowerNrb])
3464 return false;
3465 else { // both lower-numbered endpoints are the same ...
3466 if (a->endpoints[(lowerNra + 1) % 2] < b->endpoints[(lowerNrb + 1) % 2])
3467 return true;
3468 else if (a->endpoints[(lowerNra + 1) % 2] > b->endpoints[(lowerNrb + 1) % 2])
3469 return false;
3470 }
3471 return false;
3472 }
3473 ;
3474};
3475
3476#define UniqueLines set < class BoundaryLineSet *, BoundaryLineSetCompare>
3477
3478/**
3479 * Finds all degenerated lines within the tesselation structure.
3480 *
3481 * @return map of keys of degenerated line pairs, each line occurs twice
3482 * in the list, once as key and once as value
3483 */
3484IndexToIndex * Tesselation::FindAllDegeneratedLines()
3485{
3486 Info FunctionInfo(__func__);
3487 UniqueLines AllLines;
3488 IndexToIndex * DegeneratedLines = new IndexToIndex;
3489
3490 // sanity check
3491 if (LinesOnBoundary.empty()) {
3492 ELOG(2, "FindAllDegeneratedTriangles() was called without any tesselation structure.");
3493 return DegeneratedLines;
3494 }
3495 LineMap::iterator LineRunner1;
3496 pair<UniqueLines::iterator, bool> tester;
3497 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
3498 tester = AllLines.insert(LineRunner1->second);
3499 if (!tester.second) { // found degenerated line
3500 DegeneratedLines->insert(pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr));
3501 DegeneratedLines->insert(pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr));
3502 }
3503 }
3504
3505 AllLines.clear();
3506
3507 LOG(0, "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines.");
3508 IndexToIndex::iterator it;
3509 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
3510 const LineMap::const_iterator Line1 = LinesOnBoundary.find((*it).first);
3511 const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
3512 if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
3513 LOG(0, *Line1->second << " => " << *Line2->second);
3514 else
3515 ELOG(1, "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!");
3516 }
3517
3518 return DegeneratedLines;
3519}
3520
3521/**
3522 * Finds all degenerated triangles within the tesselation structure.
3523 *
3524 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
3525 * in the list, once as key and once as value
3526 */
3527IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
3528{
3529 Info FunctionInfo(__func__);
3530 IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
3531 IndexToIndex * DegeneratedTriangles = new IndexToIndex;
3532 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
3533 LineMap::iterator Liner;
3534 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
3535
3536 for (IndexToIndex::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
3537 // run over both lines' triangles
3538 Liner = LinesOnBoundary.find(LineRunner->first);
3539 if (Liner != LinesOnBoundary.end())
3540 line1 = Liner->second;
3541 Liner = LinesOnBoundary.find(LineRunner->second);
3542 if (Liner != LinesOnBoundary.end())
3543 line2 = Liner->second;
3544 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
3545 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
3546 if ((TriangleRunner1->second != TriangleRunner2->second) && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
3547 DegeneratedTriangles->insert(pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr));
3548 DegeneratedTriangles->insert(pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr));
3549 }
3550 }
3551 }
3552 }
3553 delete (DegeneratedLines);
3554
3555 LOG(0, "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:");
3556 for (IndexToIndex::iterator it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
3557 LOG(0, (*it).first << " => " << (*it).second);
3558
3559 return DegeneratedTriangles;
3560}
3561
3562/**
3563 * Purges degenerated triangles from the tesselation structure if they are not
3564 * necessary to keep a single point within the structure.
3565 */
3566void Tesselation::RemoveDegeneratedTriangles()
3567{
3568 Info FunctionInfo(__func__);
3569 IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
3570 TriangleMap::iterator finder;
3571 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
3572 int count = 0;
3573
3574 // iterate over all degenerated triangles
3575 for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin(); !DegeneratedTriangles->empty(); TriangleKeyRunner = DegeneratedTriangles->begin()) {
3576 LOG(0, "Checking presence of triangles " << TriangleKeyRunner->first << " and " << TriangleKeyRunner->second << ".");
3577 // both ways are stored in the map, only use one
3578 if (TriangleKeyRunner->first > TriangleKeyRunner->second)
3579 continue;
3580
3581 // determine from the keys in the map the two _present_ triangles
3582 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
3583 if (finder != TrianglesOnBoundary.end())
3584 triangle = finder->second;
3585 else
3586 continue;
3587 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
3588 if (finder != TrianglesOnBoundary.end())
3589 partnerTriangle = finder->second;
3590 else
3591 continue;
3592
3593 // determine which lines are shared by the two triangles
3594 bool trianglesShareLine = false;
3595 for (int i = 0; i < 3; ++i)
3596 for (int j = 0; j < 3; ++j)
3597 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
3598
3599 if (trianglesShareLine && (triangle->endpoints[1]->LinesCount > 2) && (triangle->endpoints[2]->LinesCount > 2) && (triangle->endpoints[0]->LinesCount > 2)) {
3600 // check whether we have to fix lines
3601 BoundaryTriangleSet *Othertriangle = NULL;
3602 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
3603 TriangleMap::iterator TriangleRunner;
3604 for (int i = 0; i < 3; ++i)
3605 for (int j = 0; j < 3; ++j)
3606 if (triangle->lines[i] != partnerTriangle->lines[j]) {
3607 // get the other two triangles
3608 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
3609 if (TriangleRunner->second != triangle) {
3610 Othertriangle = TriangleRunner->second;
3611 }
3612 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
3613 if (TriangleRunner->second != partnerTriangle) {
3614 OtherpartnerTriangle = TriangleRunner->second;
3615 }
3616 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
3617 // the line of triangle receives the degenerated ones
3618 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
3619 triangle->lines[i]->triangles.insert(TrianglePair(partnerTriangle->Nr, partnerTriangle));
3620 for (int k = 0; k < 3; k++)
3621 if (triangle->lines[i] == Othertriangle->lines[k]) {
3622 Othertriangle->lines[k] = partnerTriangle->lines[j];
3623 break;
3624 }
3625 // the line of partnerTriangle receives the non-degenerated ones
3626 partnerTriangle->lines[j]->triangles.erase(partnerTriangle->Nr);
3627 partnerTriangle->lines[j]->triangles.insert(TrianglePair(Othertriangle->Nr, Othertriangle));
3628 partnerTriangle->lines[j] = triangle->lines[i];
3629 }
3630
3631 // erase the pair
3632 count += (int) DegeneratedTriangles->erase(triangle->Nr);
3633 LOG(0, "RemoveDegeneratedTriangles() removes triangle " << *triangle << ".");
3634 RemoveTesselationTriangle(triangle);
3635 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
3636 LOG(0, "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << ".");
3637 RemoveTesselationTriangle(partnerTriangle);
3638 } else {
3639 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.");
3640 }
3641 }
3642 delete (DegeneratedTriangles);
3643 if (count > 0)
3644 LastTriangle = NULL;
3645
3646 LOG(0, "RemoveDegeneratedTriangles() removed " << count << " triangles:");
3647}
3648
3649/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
3650 * We look for the closest point on the boundary, we look through its connected boundary lines and
3651 * seek the one with the minimum angle between its center point and the new point and this base line.
3652 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
3653 * \param *out output stream for debugging
3654 * \param *point point to add
3655 * \param *LC Linked Cell structure to find nearest point
3656 */
3657void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell_deprecated *LC)
3658{
3659 Info FunctionInfo(__func__);
3660 // find nearest boundary point
3661 class TesselPoint *BackupPoint = NULL;
3662 class TesselPoint *NearestPoint = FindClosestTesselPoint(point->getPosition(), BackupPoint, LC);
3663 class BoundaryPointSet *NearestBoundaryPoint = NULL;
3664 PointMap::iterator PointRunner;
3665
3666 if (NearestPoint == point)
3667 NearestPoint = BackupPoint;
3668 PointRunner = PointsOnBoundary.find(NearestPoint->getNr());
3669 if (PointRunner != PointsOnBoundary.end()) {
3670 NearestBoundaryPoint = PointRunner->second;
3671 } else {
3672 ELOG(1, "I cannot find the boundary point.");
3673 return;
3674 }
3675 LOG(0, "Nearest point on boundary is " << NearestPoint->getName() << ".");
3676
3677 // go through its lines and find the best one to split
3678 Vector CenterToPoint;
3679 Vector BaseLine;
3680 double angle, BestAngle = 0.;
3681 class BoundaryLineSet *BestLine = NULL;
3682 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
3683 BaseLine = (Runner->second->endpoints[0]->node->getPosition()) -
3684 (Runner->second->endpoints[1]->node->getPosition());
3685 CenterToPoint = 0.5 * ((Runner->second->endpoints[0]->node->getPosition()) +
3686 (Runner->second->endpoints[1]->node->getPosition()));
3687 CenterToPoint -= (point->getPosition());
3688 angle = CenterToPoint.Angle(BaseLine);
3689 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
3690 BestAngle = angle;
3691 BestLine = Runner->second;
3692 }
3693 }
3694
3695 // remove one triangle from the chosen line
3696 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
3697 BestLine->triangles.erase(TempTriangle->Nr);
3698 int nr = -1;
3699 for (int i = 0; i < 3; i++) {
3700 if (TempTriangle->lines[i] == BestLine) {
3701 nr = i;
3702 break;
3703 }
3704 }
3705
3706 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
3707 LOG(2, "Adding new triangle points.");
3708 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3709 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3710 AddTesselationPoint(point, 2);
3711 LOG(2, "Adding new triangle lines.");
3712 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
3713 AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
3714 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
3715 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3716 BTS->GetNormalVector(TempTriangle->NormalVector);
3717 BTS->NormalVector.Scale(-1.);
3718 LOG(1, "INFO: NormalVector of new triangle is " << BTS->NormalVector << ".");
3719 AddTesselationTriangle();
3720
3721 // create other side of this triangle and close both new sides of the first created triangle
3722 LOG(2, "Adding new triangle points.");
3723 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3724 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3725 AddTesselationPoint(point, 2);
3726 LOG(2, "Adding new triangle lines.");
3727 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
3728 AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
3729 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
3730 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3731 BTS->GetNormalVector(TempTriangle->NormalVector);
3732 LOG(1, "INFO: NormalVector of other new triangle is " << BTS->NormalVector << ".");
3733 AddTesselationTriangle();
3734
3735 // add removed triangle to the last open line of the second triangle
3736 for (int i = 0; i < 3; i++) { // look for the same line as BestLine (only it's its degenerated companion)
3737 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
3738 if (BestLine == BTS->lines[i]) {
3739 ELOG(0, "BestLine is same as found line, something's wrong here!");
3740 performCriticalExit();
3741 }
3742 BTS->lines[i]->triangles.insert(pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle));
3743 TempTriangle->lines[nr] = BTS->lines[i];
3744 break;
3745 }
3746 }
3747}
3748;
3749
3750/** Writes the envelope to file.
3751 * \param *out otuput stream for debugging
3752 * \param *filename basename of output file
3753 * \param *cloud IPointCloud structure with all nodes
3754 */
3755void Tesselation::Output(const char *filename, IPointCloud & cloud)
3756{
3757 Info FunctionInfo(__func__);
3758 ofstream *tempstream = NULL;
3759 string NameofTempFile;
3760 string NumberName;
3761
3762 if (LastTriangle != NULL) {
3763 stringstream sstr;
3764 sstr << "-"<< TrianglesOnBoundary.size() << "-" << LastTriangle->getEndpointName(0) << "_" << LastTriangle->getEndpointName(1) << "_" << LastTriangle->getEndpointName(2);
3765 NumberName = sstr.str();
3766 if (DoTecplotOutput) {
3767 string NameofTempFile(filename);
3768 NameofTempFile.append(NumberName);
3769 for (size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3770 NameofTempFile.erase(npos, 1);
3771 NameofTempFile.append(TecplotSuffix);
3772 LOG(1, "INFO: Writing temporary non convex hull to file " << NameofTempFile << ".");
3773 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3774 WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
3775 tempstream->close();
3776 tempstream->flush();
3777 delete (tempstream);
3778 }
3779
3780 if (DoRaster3DOutput) {
3781 string NameofTempFile(filename);
3782 NameofTempFile.append(NumberName);
3783 for (size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3784 NameofTempFile.erase(npos, 1);
3785 NameofTempFile.append(Raster3DSuffix);
3786 LOG(1, "INFO: Writing temporary non convex hull to file " << NameofTempFile << ".");
3787 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3788 WriteRaster3dFile(tempstream, this, cloud);
3789 IncludeSphereinRaster3D(tempstream, this, cloud);
3790 tempstream->close();
3791 tempstream->flush();
3792 delete (tempstream);
3793 }
3794 }
3795 if (DoTecplotOutput || DoRaster3DOutput)
3796 TriangleFilesWritten++;
3797}
3798;
3799
3800struct BoundaryPolygonSetCompare
3801{
3802 bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const
3803 {
3804 if (s1->endpoints.size() < s2->endpoints.size())
3805 return true;
3806 else if (s1->endpoints.size() > s2->endpoints.size())
3807 return false;
3808 else { // equality of number of endpoints
3809 PointSet::const_iterator Walker1 = s1->endpoints.begin();
3810 PointSet::const_iterator Walker2 = s2->endpoints.begin();
3811 while ((Walker1 != s1->endpoints.end()) || (Walker2 != s2->endpoints.end())) {
3812 if ((*Walker1)->Nr < (*Walker2)->Nr)
3813 return true;
3814 else if ((*Walker1)->Nr > (*Walker2)->Nr)
3815 return false;
3816 Walker1++;
3817 Walker2++;
3818 }
3819 return false;
3820 }
3821 }
3822};
3823
3824#define UniquePolygonSet set < BoundaryPolygonSet *, BoundaryPolygonSetCompare>
3825
3826/** Finds all degenerated polygons and calls ReTesselateDegeneratedPolygon()/
3827 * \return number of polygons found
3828 */
3829int Tesselation::CorrectAllDegeneratedPolygons()
3830{
3831 Info FunctionInfo(__func__);
3832 /// 2. Go through all BoundaryPointSet's, check their triangles' NormalVector
3833 IndexToIndex *DegeneratedTriangles = FindAllDegeneratedTriangles();
3834 set<BoundaryPointSet *> EndpointCandidateList;
3835 pair<set<BoundaryPointSet *>::iterator, bool> InsertionTester;
3836 pair<map<int, Vector *>::iterator, bool> TriangleInsertionTester;
3837 for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
3838 LOG(0, "Current point is " << *Runner->second << ".");
3839 map<int, Vector *> TriangleVectors;
3840 // gather all NormalVectors
3841 LOG(1, "Gathering triangles ...");
3842 for (LineMap::const_iterator LineRunner = (Runner->second)->lines.begin(); LineRunner != (Runner->second)->lines.end(); LineRunner++)
3843 for (TriangleMap::const_iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
3844 if (DegeneratedTriangles->find(TriangleRunner->second->Nr) == DegeneratedTriangles->end()) {
3845 TriangleInsertionTester = TriangleVectors.insert(pair<int, Vector *> ((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)));
3846 if (TriangleInsertionTester.second)
3847 LOG(1, " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list.");
3848 } else {
3849 LOG(1, " NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one.");
3850 }
3851 }
3852 // check whether there are two that are parallel
3853 LOG(1, "Finding two parallel triangles ...");
3854 for (map<int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
3855 for (map<int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
3856 if (VectorWalker != VectorRunner) { // skip equals
3857 const double SCP = VectorWalker->second->ScalarProduct(*VectorRunner->second); // ScalarProduct should result in -1. for degenerated triangles
3858 LOG(1, "Checking " << *VectorWalker->second << " against " << *VectorRunner->second << ": " << SCP);
3859 if (fabs(SCP + 1.) < ParallelEpsilon) {
3860 InsertionTester = EndpointCandidateList.insert((Runner->second));
3861 if (InsertionTester.second)
3862 LOG(0, " Adding " << *Runner->second << " to endpoint candidate list.");
3863 // and break out of both loops
3864 VectorWalker = TriangleVectors.end();
3865 VectorRunner = TriangleVectors.end();
3866 break;
3867 }
3868 }
3869 }
3870 delete DegeneratedTriangles;
3871
3872 /// 3. Find connected endpoint candidates and put them into a polygon
3873 UniquePolygonSet ListofDegeneratedPolygons;
3874 BoundaryPointSet *Walker = NULL;
3875 BoundaryPointSet *OtherWalker = NULL;
3876 BoundaryPolygonSet *Current = NULL;
3877 stack<BoundaryPointSet*> ToCheckConnecteds;
3878 while (!EndpointCandidateList.empty()) {
3879 Walker = *(EndpointCandidateList.begin());
3880 if (Current == NULL) { // create a new polygon with current candidate
3881 LOG(0, "Starting new polygon set at point " << *Walker);
3882 Current = new BoundaryPolygonSet;
3883 Current->endpoints.insert(Walker);
3884 EndpointCandidateList.erase(Walker);
3885 ToCheckConnecteds.push(Walker);
3886 }
3887
3888 // go through to-check stack
3889 while (!ToCheckConnecteds.empty()) {
3890 Walker = ToCheckConnecteds.top(); // fetch ...
3891 ToCheckConnecteds.pop(); // ... and remove
3892 for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
3893 OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
3894 LOG(1, "Checking " << *OtherWalker);
3895 set<BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
3896 if (Finder != EndpointCandidateList.end()) { // found a connected partner
3897 LOG(1, " Adding to polygon.");
3898 Current->endpoints.insert(OtherWalker);
3899 EndpointCandidateList.erase(Finder); // remove from candidates
3900 ToCheckConnecteds.push(OtherWalker); // but check its partners too
3901 } else {
3902 LOG(1, " is not connected to " << *Walker);
3903 }
3904 }
3905 }
3906
3907 LOG(0, "Final polygon is " << *Current);
3908 ListofDegeneratedPolygons.insert(Current);
3909 Current = NULL;
3910 }
3911
3912 const int counter = ListofDegeneratedPolygons.size();
3913
3914 if (DoLog(0)) {
3915 std::stringstream output;
3916 output << "The following " << counter << " degenerated polygons have been found: ";
3917 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
3918 output << " " << **PolygonRunner;
3919 LOG(0, output.str());
3920 }
3921
3922 /// 4. Go through all these degenerated polygons
3923 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++) {
3924 stack<int> TriangleNrs;
3925 Vector NormalVector;
3926 /// 4a. Gather all triangles of this polygon
3927 TriangleSet *T = (*PolygonRunner)->GetAllContainedTrianglesFromEndpoints();
3928
3929 // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
3930 if (T->size() == 2) {
3931 LOG(1, " Skipping degenerated polygon, is just a (already simply degenerated) triangle.");
3932 delete (T);
3933 continue;
3934 }
3935
3936 // check whether number is even
3937 // If this case occurs, we have to think about it!
3938 // The Problem is probably due to two degenerated polygons being connected by a bridging, non-degenerated polygon, as somehow one node has
3939 // connections to either polygon ...
3940 if (T->size() % 2 != 0) {
3941 ELOG(0, " degenerated polygon contains an odd number of triangles, probably contains bridging non-degenerated ones, too!");
3942 performCriticalExit();
3943 }
3944 TriangleSet::iterator TriangleWalker = T->begin(); // is the inner iterator
3945 /// 4a. Get NormalVector for one side (this is "front")
3946 NormalVector = (*TriangleWalker)->NormalVector;
3947 LOG(1, "\"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector);
3948 TriangleWalker++;
3949 TriangleSet::iterator TriangleSprinter = TriangleWalker; // is the inner advanced iterator
3950 /// 4b. Remove all triangles whose NormalVector is in opposite direction (i.e. "back")
3951 BoundaryTriangleSet *triangle = NULL;
3952 while (TriangleSprinter != T->end()) {
3953 TriangleWalker = TriangleSprinter;
3954 triangle = *TriangleWalker;
3955 TriangleSprinter++;
3956 LOG(1, "Current triangle to test for removal: " << *triangle);
3957 if (triangle->NormalVector.ScalarProduct(NormalVector) < 0) { // if from other side, then delete and remove from list
3958 LOG(1, " Removing ... ");
3959 TriangleNrs.push(triangle->Nr);
3960 T->erase(TriangleWalker);
3961 RemoveTesselationTriangle(triangle);
3962 } else
3963 LOG(1, " Keeping ... ");
3964 }
3965 /// 4c. Copy all "front" triangles but with inverse NormalVector
3966 TriangleWalker = T->begin();
3967 while (TriangleWalker != T->end()) { // go through all front triangles
3968 LOG(1, " Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector);
3969 for (int i = 0; i < 3; i++)
3970 AddTesselationPoint((*TriangleWalker)->endpoints[i]->node, i);
3971 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
3972 AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
3973 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
3974 if (TriangleNrs.empty())
3975 ELOG(0, "No more free triangle numbers!");
3976 BTS = new BoundaryTriangleSet(BLS, TriangleNrs.top()); // copy triangle ...
3977 AddTesselationTriangle(); // ... and add
3978 TriangleNrs.pop();
3979 BTS->NormalVector = -1 * (*TriangleWalker)->NormalVector;
3980 TriangleWalker++;
3981 }
3982 if (!TriangleNrs.empty()) {
3983 ELOG(0, "There have been less triangles created than removed!");
3984 }
3985 delete (T); // remove the triangleset
3986 }
3987 IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
3988 LOG(0, "Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:");
3989 IndexToIndex::iterator it;
3990 for (it = SimplyDegeneratedTriangles->begin(); it != SimplyDegeneratedTriangles->end(); it++)
3991 LOG(0, (*it).first << " => " << (*it).second);
3992 delete (SimplyDegeneratedTriangles);
3993 /// 5. exit
3994 UniquePolygonSet::iterator PolygonRunner;
3995 while (!ListofDegeneratedPolygons.empty()) {
3996 PolygonRunner = ListofDegeneratedPolygons.begin();
3997 delete (*PolygonRunner);
3998 ListofDegeneratedPolygons.erase(PolygonRunner);
3999 }
4000
4001 return counter;
4002}
4003;
Note: See TracBrowser for help on using the repository browser.