source: src/Tesselation/tesselation.cpp@ b9d387

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

Added check whether all points remain inside surface and whether it is convex to ConvexEnvelopeAction.

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