source: src/Tesselation/tesselation.cpp@ a2a2f7

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

Huge warning fix.

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