source: src/UIElements/Views/Qt4/Qt3D/GLMoleculeObject_molecule.cpp@ 5be798

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

Qt4 instance use new lastChanged..Id() in place of lastChanged().

  • also changed in FormatParser_common.
  • Property mode set to 100644
File size: 31.8 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 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * GLMoleculeObject_molecule.cpp
26 *
27 * Created on: Mar 30, 2012
28 * Author: ankele
29 */
30
31
32
33
34
35// include config.h
36#ifdef HAVE_CONFIG_H
37#include <config.h>
38#endif
39
40#include "GLMoleculeObject_molecule.hpp"
41
42#include <Qt3D/qglscenenode.h>
43#include <Qt3D/qglbuilder.h>
44
45#include "CodePatterns/MemDebug.hpp"
46
47#include <boost/assign.hpp>
48
49#include "CodePatterns/Assert.hpp"
50#include "CodePatterns/Log.hpp"
51#include "CodePatterns/Observer/Notification.hpp"
52#include "CodePatterns/Observer/ObserverLog.hpp"
53
54#include "Atom/atom.hpp"
55#include "molecule.hpp"
56#include "Descriptors/AtomIdDescriptor.hpp"
57#include "Descriptors/MoleculeIdDescriptor.hpp"
58#include "Element/element.hpp"
59#include "LinearAlgebra/Vector.hpp"
60#include "LinkedCell/PointCloudAdaptor.hpp"
61#include "LinkedCell/linkedcell.hpp"
62#include "Tesselation/tesselation.hpp"
63#include "Tesselation/BoundaryLineSet.hpp"
64#include "Tesselation/BoundaryTriangleSet.hpp"
65#include "Tesselation/CandidateForTesselation.hpp"
66#include "Atom/TesselPoint.hpp"
67#include "World.hpp"
68
69using namespace boost::assign;
70
71#include "GLMoleculeObject_atom.hpp"
72
73static Observable::channels_t getAtomsChannels()
74{
75 Observable::channels_t channels;
76 channels += molecule::AtomInserted, molecule::AtomRemoved;
77 return channels;
78}
79
80static Observable::channels_t getAllAtomicChangesChannels()
81{
82 Observable::channels_t channels;
83 channels += molecule::AtomInserted, molecule::AtomRemoved, molecule::AtomMoved;
84 return channels;
85}
86
87// static instances
88const Observable::channels_t GLMoleculeObject_molecule::AtomsChannels(getAtomsChannels());
89const Observable::channels_t GLMoleculeObject_molecule::HullChannels(getAllAtomicChangesChannels());
90const Observable::channels_t GLMoleculeObject_molecule::BoundingBoxChannels(getAllAtomicChangesChannels());
91const Observable::channels_t GLMoleculeObject_molecule::IndexChannels(1, molecule::IndexChanged);
92
93static QGLSceneNode *createMoleculeMesh(const QGeometryData &_geo)
94{
95 // Build a mesh from the geometry.
96 QGLBuilder builder;
97 builder.addTriangles(_geo);
98 QGLSceneNode *mesh = builder.finalizedSceneNode();
99 return mesh;
100}
101
102GLMoleculeObject_molecule::GLMoleculeObject_molecule(QObject *parent, const moleculeId_t _molid) :
103 GLMoleculeObject((QGLSceneNode *)NULL, parent),
104 Observer(std::string("GLMoleculeObject_molecule")+toString(_molid)),
105 owner(NULL),
106 molref(getMolecule(_molid)),
107 /* We must not use boost::cref(this) as "this" has not been properly constructed and seemingly
108 * boost::cref tries to do some magic to grasp the inheritance hierarchy which fails because
109 * the class has not been fully constructed yet. "This" itself seems to be working fine.
110 */
111 MolIndexUpdater(
112 boost::bind(&GLMoleculeObject_molecule::updateIndex, this)
113 ),
114 TesselationHullUpdater(
115 boost::bind(&GLMoleculeObject_molecule::updateTesselationHull, this)
116 ),
117 IsSelectedUpdater(
118 boost::bind(&GLMoleculeObject_molecule::updateIsSelected, this)
119 ),
120 BoundingBoxUpdater(
121 boost::bind(&GLMoleculeObject_molecule::updateBoundingBox, this)
122 ),
123 PresentAtomsUpdater(
124 boost::bind(&GLMoleculeObject_molecule::updateAtoms, this)
125 ),
126 MolIndex(
127 molref,
128 MolIndexUpdater,
129 "MoleculeIndex_"+toString(_molid),
130 _molid,
131 IndexChannels),
132 TesselationHull(
133 molref,
134 TesselationHullUpdater,
135 "MoleculeTesselationHull_"+toString(_molid),
136 HullChannels),
137 isSelected(
138 const_cast<const World * const>(World::getPointer()),
139 IsSelectedUpdater,
140 "MoleculeBoundingBox_"+toString(_molid),
141 updateIsSelected(),
142 BoundingBoxChannels),
143 BoundingBox(
144 molref,
145 BoundingBoxUpdater,
146 "MoleculeBoundingBox_"+toString(_molid),
147 updateBoundingBox(),
148 BoundingBoxChannels),
149 PresentAtoms(
150 molref,
151 PresentAtomsUpdater,
152 "MoleculeAtoms_"+toString(_molid),
153 updateAtoms(),
154 AtomsChannels),
155 hoverAtomId(-1)
156{
157 setObjectId(_molid);
158 setMaterial(getMaterial(1));
159
160 // initially, atoms and bonds should be visible
161 m_visible = false;
162
163 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
164 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
165 connect (this, SIGNAL(TesselationHullChanged()), this, SLOT(resetTesselationHull()), Qt::QueuedConnection);
166 connect (this, SIGNAL(BoundingBoxChanged()), this, SLOT(resetBoundingBox()), Qt::QueuedConnection);
167 connect (this, SIGNAL(IsSelectedChanged()), this, SLOT(resetIsSelected()), Qt::QueuedConnection);
168 connect (this, SIGNAL(IdChanged()), this, SLOT(resetIndex()), Qt::QueuedConnection);
169 connect (this, SIGNAL(AtomInserted(const atomId_t)), this, SLOT(atomInserted(const atomId_t)), Qt::QueuedConnection);
170 connect (this, SIGNAL(AtomInserted(const atomId_t)), this, SLOT(resetAtoms()), Qt::QueuedConnection);
171 connect (this, SIGNAL(AtomRemoved(const atomId_t)), this, SLOT(resetAtoms()), Qt::QueuedConnection);
172 connect (this, SIGNAL(AtomRemoved(const atomId_t)), this, SLOT(atomRemoved(const atomId_t)), Qt::QueuedConnection);
173
174 connect( this, SIGNAL(clicked()), this, SLOT(wasClicked()));
175}
176
177GLMoleculeObject_molecule::GLMoleculeObject_molecule(QGLSceneNode *mesh[], QObject *parent, const moleculeId_t _molid) :
178 GLMoleculeObject(mesh, parent),
179 Observer(std::string("GLMoleculeObject_molecule")+toString(_molid)),
180 owner(NULL),
181 molref(getMolecule(_molid)),
182 /* We must not use boost::cref(this) as "this" has not been properly constructed and seemingly
183 * boost::cref tries to do some magic to grasp the inheritance hierarchy which fails because
184 * the class has not been fully constructed yet. "This" itself seems to be working fine.
185 */
186 MolIndexUpdater(
187 boost::bind(&GLMoleculeObject_molecule::updateIndex, this)
188 ),
189 TesselationHullUpdater(
190 boost::bind(&GLMoleculeObject_molecule::updateTesselationHull, this)
191 ),
192 IsSelectedUpdater(
193 boost::bind(&GLMoleculeObject_molecule::updateIsSelected, this)
194 ),
195 BoundingBoxUpdater(
196 boost::bind(&GLMoleculeObject_molecule::updateBoundingBox, this)
197 ),
198 PresentAtomsUpdater(
199 boost::bind(&GLMoleculeObject_molecule::updateAtoms, this)
200 ),
201 MolIndex(
202 molref,
203 MolIndexUpdater,
204 "MoleculeIndex_"+toString(_molid),
205 _molid,
206 IndexChannels),
207 TesselationHull(
208 molref,
209 TesselationHullUpdater,
210 "MoleculeTesselationHull_"+toString(_molid),
211 HullChannels),
212 isSelected(
213 const_cast<const World * const>(World::getPointer()),
214 IsSelectedUpdater,
215 "MoleculeBoundingBox_"+toString(_molid),
216 updateIsSelected(),
217 BoundingBoxChannels),
218 BoundingBox(
219 molref,
220 BoundingBoxUpdater,
221 "MoleculeBoundingBox_"+toString(_molid),
222 updateBoundingBox(),
223 BoundingBoxChannels),
224 PresentAtoms(
225 molref,
226 PresentAtomsUpdater,
227 "MoleculeAtoms_"+toString(_molid),
228 atoms_t(),
229 AtomsChannels),
230 hoverAtomId(-1)
231{
232 setObjectId(_molid);
233 setMaterial(getMaterial(1));
234
235 // initially, atoms and bonds should be visible
236 m_visible = false;
237
238 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
239 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
240 connect (this, SIGNAL(TesselationHullChanged()), this, SLOT(resetTesselationHull()), Qt::QueuedConnection);
241 connect (this, SIGNAL(BoundingBoxChanged()), this, SLOT(resetBoundingBox()), Qt::QueuedConnection);
242 connect (this, SIGNAL(IsSelectedChanged()), this, SLOT(resetIsSelected()), Qt::QueuedConnection);
243 connect (this, SIGNAL(IdChanged()), this, SLOT(resetIndex()), Qt::QueuedConnection);
244 connect (this, SIGNAL(AtomInserted(const atomId_t)), this, SLOT(atomInserted(const atomId_t)), Qt::QueuedConnection);
245 connect (this, SIGNAL(AtomInserted(const atomId_t)), this, SLOT(resetAtoms()), Qt::QueuedConnection);
246 connect (this, SIGNAL(AtomRemoved(const atomId_t)), this, SLOT(resetAtoms()), Qt::QueuedConnection);
247 connect (this, SIGNAL(AtomRemoved(const atomId_t)), this, SLOT(atomRemoved(const atomId_t)), Qt::QueuedConnection);
248
249 connect( this, SIGNAL(clicked()), this, SLOT(wasClicked()));
250}
251
252GLMoleculeObject_molecule::~GLMoleculeObject_molecule()
253{
254 deactivateObserver();
255}
256
257void GLMoleculeObject_molecule::deactivateObserver()
258{
259 if (owner != NULL) {
260 owner->signOff(this, molecule::AtomInserted);
261 owner->signOff(this, molecule::AtomRemoved);
262 owner->signOff(this, molecule::AtomMoved);
263 owner->signOff(this, molecule::IndexChanged);
264 /*_atom->signOff(this, AtomObservable::IndexChanged);
265 _atom->signOff(this, AtomObservable::PositionChanged);
266 _atom->signOff(this, AtomObservable::ElementChanged);
267 _atom->signOff(this, AtomObservable::BondsAdded);*/
268 World::getInstance().signOff(this, World::SelectionChanged);
269 owner = NULL;
270 }
271}
272
273void GLMoleculeObject_molecule::activateObserver()
274{
275 // sign on as observer (obtain non-const instance before)
276 const molecule * const _molecule = getMolecule(MolIndex.get());
277 if (_molecule != NULL) {
278 owner = static_cast<const Observable *>(_molecule);
279 owner->signOn(this, molecule::AtomInserted);
280 owner->signOn(this, molecule::AtomRemoved);
281 owner->signOn(this, molecule::AtomMoved);
282 owner->signOn(this, molecule::IndexChanged);
283 /*molref->signOn(this, AtomObservable::IndexChanged);
284 molref->signOn(this, AtomObservable::PositionChanged);
285 molref->signOn(this, AtomObservable::ElementChanged);
286 molref->signOn(this, AtomObservable::BondsAdded);*/
287 World::getInstance().signOn(this, World::SelectionChanged);
288 } else {
289 ELOG(1, "GLMoleculeObject_molecule() - added null object for not present mol id " << MolIndex.get());
290 }
291
292}
293
294void GLMoleculeObject_molecule::addAtomBonds(
295 const bond::ptr &_bond,
296 const GLMoleculeObject_bond::SideOfBond _side
297 )
298{
299 bool bond_present = false;
300 const BondIds ids = getBondIds(_bond, _side);
301 // check whether bond is not present already
302 bond_present = BondsinSceneMap.count(ids);
303 if (!bond_present)
304 bondInserted(ids.first, ids.second, _side);
305 else {
306 BondsinSceneMap[ids]->resetPosition();
307 BondsinSceneMap[ids]->resetWidth();
308 }
309}
310
311void GLMoleculeObject_molecule::addAtomBonds(
312 const atom *_atom)
313{
314 const bool atom_present = AtomsinSceneMap.count(_atom->getId());
315 const BondList &bondlist = _atom->getListOfBonds();
316 for (BondList::const_iterator bonditer = bondlist.begin();
317 (bonditer != bondlist.end()) && atom_present;
318 ++bonditer) {
319 const bond::ptr _bond = *bonditer;
320 // check if OtherAtom's sphere is already present
321 const atom *OtherAtom = _bond->GetOtherAtom(_atom);
322 const bool otheratom_present = AtomsinSceneMap.count(OtherAtom->getId());
323 if (otheratom_present && atom_present) {
324 const GLMoleculeObject_bond::SideOfBond side = (_bond->leftatom == _atom) ?
325 GLMoleculeObject_bond::left : GLMoleculeObject_bond::right;
326 const GLMoleculeObject_bond::SideOfBond otherside = (_bond->leftatom == _atom) ?
327 GLMoleculeObject_bond::right : GLMoleculeObject_bond::left;
328 addAtomBonds(_bond, side);
329 addAtomBonds(_bond, otherside);
330 }
331 }
332}
333
334QGeometryData GLMoleculeObject_molecule::updateTesselationHull() const
335{
336 QGeometryData geo;
337
338 const molecule * const molref = getMolecule(MolIndex.get());
339 if (molref == NULL) {
340 ELOG(1, "Could not createMoleculeMesh, molecule with id " << MolIndex.get() << " already gone.");
341 return geo;
342 }
343 double minradius = 2.; // TODO: set to maximum bond length value
344 LOG(3, "DEBUG: Molecule fits into sphere of radius " << minradius);
345 // check minimum bond radius in molecule
346 double minlength = std::numeric_limits<double>::max();
347 for (molecule::const_iterator iter = molref->begin();
348 iter != molref->end(); ++iter) {
349 const BondList &ListOfBonds = (*iter)->getListOfBonds();
350 for (BondList::const_iterator bonditer = ListOfBonds.begin();
351 bonditer != ListOfBonds.end(); ++bonditer) {
352 const double bond_distance = (*bonditer)->GetDistance();
353 minlength = std::min(bond_distance, minlength);
354 }
355 }
356 minradius = std::max( std::max(minradius, minlength), 1.);
357
358 // we need at least three points for tesselation
359 if (molref->getAtomCount() >= 3) {
360 // Tesselate the points.
361 Tesselation T;
362 PointCloudAdaptor<molecule> cloud(const_cast<molecule *>(molref), molref->getName());
363 T(cloud, minradius);
364
365 // Fill the points into a Qt geometry.
366 LinkedCell_deprecated LinkedList(cloud, minradius);
367 std::map<int, int> indices;
368 std::map<int, Vector> normals;
369 int index = 0;
370 for (PointMap::const_iterator piter = T.PointsOnBoundary.begin();
371 piter != T.PointsOnBoundary.end(); ++piter) {
372 const Vector &point = piter->second->getPosition();
373 // add data to the primitive
374 geo.appendVertex(QVector3D(point[0], point[1], point[2]));
375 Vector normalvector;
376 for (LineMap::const_iterator lineiter = piter->second->lines.begin();
377 lineiter != piter->second->lines.end(); ++lineiter)
378 for (TriangleMap::const_iterator triangleiter = lineiter->second->triangles.begin();
379 triangleiter != lineiter->second->triangles.end(); ++triangleiter)
380 normalvector +=
381 triangleiter->second->NormalVector;
382 normalvector.Normalize();
383 geo.appendNormal(QVector3D(normalvector[0], normalvector[1], normalvector[2]));
384 geo.appendColor(QColor(1, 1, 1, 1));
385 geo.appendTexCoord(QVector2D(0, 0));
386 indices.insert( std::make_pair( piter->second->getNr(), index++));
387 }
388
389 // Fill the tesselated triangles into the geometry.
390 for (TriangleMap::const_iterator runner = T.TrianglesOnBoundary.begin();
391 runner != T.TrianglesOnBoundary.end(); runner++) {
392 int v[3];
393 for (size_t i=0; i<3; ++i)
394 v[i] = runner->second->endpoints[i]->getNr();
395
396 // Sort the vertices so the triangle is clockwise (relative to the normal vector).
397 Vector cross = T.PointsOnBoundary[v[1]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition();
398 cross.VectorProduct(T.PointsOnBoundary[v[2]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition());
399 if (cross.ScalarProduct(runner->second->NormalVector) > 0)
400 geo.appendIndices(indices[v[0]], indices[v[1]], indices[v[2]]);
401 else
402 geo.appendIndices(indices[v[0]], indices[v[2]], indices[v[1]]);
403 }
404 }
405
406 return geo;
407}
408
409bool GLMoleculeObject_molecule::updateIsSelected() const
410{
411 return const_cast<const World &>(World::getInstance()).isMoleculeSelected(MolIndex.get());
412}
413
414GLMoleculeObject_molecule::BoundingBoxInfo GLMoleculeObject_molecule::updateBoundingBox() const
415{
416 BoundingBoxInfo info;
417 const molecule * const _molecule = getMolecule(MolIndex.get());
418 if (_molecule != NULL) {
419 Shape shape = _molecule->getBoundingSphere();
420 info.position = shape.getCenter();
421 info.radius = shape.getRadius();
422 } else
423 ELOG(2, "GLMoleculeObject_molecule cannot updateBoundingBox, molecule with "
424 << MolIndex.get() << " has disappeared.");
425 return info;
426}
427
428GLMoleculeObject_molecule::atoms_t GLMoleculeObject_molecule::updateAtoms()
429{
430 const molecule * const mol = getMolecule(MolIndex.get());
431 if (mol != NULL) {
432 const atomId_t id = mol->lastChangedAtomId();
433 if (mol->containsAtom(id))
434 DisplayedAtoms.insert(id);
435 else
436 DisplayedAtoms.erase(id);
437 }
438 return DisplayedAtoms;
439}
440
441moleculeId_t GLMoleculeObject_molecule::updateIndex() const
442{
443 return const_cast<const World &>(World::getInstance()).lastChangedMolId();
444}
445
446void GLMoleculeObject_molecule::resetTesselationHull()
447{
448 if (!TesselationHull.isValid())
449 updateMesh(createMoleculeMesh(*TesselationHull));
450}
451
452void GLMoleculeObject_molecule::resetIsSelected()
453{
454 setSelected(isSelected.get());
455}
456
457void GLMoleculeObject_molecule::resetBoundingBox()
458{
459 BoundingBoxInfo info = BoundingBox.get();
460 setPosition(QVector3D(info.position[0], info.position[1], info.position[2]));
461 setScale(info.radius + 0.3); // getBoundingSphere() only sees atoms as points, so make the box a bit bigger
462}
463
464void GLMoleculeObject_molecule::resetAtoms()
465{
466 const atoms_t atoms = PresentAtoms.get();
467 std::vector<atomId_t> InsertedAtoms;
468 std::vector<atomId_t> RemovedAtoms;
469 // obtain all newly inserted and removed atoms
470 std::set_difference(
471 atoms.begin(), atoms.end(),
472 DisplayedAtoms.begin(), DisplayedAtoms.end(),
473 std::back_inserter(InsertedAtoms));
474 std::set_difference(
475 DisplayedAtoms.begin(), DisplayedAtoms.end(),
476 atoms.begin(), atoms.end(),
477 std::back_inserter(RemovedAtoms));
478 // remove the atoms
479 std::for_each(RemovedAtoms.begin(), RemovedAtoms.end(),
480 boost::bind(&GLMoleculeObject_molecule::atomRemoved, this, _1));
481 // insert the atoms
482 std::for_each(InsertedAtoms.begin(), InsertedAtoms.end(),
483 boost::bind(&GLMoleculeObject_molecule::atomInserted, this, _1));
484
485 emit changed();
486}
487
488void GLMoleculeObject_molecule::resetIndex()
489{
490 const atomId_t newId = MolIndex.get();
491 const size_t oldId = objectId();
492 ASSERT( newId != oldId,
493 "GLMoleculeObject_molecule::resetIndex() - index "+toString(newId)+" did not change.");
494 LOG(4, "INFO: GLMoleculeObject_molecule: new index is "+toString(newId)+".");
495 setObjectId(newId);
496
497 emit indexChanged(this, oldId, newId);
498}
499
500void GLMoleculeObject_molecule::update(Observable *publisher)
501{
502#ifdef LOG_OBSERVER
503 const molecule *_mol = static_cast<molecule *>(publisher);
504 observerLog().addMessage() << "++ Update of Observer " << observerLog().getName(static_cast<Observer *>(this)) << " from molecule "+toString(_mol->getId())+".";
505#endif
506}
507
508void GLMoleculeObject_molecule::subjectKilled(Observable *publisher)
509{
510 deactivateObserver();
511}
512
513void GLMoleculeObject_molecule::recieveNotification(Observable *publisher, Notification_ptr notification)
514{
515 const molecule * const _molecule = getMolecule(MolIndex.get());
516 if (publisher == dynamic_cast<const Observable*>(_molecule)){
517 // notofication from atom
518#ifdef LOG_OBSERVER
519 observerLog().addMessage() << "++ Update of Observer "<< observerLog().getName(static_cast<Observer *>(this))
520 << " received notification from molecule " << _molecule->getId() << " for channel "
521 << notification->getChannelNo() << ".";
522#endif
523 switch (notification->getChannelNo()) {
524 case molecule::AtomInserted:
525 {
526 const atomId_t _id = _molecule->lastChangedAtomId();
527 #ifdef LOG_OBSERVER
528 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+" has been inserted.";
529 #endif
530 emit AtomInserted(_id);
531 emit TesselationHullChanged();
532 emit BoundingBoxChanged();
533 break;
534 }
535 case World::AtomRemoved:
536 {
537 const atomId_t _id = _molecule->lastChangedAtomId();
538 #ifdef LOG_OBSERVER
539 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+" has been removed.";
540 #endif
541 emit AtomRemoved(_id);
542 emit TesselationHullChanged();
543 emit BoundingBoxChanged();
544 break;
545 }
546 case molecule::AtomMoved:
547 {
548 #ifdef LOG_OBSERVER
549 const atomId_t _id = _molecule->lastChangedAtomId();
550 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+" has been inserted.";
551 #endif
552 emit TesselationHullChanged();
553 emit BoundingBoxChanged();
554 break;
555 }
556 case molecule::IndexChanged:
557 {
558 #ifdef LOG_OBSERVER
559 const atomId_t _id = _molecule->lastChangedAtomId();
560 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+"'s index has changed.";
561 #endif
562 emit IdChanged();
563 break;
564 }
565 default:
566 break;
567 }
568 }else{
569 // notification from world
570#ifdef LOG_OBSERVER
571 observerLog().addMessage() << "++ Update of Observer "<< observerLog().getName(static_cast<Observer *>(this))
572 << " received notification from world for channel "
573 << notification->getChannelNo() << ".";
574#endif
575 switch (notification->getChannelNo()) {
576 case World::SelectionChanged:
577 emit IsSelectedChanged();
578 break;
579 default:
580 break;
581 }
582 }
583}
584
585void GLMoleculeObject_molecule::initialize(QGLView *view, QGLPainter *painter)
586{
587 // Initialize all of the mesh objects that we have as children.
588 if (m_visible) {
589 GLMoleculeObject::initialize(view, painter);
590 } else {
591 foreach (QObject *obj, children()) {
592 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
593 if (meshobj)
594 meshobj->initialize(view, painter);
595 }
596 }
597}
598
599void GLMoleculeObject_molecule::draw(QGLPainter *painter, const QVector4D &cameraPlane)
600{
601 // draw either molecule's mesh or all atoms and bonds
602 if (m_visible) {
603 resetTesselationHull();
604
605 painter->modelViewMatrix().push();
606
607 // Apply the material and effect to the painter.
608 QGLMaterial *material;
609 if (m_hovering)
610 material = m_hoverMaterial;
611 else if (m_selected)
612 material = m_selectionMaterial;
613 else
614 material = m_material;
615
616 ASSERT(material, "GLMoleculeObject::draw: chosen material is NULL");
617
618 painter->setColor(material->diffuseColor());
619 painter->setFaceMaterial(QGL::AllFaces, material);
620 if (m_effect)
621 painter->setUserEffect(m_effect);
622 else
623 painter->setStandardEffect(QGL::LitMaterial);
624
625 // Mark the object for object picking purposes.
626 int prevObjectId = painter->objectPickId();
627 if (m_objectId != -1)
628 painter->setObjectPickId(m_objectId);
629
630 m_mesh[0]->draw(painter);
631
632 // Turn off the user effect, if present.
633 if (m_effect)
634 painter->setStandardEffect(QGL::LitMaterial);
635
636 // Revert to the previous object identifier.
637 painter->setObjectPickId(prevObjectId);
638
639 // Restore the modelview matrix.
640 painter->modelViewMatrix().pop();
641
642 // GLMoleculeObject::draw(painter, cameraPlane);
643 } else {
644 // Draw all of the mesh objects that we have as children.
645 foreach (QObject *obj, children()) {
646 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
647 if (meshobj)
648 meshobj->draw(painter, cameraPlane);
649 }
650
651 // update bounding box prior to selection
652 resetBoundingBox();
653
654 painter->modelViewMatrix().push();
655 painter->modelViewMatrix().translate(m_position);
656 if (m_rotationAngle != 0.0f)
657 painter->modelViewMatrix().rotate(m_rotationAngle, m_rotationVector);
658 if ((m_scaleX != 1.0f) || (m_scaleY != 1.0f) || (m_scaleZ != 1.0f))
659 painter->modelViewMatrix().scale(m_scaleX, m_scaleY, m_scaleZ);
660
661 // Draw a box around the mesh, if selected.
662 if (m_selected)
663 drawSelectionBox(painter);
664
665 // Restore the modelview matrix.
666 painter->modelViewMatrix().pop();
667 }
668}
669
670/** Adds an atom of this molecule to the scene.
671 *
672 * @param _atom atom to add
673 */
674void GLMoleculeObject_molecule::atomInserted(const atomId_t _id)
675{
676 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomInserted for atom "+toString(_id)+".");
677
678 GLMoleculeObject_atom *atomObject = new GLMoleculeObject_atom(GLMoleculeObject::meshSphere, this, _id);
679 ASSERT( atomObject != NULL,
680 "GLMoleculeObject_molecule::atomInserted - could not create atom object for "+toString(_id));
681 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
682 ASSERT(iter == AtomsinSceneMap.end(),
683 "GLMoleculeObject_molecule::atomInserted - same atom with id "+toString(_id)+" added again.");
684 AtomsinSceneMap.insert( make_pair(_id, atomObject) );
685
686 qRegisterMetaType<atomId_t>("atomId_t");
687 qRegisterMetaType<bond::ptr>("bond::ptr");
688 qRegisterMetaType<GLMoleculeObject_bond::SideOfBond>("GLMoleculeObject_bond::SideOfBond");
689 connect (atomObject, SIGNAL(clicked(atomId_t)), this, SIGNAL(atomClicked(atomId_t)));
690 connect (atomObject, SIGNAL(changed()), this, SIGNAL(changed()));
691 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
692 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
693 connect (atomObject, SIGNAL(selectionChanged()), this, SIGNAL(changed()));
694// connect (atomObject, SIGNAL(bondsChanged()), this, SLOT(bondInserted(const atomId_t, const atomId_t, const GLMoleculeObject_bond::SideOfBond)));
695 connect (atomObject, SIGNAL(BondsInserted(const atomId_t, const atomId_t, const GLMoleculeObject_bond::SideOfBond)), this, SLOT(bondInserted(const atomId_t, const atomId_t, const GLMoleculeObject_bond::SideOfBond)));
696 connect (atomObject, SIGNAL(BondsRemoved(const atomId_t, const atomId_t)), this, SLOT(bondRemoved(const atomId_t, const atomId_t)));
697 connect (atomObject, SIGNAL(indexChanged(GLMoleculeObject_atom*, const atomId_t, const atomId_t)), this, SLOT(changeAtomId(GLMoleculeObject_atom*, const atomId_t, const atomId_t)));
698
699 if (m_objectId == -1)
700 setObjectId(_id);
701
702 // add all bonds
703 const atom * const Walker = const_cast<const World &>(World::getInstance()).
704 getAtom(AtomById(_id));
705 if (Walker != NULL)
706 addAtomBonds(Walker);
707 else
708 ELOG(1, "GLMoleculeObject_atom disappeared while about to add bonds.");
709
710 emit changeOccured();
711}
712
713/** Removes an atom of this molecule from the scene.
714 *
715 * We just the id as the atom might have already been destroyed.
716 *
717 * @param _id id of atom to remove
718 */
719void GLMoleculeObject_molecule::atomRemoved(const atomId_t _id)
720{
721 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomRemoved for atom "+toString(_id)+".");
722 // bonds are removed by signal coming from ~bond
723
724 if ((unsigned int)m_objectId == _id)
725 setObjectId(-1);
726
727 // remove atoms
728 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
729 ASSERT(iter != AtomsinSceneMap.end(),
730 "GLMoleculeObject_molecule::atomRemoved() - atom "+toString(_id)+" not on display.");
731 GLMoleculeObject_atom *atomObject = iter->second;
732 AtomsinSceneMap.erase(iter);
733 atomObject->disconnect();
734 delete atomObject;
735
736 emit changeOccured();
737}
738
739void GLMoleculeObject_molecule::hoverChangedSignalled(GLMoleculeObject *ob)
740{
741 // Find the atom, ob corresponds to.
742 hoverAtomId = -1;
743 GLMoleculeObject_atom *atomObject = dynamic_cast<GLMoleculeObject_atom *>(ob);
744 if (atomObject){
745 for (AtomNodeMap::iterator iter = AtomsinSceneMap.begin();iter != AtomsinSceneMap.end(); ++ iter){
746 if (iter->second == atomObject)
747 hoverAtomId = iter->first;
748 }
749
750 // Propagate signal.
751 emit hoverChanged(hoverAtomId);
752 } else {
753 // Find the atom, ob corresponds to.
754 GLMoleculeObject_molecule *moleculeObject = dynamic_cast<GLMoleculeObject_molecule *>(ob);
755 if (moleculeObject == this){
756 // Propagate signal.
757 emit hoverChanged(MolIndex.get(), 0);
758 }
759 }
760}
761
762
763/** Helper function to get bond ids in the correct order for BondNodeMap.
764 *
765 * \return pair of ids in correct order.
766 */
767GLMoleculeObject_molecule::BondIds GLMoleculeObject_molecule::getBondIds(
768 const bond::ptr _bond,
769 const enum GLMoleculeObject_bond::SideOfBond _side)
770{
771 BondIds ids;
772 switch (_side) {
773 case GLMoleculeObject_bond::left:
774 ids = std::make_pair(_bond->leftatom->getId(), _bond->rightatom->getId());
775 break;
776 case GLMoleculeObject_bond::right:
777 ids = std::make_pair(_bond->rightatom->getId(), _bond->leftatom->getId());
778 break;
779 }
780 return ids;
781}
782
783/** Adds a bond to the scene.
784 *
785 * @param _bond bond to add
786 * @param side which side of the bond (left or right)
787 */
788void GLMoleculeObject_molecule::bondInserted(
789 const atomId_t _left, const atomId_t _right,
790 const enum GLMoleculeObject_bond::SideOfBond _side)
791{
792 LOG(3, "INFO: GLWorldScene::bondInserted() - Adding bond "+toString(_left)
793 +toString(_right)+".");
794 //LOG(4, "INFO: Currently present bonds " << BondsinSceneMap << ".");
795
796 const BondIds ids( std::make_pair(_left, _right) );
797 BondNodeMap::iterator iter = BondsinSceneMap.find(ids);
798 if (iter == BondsinSceneMap.end()) {
799 GLMoleculeObject_bond * bondObject =
800 new GLMoleculeObject_bond(GLMoleculeObject::meshCylinder, this, ids, _side);
801 connect (
802 bondObject, SIGNAL(BondRemoved(const atomId_t, const atomId_t)),
803 this, SLOT(bondRemoved(const atomId_t, const atomId_t)));
804 connect (bondObject, SIGNAL(changed()), this, SIGNAL(changed()));
805 BondsinSceneMap.insert( make_pair(ids, bondObject) );
806 // BondIdsinSceneMap.insert( Leftids );
807 } else {
808 iter->second->resetPosition();
809 iter->second->resetWidth();
810 }
811 emit changeOccured();
812}
813
814/** Removes a bond from the scene.
815 *
816 * @param _bond bond to remove
817 */
818void GLMoleculeObject_molecule::bondRemoved(const atomId_t leftnr, const atomId_t rightnr)
819{
820 LOG(3, "INFO: GLWorldScene::bondRemoved() - Removing bond between "+toString(leftnr)+" and "+toString(rightnr)+".");
821 {
822 // left bond
823 const BondIds Leftids( make_pair(leftnr, rightnr) );
824 BondNodeMap::iterator leftiter = BondsinSceneMap.find( Leftids );
825 ASSERT(leftiter != BondsinSceneMap.end(),
826 "GLWorldScene::bondRemoved() - bond "+toString(leftnr)+"-"
827 +toString(rightnr)+" not on display.");
828 GLMoleculeObject_bond *bondObject = leftiter->second;
829 bondObject->disconnect();
830 BondsinSceneMap.erase(leftiter);
831 delete bondObject; // is done by signal from bond itself
832 //LOG(4, "INFO: Still present bonds " << BondsinSceneMap << ".");
833 }
834
835 emit changeOccured();
836}
837
838void GLMoleculeObject_molecule::setVisible(bool value)
839{
840 // first update the mesh if we are going to be visible now
841 if (value)
842 updateTesselationHull();
843 // then emit onward
844 GLMoleculeObject::setVisible(value);
845}
846
847std::ostream &operator<<(std::ostream &ost, const GLMoleculeObject_molecule::BondIds &t)
848{
849 ost << t.first << "," << t.second;
850 return ost;
851}
852
853void GLMoleculeObject_molecule::wasClicked()
854{
855 LOG(4, "INFO: GLMoleculeObject_molecule: atom " << MolIndex.get() << " has been clicked");
856 emit moleculeClicked(MolIndex.get());
857}
858
859void GLMoleculeObject_molecule::changeAtomId(
860 GLMoleculeObject_atom *ob,
861 const atomId_t oldId,
862 const atomId_t newId)
863{
864 LOG(3, "INFO: GLMoleculeObject_molecule - change atom id " << oldId << " to " << newId << ".");
865
866 // Remove from map.
867 AtomNodeMap::iterator iter = AtomsinSceneMap.find(oldId);
868 ASSERT(iter != AtomsinSceneMap.end(),
869 "GLMoleculeObject_molecule::changeAtomId() - atom with old id "+toString(oldId)+" not on display.");
870 ASSERT(iter->second == ob,
871 "GLMoleculeObject_molecule::changeAtomId() - atom with id "
872 +toString(oldId)+" does not match with object in AtomsinSceneMap.");
873 AtomsinSceneMap.erase(iter);
874
875 // Reinsert with new id.
876 {
877 AtomNodeMap::iterator iter = AtomsinSceneMap.find(newId);
878 ASSERT(iter == AtomsinSceneMap.end(),
879 "GLMoleculeObject_molecule::changeAtomId() - atom with new id "+toString(newId)+" already known.");
880 }
881 AtomsinSceneMap.insert( make_pair(newId, ob) );
882}
883
884const molecule * const GLMoleculeObject_molecule::getMolecule(const moleculeId_t _id)
885{
886 const molecule * const mol = const_cast<const World &>(World::getInstance()).
887 getMolecule(MoleculeById(_id));
888 return mol;
889}
Note: See TracBrowser for help on using the repository browser.