source: src/Shapes/Shape.cpp@ 4a187d

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 4a187d was f06cbb, checked in by Frederik Heber <heber@…>, 11 years ago

AndShape and OrShape now use Cacheable to store center and radius once calculated.

  • otherwise we might have to traverse a huge tree all the time when actually the shape cannot change and hence a once determined center is always true.
  • getRadius() and getCenter() functionality moved into private functions calculate...().
  • Property mode set to 100644
File size: 14.6 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 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * Shape.cpp
25 *
26 * Created on: Jun 18, 2010
27 * Author: crueger
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include "CodePatterns/Assert.hpp"
38#include "LinearAlgebra/Vector.hpp"
39
40#include "Shapes/Shape.hpp"
41#include "Shapes/Shape_impl.hpp"
42#include "Shapes/ShapeExceptions.hpp"
43#include "Shapes/ShapeType.hpp"
44
45#include "Tesselation/ApproximateShapeArea.hpp"
46#include "Tesselation/ApproximateShapeVolume.hpp"
47
48#include <boost/bind.hpp>
49#include <algorithm>
50#include <limits>
51#include <string>
52
53
54Shape::Shape(const Shape& src) :
55 impl(src.getImpl()), name(src.getName())
56{}
57
58Shape::~Shape(){}
59
60bool Shape::isInside(const Vector &point) const{
61 return impl->isInside(point);
62}
63
64bool Shape::isOnSurface(const Vector &point) const{
65 return impl->isOnSurface(point);
66}
67
68Vector Shape::getNormal(const Vector &point) const throw (NotOnSurfaceException){
69 return impl->getNormal(point);
70}
71
72Vector Shape::getCenter() const{
73 return impl->getCenter();
74}
75
76double Shape::getRadius() const{
77 return impl->getRadius();
78}
79
80void Shape::setName(const std::string &_name){
81 name = _name;
82}
83
84std::string Shape::getName() const{
85 return name;
86}
87
88/** Returns the volume of the Shape.
89 *
90 * If the underlying implementation does not have a working implementation,
91 * i.e. returns -1., then we use an approximate method to calculate the
92 * volume via a mesh of grid points and checking for isInside (basically
93 * a Monte-Carlo integration of the volume).
94 *
95 * \return volume of the shape
96 */
97double Shape::getVolume() const
98{
99 const double volume = impl->getVolume();
100 if (volume != -1.) {
101 return volume;
102 } else {
103 ApproximateShapeVolume Approximator(*this);
104 return Approximator();
105 }
106}
107
108/** Returns the surface area of the Shape.
109 *
110 * If the underlying implementation does not have a working implementation,
111 * i.e. returns -1., then we use the working filling of the shapes surface
112 * with points and subsequent tesselation and obtaining the approximate
113 * surface area therefrom.
114 *
115 * @return surface area of the Shape
116 */
117double Shape::getSurfaceArea() const
118{
119 const double surfacearea = impl->getSurfaceArea();
120 if (surfacearea != -1.) {
121 return surfacearea;
122 } else {
123 ApproximateShapeArea Approximator(*this);
124 return Approximator();
125 }
126}
127
128LineSegmentSet Shape::getLineIntersections(const Line &line) const{
129 return impl->getLineIntersections(line);
130}
131
132std::vector<Vector> Shape::getHomogeneousPointsOnSurface(const size_t N) const {
133 return impl->getHomogeneousPointsOnSurface(N);
134}
135
136std::vector<Vector> Shape::getHomogeneousPointsInVolume(const size_t N) const {
137 return impl->getHomogeneousPointsInVolume(N);
138}
139
140Shape::Shape(Shape::impl_ptr _impl) :
141 impl(_impl)
142{}
143
144Shape &Shape::operator=(const Shape& rhs){
145 if(&rhs!=this){
146 impl=rhs.getImpl();
147 }
148 return *this;
149}
150
151bool Shape::operator==(const Shape &rhs) const{
152 return (this->getType() == rhs.getType());
153}
154
155std::string Shape::toString() const {
156 return impl->toString();
157}
158
159enum ShapeType Shape::getType() const{
160 return impl->getType();
161}
162
163Shape::impl_ptr Shape::getImpl() const{
164 return impl;
165}
166
167// allows arbitrary friendship, but only if implementation is known
168Shape::impl_ptr getShapeImpl(const Shape &shape){
169 return shape.getImpl();
170}
171
172/***************************** Some simple Shapes ***************************/
173
174Shape Everywhere(){
175 static Shape::impl_ptr impl = Shape::impl_ptr(new Everywhere_impl());
176 return Shape(impl);
177}
178
179Shape Nowhere(){
180 static Shape::impl_ptr impl = Shape::impl_ptr(new Nowhere_impl());
181 return Shape(impl);
182}
183
184/****************************** Operators ***********************************/
185
186// AND
187
188AndShape_impl::AndShape_impl(const Shape::impl_ptr &_lhs, const Shape::impl_ptr &_rhs) :
189 lhs(_lhs),
190 rhs(_rhs),
191 radius(NULL, boost::bind(&AndShape_impl::calculateRadius, this), "radius"),
192 center(NULL, boost::bind(&AndShape_impl::calculateCenter, this), "center")
193{}
194
195AndShape_impl::~AndShape_impl(){}
196
197bool AndShape_impl::isInside(const Vector &point) const{
198 return lhs->isInside(point) && rhs->isInside(point);
199}
200
201bool AndShape_impl::isOnSurface(const Vector &point) const{
202 // check the number of surfaces that this point is on
203 int surfaces =0;
204 surfaces += lhs->isOnSurface(point);
205 surfaces += rhs->isOnSurface(point);
206
207 switch(surfaces){
208 case 0:
209 return false;
210 // no break necessary
211 case 1:
212 // if it is inside for the object where it does not lie on
213 // the surface the whole point lies inside
214 return (lhs->isOnSurface(point) && rhs->isInside(point)) ||
215 (rhs->isOnSurface(point) && lhs->isInside(point));
216 // no break necessary
217 case 2:
218 {
219 // it lies on both Shapes... could be an edge or an inner point
220 // test the direction of the normals
221 Vector direction=lhs->getNormal(point)+rhs->getNormal(point);
222 // if the directions are opposite we lie on the inside
223 return !direction.IsZero();
224 }
225 // no break necessary
226 default:
227 // if this happens there is something wrong
228 ASSERT(0,"Default case should have never been used");
229 }
230 return false; // never reached
231}
232
233Vector AndShape_impl::getNormal(const Vector &point) const throw (NotOnSurfaceException){
234 Vector res;
235 if(!isOnSurface(point)){
236 throw NotOnSurfaceException() << ShapeVector(&point);
237 }
238 res += lhs->isOnSurface(point)?lhs->getNormal(point):zeroVec;
239 res += rhs->isOnSurface(point)?rhs->getNormal(point):zeroVec;
240 res.Normalize();
241 return res;
242}
243
244Vector AndShape_impl::calculateCenter() const
245{
246 // calculate closest position on sphere surface to other center ..
247 const Vector rhsDistance = rhs->getCenter() + rhs->getRadius()*((lhs->getCenter() - rhs->getCenter()).getNormalized());
248 const Vector lhsDistance = lhs->getCenter() + lhs->getRadius()*((rhs->getCenter() - lhs->getCenter()).getNormalized());
249 // .. and then it's right in between those two
250 return 0.5*(rhsDistance + lhsDistance);
251}
252
253double AndShape_impl::calculateRadius() const
254{
255 const double distance = (lhs->getCenter() - rhs->getCenter()).Norm();
256 const double minradii = std::min(lhs->getRadius(), rhs->getRadius());
257 // if no intersection
258 if (distance > (lhs->getRadius() + rhs->getRadius()))
259 return 0.;
260 else // if intersection it can only be the smaller one
261 return minradii;
262}
263
264double AndShape_impl::getVolume() const
265{
266 // TODO
267 return -1.;
268}
269
270double AndShape_impl::getSurfaceArea() const
271{
272 // TODO
273 return -1.;
274}
275
276LineSegmentSet AndShape_impl::getLineIntersections(const Line &line) const{
277 return intersect(lhs->getLineIntersections(line),rhs->getLineIntersections(line));
278}
279
280std::string AndShape_impl::toString() const{
281 return std::string("(") + lhs->toString() + std::string("&&") + rhs->toString() + std::string(")");
282}
283
284enum ShapeType AndShape_impl::getType() const{
285 return CombinedType;
286}
287
288std::vector<Vector> AndShape_impl::getHomogeneousPointsOnSurface(const size_t N) const {
289 std::vector<Vector> PointsOnSurface_lhs = lhs->getHomogeneousPointsOnSurface(N);
290 std::vector<Vector> PointsOnSurface_rhs = rhs->getHomogeneousPointsOnSurface(N);
291 std::vector<Vector> PointsOnSurface;
292
293 for (std::vector<Vector>::const_iterator iter = PointsOnSurface_lhs.begin(); iter != PointsOnSurface_lhs.end(); ++iter) {
294 if (rhs->isInside(*iter))
295 PointsOnSurface.push_back(*iter);
296 }
297 for (std::vector<Vector>::const_iterator iter = PointsOnSurface_rhs.begin(); iter != PointsOnSurface_rhs.end(); ++iter) {
298 if (lhs->isInside(*iter))
299 PointsOnSurface.push_back(*iter);
300 }
301
302 return PointsOnSurface;
303}
304
305std::vector<Vector> AndShape_impl::getHomogeneousPointsInVolume(const size_t N) const {
306 ASSERT(0,
307 "AndShape_impl::getHomogeneousPointsInVolume() - not implemented.");
308 return std::vector<Vector>();
309}
310
311
312Shape operator&&(const Shape &lhs,const Shape &rhs){
313 Shape::impl_ptr newImpl = Shape::impl_ptr(new AndShape_impl(getShapeImpl(lhs),getShapeImpl(rhs)));
314 return Shape(newImpl);
315}
316
317// OR
318
319OrShape_impl::OrShape_impl(const Shape::impl_ptr &_lhs, const Shape::impl_ptr &_rhs) :
320 lhs(_lhs),
321 rhs(_rhs),
322 radius(NULL, boost::bind(&OrShape_impl::calculateRadius, this), "radius"),
323 center(NULL, boost::bind(&OrShape_impl::calculateCenter, this), "center")
324{}
325
326OrShape_impl::~OrShape_impl(){}
327
328bool OrShape_impl::isInside(const Vector &point) const{
329 return rhs->isInside(point) || lhs->isInside(point);
330}
331
332bool OrShape_impl::isOnSurface(const Vector &point) const{
333 // check the number of surfaces that this point is on
334 int surfaces =0;
335 surfaces += lhs->isOnSurface(point);
336 surfaces += rhs->isOnSurface(point);
337
338 switch(surfaces){
339 case 0:
340 return false;
341 // no break necessary
342 case 1:
343 // if it is inside for the object where it does not lie on
344 // the surface the whole point lies inside
345 return (lhs->isOnSurface(point) && !rhs->isInside(point)) ||
346 (rhs->isOnSurface(point) && !lhs->isInside(point));
347 // no break necessary
348 case 2:
349 {
350 // it lies on both Shapes... could be an edge or an inner point
351 // test the direction of the normals
352 Vector direction=lhs->getNormal(point)+rhs->getNormal(point);
353 // if the directions are opposite we lie on the inside
354 return !direction.IsZero();
355 }
356 // no break necessary
357 default:
358 // if this happens there is something wrong
359 ASSERT(0,"Default case should have never been used");
360 }
361 return false; // never reached
362}
363
364Vector OrShape_impl::getNormal(const Vector &point) const throw (NotOnSurfaceException){
365 Vector res;
366 if(!isOnSurface(point)){
367 throw NotOnSurfaceException() << ShapeVector(&point);
368 }
369 res += lhs->isOnSurface(point)?lhs->getNormal(point):zeroVec;
370 res += rhs->isOnSurface(point)?rhs->getNormal(point):zeroVec;
371 res.Normalize();
372 return res;
373}
374
375Vector OrShape_impl::calculateCenter() const
376{
377 // calculate furthest position on sphere surface to other center ..
378 const Vector rhsDistance = rhs->getCenter() + rhs->getRadius()*((rhs->getCenter() - lhs->getCenter()).getNormalized());
379 const Vector lhsDistance = lhs->getCenter() + lhs->getRadius()*((lhs->getCenter() - rhs->getCenter()).getNormalized());
380 // .. and then it's right in between those two
381 return .5*(rhsDistance + lhsDistance);
382}
383
384double OrShape_impl::calculateRadius() const
385{
386 const Vector rhsDistance = rhs->getCenter() + rhs->getRadius()*((rhs->getCenter() - lhs->getCenter()).getNormalized());
387 const Vector lhsDistance = lhs->getCenter() + lhs->getRadius()*((lhs->getCenter() - rhs->getCenter()).getNormalized());
388 return .5*(rhsDistance - lhsDistance).Norm();
389}
390
391double OrShape_impl::getVolume() const
392{
393 // TODO
394 return -1.;
395}
396
397double OrShape_impl::getSurfaceArea() const
398{
399 // TODO
400 return -1.;
401}
402
403LineSegmentSet OrShape_impl::getLineIntersections(const Line &line) const{
404 return merge(lhs->getLineIntersections(line),rhs->getLineIntersections(line));
405}
406
407std::string OrShape_impl::toString() const{
408 return std::string("(") + lhs->toString() + std::string("||") + rhs->toString() + std::string(")");
409}
410
411enum ShapeType OrShape_impl::getType() const{
412 return CombinedType;
413}
414
415std::vector<Vector> OrShape_impl::getHomogeneousPointsOnSurface(const size_t N) const {
416 std::vector<Vector> PointsOnSurface_lhs = lhs->getHomogeneousPointsOnSurface(N);
417 std::vector<Vector> PointsOnSurface_rhs = rhs->getHomogeneousPointsOnSurface(N);
418 std::vector<Vector> PointsOnSurface;
419
420 for (std::vector<Vector>::const_iterator iter = PointsOnSurface_lhs.begin(); iter != PointsOnSurface_lhs.end(); ++iter) {
421 if (!rhs->isInside(*iter))
422 PointsOnSurface.push_back(*iter);
423 }
424 for (std::vector<Vector>::const_iterator iter = PointsOnSurface_rhs.begin(); iter != PointsOnSurface_rhs.end(); ++iter) {
425 if (!lhs->isInside(*iter))
426 PointsOnSurface.push_back(*iter);
427 }
428
429 return PointsOnSurface;
430}
431
432std::vector<Vector> OrShape_impl::getHomogeneousPointsInVolume(const size_t N) const {
433 ASSERT(0,
434 "OrShape_impl::getHomogeneousPointsInVolume() - not implemented.");
435 return std::vector<Vector>();
436}
437
438Shape operator||(const Shape &lhs,const Shape &rhs){
439 Shape::impl_ptr newImpl = Shape::impl_ptr(new OrShape_impl(getShapeImpl(lhs),getShapeImpl(rhs)));
440 return Shape(newImpl);
441}
442
443// NOT
444
445NotShape_impl::NotShape_impl(const Shape::impl_ptr &_arg) :
446 arg(_arg)
447{}
448
449NotShape_impl::~NotShape_impl(){}
450
451bool NotShape_impl::isInside(const Vector &point) const{
452 return !arg->isInside(point);
453}
454
455bool NotShape_impl::isOnSurface(const Vector &point) const{
456 return arg->isOnSurface(point);
457}
458
459Vector NotShape_impl::getNormal(const Vector &point) const throw(NotOnSurfaceException){
460 return -1.*arg->getNormal(point);
461}
462
463Vector NotShape_impl::getCenter() const
464{
465 return arg->getCenter();
466}
467
468double NotShape_impl::getRadius() const
469{
470 return std::numeric_limits<double>::infinity();
471}
472
473double NotShape_impl::getVolume() const
474{
475 // TODO
476 return -1.; //-arg->getVolume();
477}
478
479double NotShape_impl::getSurfaceArea() const
480{
481 // TODO
482 return -1.; // -arg->getSurfaceArea();
483}
484
485LineSegmentSet NotShape_impl::getLineIntersections(const Line &line) const{
486 return invert(arg->getLineIntersections(line));
487}
488
489std::string NotShape_impl::toString() const{
490 return std::string("!") + arg->toString();
491}
492
493enum ShapeType NotShape_impl::getType() const{
494 return CombinedType;
495}
496
497std::vector<Vector> NotShape_impl::getHomogeneousPointsOnSurface(const size_t N) const {
498 // surfaces are the same, only normal direction is different
499 return arg->getHomogeneousPointsOnSurface(N);
500}
501
502std::vector<Vector> NotShape_impl::getHomogeneousPointsInVolume(const size_t N) const {
503 ASSERT(0,
504 "NotShape_impl::getHomogeneousPointsInVolume() - not implemented.");
505 return std::vector<Vector>();
506}
507
508Shape operator!(const Shape &arg){
509 Shape::impl_ptr newImpl = Shape::impl_ptr(new NotShape_impl(getShapeImpl(arg)));
510 return Shape(newImpl);
511}
512
513/**************** global operations *********************************/
514std::ostream &operator<<(std::ostream &ost,const Shape &shape){
515 ost << shape.toString();
516 return ost;
517}
Note: See TracBrowser for help on using the repository browser.