source: src/Tesselation/tesselation.cpp@ 054d47

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 054d47 was 7f1b51, checked in by Frederik Heber <heber@…>, 11 years ago

Merge branch 'GUI_Fixes' into stable

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