source: src/Tesselation/BoundaryTriangleSet.cpp@ f6ad4d

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

Added getArea() function to BoundaryTriangleSet.

  • Property mode set to 100644
File size: 17.1 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * BoundaryTriangleSet.cpp
10 *
11 * Created on: Jul 29, 2010
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 "BoundaryTriangleSet.hpp"
23
24#include <iostream>
25
26#include "BoundaryLineSet.hpp"
27#include "BoundaryPointSet.hpp"
28#include "Atom/TesselPoint.hpp"
29
30#include "Helpers/defs.hpp"
31
32#include "CodePatterns/Assert.hpp"
33#include "CodePatterns/Info.hpp"
34#include "CodePatterns/Log.hpp"
35#include "CodePatterns/Verbose.hpp"
36#include "LinearAlgebra/Exceptions.hpp"
37#include "LinearAlgebra/Line.hpp"
38#include "LinearAlgebra/Plane.hpp"
39#include "LinearAlgebra/Vector.hpp"
40
41using namespace std;
42
43/** Constructor for BoundaryTriangleSet.
44 */
45BoundaryTriangleSet::BoundaryTriangleSet() :
46 Nr(-1)
47{
48 Info FunctionInfo(__func__);
49 for (int i = 0; i < 3; i++) {
50 endpoints[i] = NULL;
51 lines[i] = NULL;
52 }
53}
54;
55
56/** Constructor for BoundaryTriangleSet with three lines.
57 * \param *line[3] lines that make up the triangle
58 * \param number number of triangle
59 */
60BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet * const line[3], const int number) :
61 Nr(number)
62{
63 Info FunctionInfo(__func__);
64 // set number
65 // set lines
66 for (int i = 0; i < 3; i++) {
67 lines[i] = line[i];
68 lines[i]->AddTriangle(this);
69 }
70 // get ascending order of endpoints
71 PointMap OrderMap;
72 for (int i = 0; i < 3; i++) {
73 // for all three lines
74 for (int j = 0; j < 2; j++) { // for both endpoints
75 OrderMap.insert(pair<int, class BoundaryPointSet *> (line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
76 // and we don't care whether insertion fails
77 }
78 }
79 // set endpoints
80 int Counter = 0;
81 LOG(0, "New triangle " << Nr << " with end points: ");
82 for (PointMap::iterator runner = OrderMap.begin(); runner != OrderMap.end(); runner++) {
83 endpoints[Counter] = runner->second;
84 LOG(0, " " << *endpoints[Counter]);
85 Counter++;
86 }
87 ASSERT(Counter >= 3,"We have a triangle with only two distinct endpoints!");
88};
89
90
91/** Destructor of BoundaryTriangleSet.
92 * Removes itself from each of its lines' LineMap and removes them if necessary.
93 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
94 */
95BoundaryTriangleSet::~BoundaryTriangleSet()
96{
97 Info FunctionInfo(__func__);
98 for (int i = 0; i < 3; i++) {
99 if (lines[i] != NULL) {
100 if (lines[i]->triangles.erase(Nr)) {
101 //LOG(0, "Triangle Nr." << Nr << " erased in line " << *lines[i] << ".");
102 }
103 if (lines[i]->triangles.empty()) {
104 //LOG(0, *lines[i] << " is no more attached to any triangle, erasing.");
105 delete (lines[i]);
106 lines[i] = NULL;
107 }
108 }
109 }
110 //LOG(0, "Erasing triangle Nr." << Nr << " itself.");
111}
112;
113
114/** Calculates the area of this triangle.
115 *
116 * @return surface area in between the tree points of this triangle
117 */
118double BoundaryTriangleSet::getArea() const
119{
120 Vector x;
121 Vector y;
122 x = getEndpoint(0) - getEndpoint(1);
123 y = getEndpoint(0) - getEndpoint(2);
124 const double a = x.Norm();
125 const double b = y.Norm();
126 const double c = getEndpoint(2).distance(getEndpoint(1));
127 const double area = sqrt(((a + b + c) * (a + b + c) - 2 * (a * a + b * b + c * c)) / 16.); // area of tesselated triangle
128 return area;
129}
130
131/** Calculates the normal vector for this triangle.
132 * Is made unique by comparison with \a OtherVector to point in the other direction.
133 * \param &OtherVector direction vector to make normal vector unique.
134 */
135void BoundaryTriangleSet::GetNormalVector(const Vector &OtherVector)
136{
137 Info FunctionInfo(__func__);
138 // get normal vector
139 NormalVector = Plane((endpoints[0]->node->getPosition()),
140 (endpoints[1]->node->getPosition()),
141 (endpoints[2]->node->getPosition())).getNormal();
142
143 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
144 if (NormalVector.ScalarProduct(OtherVector) > 0.)
145 NormalVector.Scale(-1.);
146 LOG(1, "Normal Vector is " << NormalVector << ".");
147}
148;
149
150/** Finds the point on the triangle \a *BTS through which the line defined by \a *MolCenter and \a *x crosses.
151 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
152 * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
153 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
154 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
155 * the first two basepoints) or not.
156 * \param *out output stream for debugging
157 * \param &MolCenter offset vector of line
158 * \param &x second endpoint of line, minus \a *MolCenter is directional vector of line
159 * \param &Intersection intersection on plane on return
160 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
161 */
162
163bool BoundaryTriangleSet::GetIntersectionInsideTriangle(const Vector & MolCenter, const Vector & x, Vector &Intersection) const
164{
165 Info FunctionInfo(__func__);
166 Vector CrossPoint;
167 Vector helper;
168
169 try {
170 Line centerLine = makeLineThrough(MolCenter, x);
171 Intersection = Plane(NormalVector, (endpoints[0]->node->getPosition())).GetIntersection(centerLine);
172
173 LOG(1, "INFO: Triangle is " << *this << ".");
174 LOG(1, "INFO: Line is from " << MolCenter << " to " << x << ".");
175 LOG(1, "INFO: Intersection is " << Intersection << ".");
176
177 if (Intersection.DistanceSquared(endpoints[0]->node->getPosition()) < MYEPSILON) {
178 LOG(1, "Intersection coindices with first endpoint.");
179 return true;
180 } else if (Intersection.DistanceSquared(endpoints[1]->node->getPosition()) < MYEPSILON) {
181 LOG(1, "Intersection coindices with second endpoint.");
182 return true;
183 } else if (Intersection.DistanceSquared(endpoints[2]->node->getPosition()) < MYEPSILON) {
184 LOG(1, "Intersection coindices with third endpoint.");
185 return true;
186 }
187 // Calculate cross point between one baseline and the line from the third endpoint to intersection
188 int i = 0;
189 do {
190 Line line1 = makeLineThrough((endpoints[i%3]->node->getPosition()),(endpoints[(i+1)%3]->node->getPosition()));
191 Line line2 = makeLineThrough((endpoints[(i+2)%3]->node->getPosition()),Intersection);
192 CrossPoint = line1.getIntersection(line2);
193 helper = (endpoints[(i+1)%3]->node->getPosition()) - (endpoints[i%3]->node->getPosition());
194 CrossPoint -= (endpoints[i%3]->node->getPosition()); // cross point was returned as absolute vector
195 const double s = CrossPoint.ScalarProduct(helper)/helper.NormSquared();
196 LOG(1, "INFO: Factor s is " << s << ".");
197 if ((s < -MYEPSILON) || ((s-1.) > MYEPSILON)) {
198 LOG(1, "INFO: Crosspoint " << CrossPoint << "outside of triangle.");
199 return false;
200 }
201 i++;
202 } while (i < 3);
203 LOG(1, "INFO: Crosspoint " << CrossPoint << " inside of triangle.");
204 return true;
205 }
206 catch (LinearAlgebraException &excp) {
207 LOG(1, boost::diagnostic_information(excp));
208 ELOG(1, "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!");
209 return false;
210 }
211 return true;
212}
213
214
215/** Finds the point on the triangle to the point \a *x.
216 * We call Vector::GetIntersectionWithPlane() with \a * and the center of the triangle to receive an intersection point.
217 * Then we check the in-plane part (the part projected down onto plane). We check whether it crosses one of the
218 * boundary lines. If it does, we return this intersection as closest point, otherwise the projected point down.
219 * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
220 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
221 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
222 * the first two basepoints) or not.
223 * \param *x point
224 * \param *ClosestPoint desired closest point inside triangle to \a *x, is absolute vector
225 * \return Distance squared between \a *x and closest point inside triangle
226 */
227double BoundaryTriangleSet::GetClosestPointInsideTriangle(const Vector &x, Vector &ClosestPoint) const
228{
229 Info FunctionInfo(__func__);
230 Vector Direction;
231
232 // 1. get intersection with plane
233 LOG(1, "INFO: Looking for closest point of triangle " << *this << " to " << x << ".");
234 GetCenter(Direction);
235 try {
236 Line l = makeLineThrough(x, Direction);
237 ClosestPoint = Plane(NormalVector, (endpoints[0]->node->getPosition())).GetIntersection(l);
238 }
239 catch (LinearAlgebraException &excp) {
240 (ClosestPoint) = (x);
241 }
242
243 // 2. Calculate in plane part of line (x, intersection)
244 Vector InPlane = (x) - (ClosestPoint); // points from plane intersection to straight-down point
245 InPlane.ProjectOntoPlane(NormalVector);
246 InPlane += ClosestPoint;
247
248 LOG(2, "INFO: Triangle is " << *this << ".");
249 LOG(2, "INFO: Line is from " << Direction << " to " << x << ".");
250 LOG(2, "INFO: In-plane part is " << InPlane << ".");
251
252 // Calculate cross point between one baseline and the desired point such that distance is shortest
253 double ShortestDistance = -1.;
254 bool InsideFlag = false;
255 Vector CrossDirection[3];
256 Vector CrossPoint[3];
257 Vector helper;
258 for (int i = 0; i < 3; i++) {
259 // treat direction of line as normal of a (cut)plane and the desired point x as the plane offset, the intersect line with point
260 Direction = (endpoints[(i+1)%3]->node->getPosition()) - (endpoints[i%3]->node->getPosition());
261 // calculate intersection, line can never be parallel to Direction (is the same vector as PlaneNormal);
262 Line l = makeLineThrough((endpoints[i%3]->node->getPosition()), (endpoints[(i+1)%3]->node->getPosition()));
263 CrossPoint[i] = Plane(Direction, InPlane).GetIntersection(l);
264 CrossDirection[i] = CrossPoint[i] - InPlane;
265 CrossPoint[i] -= (endpoints[i%3]->node->getPosition()); // cross point was returned as absolute vector
266 const double s = CrossPoint[i].ScalarProduct(Direction)/Direction.NormSquared();
267 LOG(2, "INFO: Factor s is " << s << ".");
268 if ((s >= -MYEPSILON) && ((s-1.) <= MYEPSILON)) {
269 CrossPoint[i] += (endpoints[i%3]->node->getPosition()); // make cross point absolute again
270 LOG(2, "INFO: Crosspoint is " << CrossPoint[i] << ", intersecting BoundaryLine between " << endpoints[i % 3]->node->getPosition() << " and " << endpoints[(i + 1) % 3]->node->getPosition() << ".");
271 const double distance = CrossPoint[i].DistanceSquared(x);
272 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
273 ShortestDistance = distance;
274 (ClosestPoint) = CrossPoint[i];
275 }
276 } else
277 CrossPoint[i].Zero();
278 }
279 InsideFlag = true;
280 for (int i = 0; i < 3; i++) {
281 const double sign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 1) % 3]);
282 const double othersign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 2) % 3]);
283
284 if ((sign > -MYEPSILON) && (othersign > -MYEPSILON)) // have different sign
285 InsideFlag = false;
286 }
287 if (InsideFlag) {
288 (ClosestPoint) = InPlane;
289 ShortestDistance = InPlane.DistanceSquared(x);
290 } else { // also check endnodes
291 for (int i = 0; i < 3; i++) {
292 const double distance = x.DistanceSquared(endpoints[i]->node->getPosition());
293 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
294 ShortestDistance = distance;
295 (ClosestPoint) = (endpoints[i]->node->getPosition());
296 }
297 }
298 }
299 LOG(1, "INFO: Closest Point is " << ClosestPoint << " with shortest squared distance is " << ShortestDistance << ".");
300 return ShortestDistance;
301}
302;
303
304/** Checks whether lines is any of the three boundary lines this triangle contains.
305 * \param *line line to test
306 * \return true - line is of the triangle, false - is not
307 */
308bool BoundaryTriangleSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
309{
310 Info FunctionInfo(__func__);
311 for (int i = 0; i < 3; i++)
312 if (line == lines[i])
313 return true;
314 return false;
315}
316;
317
318/** Checks whether point is any of the three endpoints this triangle contains.
319 * \param *point point to test
320 * \return true - point is of the triangle, false - is not
321 */
322bool BoundaryTriangleSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
323{
324 Info FunctionInfo(__func__);
325 for (int i = 0; i < 3; i++)
326 if (point == endpoints[i])
327 return true;
328 return false;
329}
330;
331
332/** Checks whether point is any of the three endpoints this triangle contains.
333 * \param *point TesselPoint to test
334 * \return true - point is of the triangle, false - is not
335 */
336bool BoundaryTriangleSet::ContainsBoundaryPoint(const TesselPoint * const point) const
337{
338 Info FunctionInfo(__func__);
339 for (int i = 0; i < 3; i++)
340 if (point == endpoints[i]->node)
341 return true;
342 return false;
343}
344;
345
346/** Checks whether three given \a *Points coincide with triangle's endpoints.
347 * \param *Points[3] pointer to BoundaryPointSet
348 * \return true - is the very triangle, false - is not
349 */
350bool BoundaryTriangleSet::IsPresentTupel(const BoundaryPointSet * const Points[3]) const
351{
352 Info FunctionInfo(__func__);
353 LOG(1, "INFO: Checking " << Points[0] << "," << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << ".");
354 return (((endpoints[0] == Points[0]) || (endpoints[0] == Points[1]) || (endpoints[0] == Points[2])) && ((endpoints[1] == Points[0]) || (endpoints[1] == Points[1]) || (endpoints[1] == Points[2])) && ((endpoints[2] == Points[0]) || (endpoints[2] == Points[1]) || (endpoints[2] == Points[2])
355
356 ));
357}
358;
359
360/** Checks whether three given \a *Points coincide with triangle's endpoints.
361 * \param *Points[3] pointer to BoundaryPointSet
362 * \return true - is the very triangle, false - is not
363 */
364bool BoundaryTriangleSet::IsPresentTupel(const BoundaryTriangleSet * const T) const
365{
366 Info FunctionInfo(__func__);
367 return (((endpoints[0] == T->endpoints[0]) || (endpoints[0] == T->endpoints[1]) || (endpoints[0] == T->endpoints[2])) && ((endpoints[1] == T->endpoints[0]) || (endpoints[1] == T->endpoints[1]) || (endpoints[1] == T->endpoints[2])) && ((endpoints[2] == T->endpoints[0]) || (endpoints[2] == T->endpoints[1]) || (endpoints[2] == T->endpoints[2])
368
369 ));
370}
371;
372
373/** Returns the endpoint which is not contained in the given \a *line.
374 * \param *line baseline defining two endpoints
375 * \return pointer third endpoint or NULL if line does not belong to triangle.
376 */
377class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(const BoundaryLineSet * const line) const
378{
379 Info FunctionInfo(__func__);
380 // sanity check
381 if (!ContainsBoundaryLine(line))
382 return NULL;
383 for (int i = 0; i < 3; i++)
384 if (!line->ContainsBoundaryPoint(endpoints[i]))
385 return endpoints[i];
386 // actually, that' impossible :)
387 return NULL;
388}
389;
390
391/** Returns the baseline which does not contain the given boundary point \a *point.
392 * \param *point endpoint which is neither endpoint of the desired line
393 * \return pointer to desired third baseline
394 */
395class BoundaryLineSet *BoundaryTriangleSet::GetThirdLine(const BoundaryPointSet * const point) const
396{
397 Info FunctionInfo(__func__);
398 // sanity check
399 if (!ContainsBoundaryPoint(point))
400 return NULL;
401 for (int i = 0; i < 3; i++)
402 if (!lines[i]->ContainsBoundaryPoint(point))
403 return lines[i];
404 // actually, that' impossible :)
405 return NULL;
406}
407;
408
409/** Calculates the center point of the triangle.
410 * Is third of the sum of all endpoints.
411 * \param *center central point on return.
412 */
413void BoundaryTriangleSet::GetCenter(Vector & center) const
414{
415 Info FunctionInfo(__func__);
416 center.Zero();
417 for (int i = 0; i < 3; i++)
418 (center) += (endpoints[i]->node->getPosition());
419 center.Scale(1. / 3.);
420 LOG(1, "INFO: Center is at " << center << ".");
421}
422
423/**
424 * gets the Plane defined by the three triangle Basepoints
425 */
426Plane BoundaryTriangleSet::getPlane() const{
427 ASSERT(endpoints[0] && endpoints[1] && endpoints[2], "Triangle not fully defined");
428
429 return Plane(endpoints[0]->node->getPosition(),
430 endpoints[1]->node->getPosition(),
431 endpoints[2]->node->getPosition());
432}
433
434Vector BoundaryTriangleSet::getEndpoint(int i) const{
435 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
436
437 return endpoints[i]->node->getPosition();
438}
439
440string BoundaryTriangleSet::getEndpointName(int i) const{
441 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
442
443 return endpoints[i]->node->getName();
444}
445
446/** output operator for BoundaryTriangleSet.
447 * \param &ost output stream
448 * \param &a boundary triangle
449 */
450ostream &operator <<(ostream &ost, const BoundaryTriangleSet &a)
451{
452 ost << "[" << a.Nr << "|" << a.getEndpointName(0) << "," << a.getEndpointName(1) << "," << a.getEndpointName(2) << "]";
453 // ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
454 // << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
455 return ost;
456}
457;
458
Note: See TracBrowser for help on using the repository browser.