source: src/Tesselation/tesselation.cpp@ 95cfac

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

FIX: GLMoleculeObject_shape might use empty point list for tesselation.

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