source: src/UIElements/Views/Qt4/Qt3D/GLMoleculeObject_molecule.cpp@ 015f8c

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

QtMainWindow uses QtSelectionChangedAgent.

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