source: src/Tesselation/tesselation.cpp@ 11d433

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 11d433 was 052c10, checked in by Frederik Heber <heber@…>, 11 years ago

MEMFIX: Tesselation::operator() did not free linkedlist.

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