source: src/Tesselation/tesselation.cpp@ bb86bd

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

FIX: AddTesselationLine() would only work in initial tesselation phase.

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