source: src/Tesselation/tesselation.cpp@ d127c8

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

Moved modules related to Tesselation into own source subfolder.

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