source: src/Tesselation/tesselation.cpp@ c2c786

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

FIX: RemovePointFromTesselatedSurface() used Start,Middle,EndNode confusingly.

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