source: src/Tesselation/tesselation.cpp@ 052c10

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

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

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