source: src/Tesselation/tesselation.cpp@ 27888f

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

Using Normals from tesselated surface instead of from Shapes.

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