source: src/UIElements/Views/Qt4/Qt3D/GLMoleculeObject_molecule.cpp@ 9c259e

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

FIX: GLWorldScene/View capture all missed signals for each GLMoleculeObject_molecule.

  • Taking note of subscribed molecules to sign Off on GLWorldView's destruct.
  • GLWorldView::recieveNotification() is checking for whether molecule actually exists still.
  • Property mode set to 100644
File size: 25.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 * 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 "CodePatterns/Assert.hpp"
48#include "CodePatterns/Log.hpp"
49#include "CodePatterns/Observer/Notification.hpp"
50#include "CodePatterns/Observer/ObserverLog.hpp"
51
52#include "Atom/atom.hpp"
53#include "molecule.hpp"
54#include "Descriptors/AtomIdDescriptor.hpp"
55#include "Descriptors/MoleculeIdDescriptor.hpp"
56#include "Element/element.hpp"
57#include "LinearAlgebra/Vector.hpp"
58#include "LinkedCell/PointCloudAdaptor.hpp"
59#include "LinkedCell/linkedcell.hpp"
60#include "Tesselation/tesselation.hpp"
61#include "Tesselation/BoundaryLineSet.hpp"
62#include "Tesselation/BoundaryTriangleSet.hpp"
63#include "Tesselation/CandidateForTesselation.hpp"
64#include "Atom/TesselPoint.hpp"
65#include "World.hpp"
66
67#include "GLMoleculeObject_atom.hpp"
68
69static QGLSceneNode *createMoleculeMesh(const moleculeId_t molid, QObject *parent)
70{
71 const molecule *molref = const_cast<const World &>(World::getInstance()).
72 getMolecule(MoleculeById(molid));
73 if (molref == NULL) {
74 ELOG(1, "Could not createMoleculeMesh, molecule with id " << molid << " already gone.");
75 return NULL;
76 }
77// Shape shape = molref->getBoundingSphere();
78 double minradius = 2.; // TODO: set to maximum bond length value
79 LOG(3, "DEBUG: Molecule fits into sphere of radius " << minradius);
80 // check minimum bond radius in molecule
81 double minlength = std::numeric_limits<double>::max();
82 for (molecule::const_iterator iter = molref->begin();
83 iter != molref->end(); ++iter) {
84 const BondList &ListOfBonds = (*iter)->getListOfBonds();
85 for (BondList::const_iterator bonditer = ListOfBonds.begin();
86 bonditer != ListOfBonds.end(); ++bonditer) {
87 const double bond_distance = (*bonditer)->GetDistance();
88 minlength = std::min(bond_distance, minlength);
89 }
90 }
91 minradius = std::max( std::max(minradius, minlength), 1.);
92
93 QGeometryData geo;
94 // we need at least three points for tesselation
95 if (molref->getAtomCount() >= 3) {
96 // Tesselate the points.
97 Tesselation T;
98 PointCloudAdaptor<molecule> cloud(const_cast<molecule *>(molref), molref->getName());
99 T(cloud, minradius);
100
101 // Fill the points into a Qt geometry.
102 LinkedCell_deprecated LinkedList(cloud, minradius);
103 std::map<int, int> indices;
104 std::map<int, Vector> normals;
105 int index = 0;
106 for (PointMap::const_iterator piter = T.PointsOnBoundary.begin();
107 piter != T.PointsOnBoundary.end(); ++piter) {
108 const Vector &point = piter->second->getPosition();
109 // add data to the primitive
110 geo.appendVertex(QVector3D(point[0], point[1], point[2]));
111 Vector normalvector;
112 for (LineMap::const_iterator lineiter = piter->second->lines.begin();
113 lineiter != piter->second->lines.end(); ++lineiter)
114 for (TriangleMap::const_iterator triangleiter = lineiter->second->triangles.begin();
115 triangleiter != lineiter->second->triangles.end(); ++triangleiter)
116 normalvector +=
117 triangleiter->second->NormalVector;
118 normalvector.Normalize();
119 geo.appendNormal(QVector3D(normalvector[0], normalvector[1], normalvector[2]));
120 geo.appendColor(QColor(1, 1, 1, 1));
121 geo.appendTexCoord(QVector2D(0, 0));
122 indices.insert( std::make_pair( piter->second->getNr(), index++));
123 }
124
125 // Fill the tesselated triangles into the geometry.
126 for (TriangleMap::const_iterator runner = T.TrianglesOnBoundary.begin();
127 runner != T.TrianglesOnBoundary.end(); runner++) {
128 int v[3];
129 for (size_t i=0; i<3; ++i)
130 v[i] = runner->second->endpoints[i]->getNr();
131
132 // Sort the vertices so the triangle is clockwise (relative to the normal vector).
133 Vector cross = T.PointsOnBoundary[v[1]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition();
134 cross.VectorProduct(T.PointsOnBoundary[v[2]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition());
135 if (cross.ScalarProduct(runner->second->NormalVector) > 0)
136 geo.appendIndices(indices[v[0]], indices[v[1]], indices[v[2]]);
137 else
138 geo.appendIndices(indices[v[0]], indices[v[2]], indices[v[1]]);
139 }
140 }
141
142 // Build a mesh from the geometry.
143 QGLBuilder builder;
144 builder.addTriangles(geo);
145 QGLSceneNode *mesh = builder.finalizedSceneNode();
146 return mesh;
147}
148
149GLMoleculeObject_molecule::GLMoleculeObject_molecule(QObject *parent, const moleculeId_t molid) :
150 GLMoleculeObject(createMoleculeMesh(molid, parent), parent),
151 Observer(std::string("GLMoleculeObject_molecule")+toString(molid)),
152 isBoundingBoxUptodate(true),
153 isSignedOn(false),
154 moleculeid(molid),
155 TesselationHullUptodate(true),
156 hoverAtomId(-1)
157{
158 // sign on as observer (obtain non-const instance before)
159 const molecule *_molecule = const_cast<const World &>(World::getInstance()).
160 getMolecule(MoleculeById(moleculeid));
161 if (_molecule != NULL) {
162 _molecule->signOn(this, molecule::AtomInserted);
163 _molecule->signOn(this, molecule::AtomRemoved);
164 _molecule->signOn(this, molecule::AtomMoved);
165 isSignedOn = true;
166 } else {
167 ELOG(1, "GLMoleculeObject_molecule() - added null object for not present mol id " << moleculeid);
168 }
169 /*molref->signOn(this, AtomObservable::IndexChanged);
170 molref->signOn(this, AtomObservable::PositionChanged);
171 molref->signOn(this, AtomObservable::ElementChanged);
172 molref->signOn(this, AtomObservable::BondsAdded);*/
173 setMaterial(getMaterial(1));
174 World::getInstance().signOn(this, World::SelectionChanged);
175 updateBoundingBox();
176
177 // initially, atoms and bonds should be visible
178 m_visible = false;
179
180 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
181 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
182
183 connect( this, SIGNAL(clicked()), this, SLOT(wasClicked()));
184}
185
186GLMoleculeObject_molecule::GLMoleculeObject_molecule(QGLSceneNode *mesh[], QObject *parent, const moleculeId_t molid) :
187 GLMoleculeObject(mesh, parent),
188 Observer(std::string("GLMoleculeObject_molecule")+toString(molid)),
189 isBoundingBoxUptodate(true),
190 isSignedOn(false),
191 moleculeid(molid),
192 TesselationHullUptodate(true),
193 hoverAtomId(-1)
194{
195 // sign on as observer (obtain non-const instance before)
196 const molecule *_molecule = const_cast<const World &>(World::getInstance()).
197 getMolecule(MoleculeById(moleculeid));
198 if (_molecule != NULL) {
199 _molecule->signOn(this, molecule::AtomInserted);
200 _molecule->signOn(this, molecule::AtomRemoved);
201 _molecule->signOn(this, molecule::AtomMoved);
202 isSignedOn = true;
203 } else {
204 ELOG(1, "GLMoleculeObject_molecule() - added null object for not present mol id " << moleculeid);
205 }
206 /*molref->signOn(this, AtomObservable::IndexChanged);
207 molref->signOn(this, AtomObservable::PositionChanged);
208 molref->signOn(this, AtomObservable::ElementChanged);
209 molref->signOn(this, AtomObservable::BondsAdded);*/
210 setMaterial(getMaterial(1));
211 World::getInstance().signOn(this, World::SelectionChanged);
212 updateBoundingBox();
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
220 connect( this, SIGNAL(clicked()), this, SLOT(wasClicked()));
221}
222
223GLMoleculeObject_molecule::~GLMoleculeObject_molecule()
224{
225 if (isSignedOn) {
226 const molecule *_molecule = const_cast<const World &>(World::getInstance()).
227 getMolecule(MoleculeById(moleculeid));
228 if (_molecule != NULL) {
229 _molecule->signOff(this, molecule::AtomInserted);
230 _molecule->signOff(this, molecule::AtomRemoved);
231 _molecule->signOff(this, molecule::AtomMoved);
232 } else {
233 ELOG(1, "GLMoleculeObject_molecule cannot sign off, molecule with "
234 << moleculeid << " has disappeared.");
235 }
236 }
237 /*_atom->signOff(this, AtomObservable::IndexChanged);
238 _atom->signOff(this, AtomObservable::PositionChanged);
239 _atom->signOff(this, AtomObservable::ElementChanged);
240 _atom->signOff(this, AtomObservable::BondsAdded);*/
241 World::getInstance().signOff(this, World::SelectionChanged);
242}
243
244void GLMoleculeObject_molecule::addAtomBonds(
245 const bond::ptr &_bond,
246 const GLMoleculeObject_bond::SideOfBond _side
247 )
248{
249 bool bond_present = false;
250 const BondIds ids = getBondIds(_bond, _side);
251 // check whether bond is not present already
252 bond_present = BondsinSceneMap.count(ids);
253 if (!bond_present)
254 bondInserted(_bond, _side);
255 else {
256 BondsinSceneMap[ids]->resetPosition();
257 BondsinSceneMap[ids]->resetWidth();
258 }
259}
260
261void GLMoleculeObject_molecule::addAtomBonds(
262 const atom *_atom)
263{
264 const bool atom_present = AtomsinSceneMap.count(_atom->getId());
265 const BondList &bondlist = _atom->getListOfBonds();
266 for (BondList::const_iterator bonditer = bondlist.begin();
267 (bonditer != bondlist.end()) && atom_present;
268 ++bonditer) {
269 const bond::ptr _bond = *bonditer;
270 // check if OtherAtom's sphere is already present
271 const atom *OtherAtom = _bond->GetOtherAtom(_atom);
272 const bool otheratom_present = AtomsinSceneMap.count(OtherAtom->getId());
273 if (otheratom_present && atom_present) {
274 const GLMoleculeObject_bond::SideOfBond side = (_bond->leftatom == _atom) ?
275 GLMoleculeObject_bond::left : GLMoleculeObject_bond::right;
276 const GLMoleculeObject_bond::SideOfBond otherside = (_bond->leftatom == _atom) ?
277 GLMoleculeObject_bond::right : GLMoleculeObject_bond::left;
278 addAtomBonds(_bond, side);
279 addAtomBonds(_bond, otherside);
280 }
281 }
282}
283
284void GLMoleculeObject_molecule::updateBoundingBox()
285{
286 isBoundingBoxUptodate = true;
287 const molecule * const _molecule = const_cast<const World &>(World::getInstance()).
288 getMolecule(MoleculeById(moleculeid));
289 if (_molecule == NULL) {
290 ELOG(1, "GLMoleculeObject_molecule cannot updateBoundingBox, molecule with "
291 << moleculeid << " has disappeared.");
292 return;
293 }
294 Shape shape = _molecule->getBoundingSphere();
295 Vector v = shape.getCenter();
296 setPosition(QVector3D(v[0], v[1], v[2]));
297 setScale(shape.getRadius() + 0.3); // getBoundingShape() only sees atoms as points, so make the box a bit bigger
298}
299
300void GLMoleculeObject_molecule::update(Observable *publisher)
301{
302#ifdef LOG_OBSERVER
303 const molecule *_mol = static_cast<molecule *>(publisher);
304 observerLog().addMessage() << "++ Update of Observer " << observerLog().getName(static_cast<Observer *>(this)) << " from molecule "+toString(_mol->getId())+".";
305#endif
306}
307
308void GLMoleculeObject_molecule::subjectKilled(Observable *publisher)
309{
310 isSignedOn = false;
311}
312
313void GLMoleculeObject_molecule::recieveNotification(Observable *publisher, Notification_ptr notification)
314{
315 const molecule * const _molecule = const_cast<const World &>(World::getInstance()).
316 getMolecule(MoleculeById(moleculeid));
317 if (publisher == dynamic_cast<const Observable*>(_molecule)){
318 // notofication from atom
319#ifdef LOG_OBSERVER
320 observerLog().addMessage() << "++ Update of Observer "<< observerLog().getName(static_cast<Observer *>(this))
321 << " received notification from molecule " << _molecule->getId() << " for channel "
322 << notification->getChannelNo() << ".";
323#endif
324 switch (notification->getChannelNo()) {
325 case molecule::AtomInserted:
326 {
327 const atomId_t _id = _molecule->lastChanged()->getId();
328 #ifdef LOG_OBSERVER
329 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+" has been inserted.";
330 #endif
331 QMetaObject::invokeMethod(this, // pointer to a QObject
332 "atomInserted", // member name (no parameters here)
333 Qt::QueuedConnection, // connection type
334 Q_ARG(atomId_t, _id)); // parameters
335 break;
336 }
337 case World::AtomRemoved:
338 {
339 const atomId_t _id = _molecule->lastChanged()->getId();
340 #ifdef LOG_OBSERVER
341 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+" has been removed.";
342 #endif
343 QMetaObject::invokeMethod(this, // pointer to a QObject
344 "atomRemoved", // member name (no parameters here)
345 Qt::QueuedConnection, // connection type
346 Q_ARG(atomId_t, _id)); // parameters
347 break;
348 }
349 case molecule::AtomMoved:
350 {
351 #ifdef LOG_OBSERVER
352 const atomId_t _id = _molecule->lastChanged()->getId();
353 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+" has been inserted.";
354 #endif
355 TesselationHullUptodate = false;
356 isBoundingBoxUptodate = false;
357 break;
358 }
359 default:
360 break;
361 }
362 }else{
363 // notification from world
364#ifdef LOG_OBSERVER
365 observerLog().addMessage() << "++ Update of Observer "<< observerLog().getName(static_cast<Observer *>(this))
366 << " received notification from world for channel "
367 << notification->getChannelNo() << ".";
368#endif
369 switch (notification->getChannelNo()) {
370 case World::SelectionChanged:
371 if (_molecule != NULL) {
372 setSelected(World::getInstance().isSelected(_molecule));
373 } else {
374 ELOG(1, "GLMoleculeObject_molecule cannot change selection, molecule with "
375 << moleculeid << " has disappeared.");
376 }
377 break;
378 default:
379 break;
380 }
381 }
382}
383
384void GLMoleculeObject_molecule::initialize(QGLView *view, QGLPainter *painter)
385{
386 // Initialize all of the mesh objects that we have as children.
387 if (m_visible) {
388 GLMoleculeObject::initialize(view, painter);
389 } else {
390 foreach (QObject *obj, children()) {
391 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
392 if (meshobj)
393 meshobj->initialize(view, painter);
394 }
395 }
396}
397
398void GLMoleculeObject_molecule::draw(QGLPainter *painter, const QVector4D &cameraPlane)
399{
400 // draw either molecule's mesh or all atoms and bonds
401 if (m_visible) {
402 updateTesselationHull();
403
404 painter->modelViewMatrix().push();
405
406 // Apply the material and effect to the painter.
407 QGLMaterial *material;
408 if (m_hovering)
409 material = m_hoverMaterial;
410 else if (m_selected)
411 material = m_selectionMaterial;
412 else
413 material = m_material;
414
415 ASSERT(material, "GLMoleculeObject::draw: chosen material is NULL");
416
417 painter->setColor(material->diffuseColor());
418 painter->setFaceMaterial(QGL::AllFaces, material);
419 if (m_effect)
420 painter->setUserEffect(m_effect);
421 else
422 painter->setStandardEffect(QGL::LitMaterial);
423
424 // Mark the object for object picking purposes.
425 int prevObjectId = painter->objectPickId();
426 if (m_objectId != -1)
427 painter->setObjectPickId(m_objectId);
428
429 m_mesh[0]->draw(painter);
430
431 // Turn off the user effect, if present.
432 if (m_effect)
433 painter->setStandardEffect(QGL::LitMaterial);
434
435 // Revert to the previous object identifier.
436 painter->setObjectPickId(prevObjectId);
437
438 // Restore the modelview matrix.
439 painter->modelViewMatrix().pop();
440
441 // GLMoleculeObject::draw(painter, cameraPlane);
442 } else {
443 // Draw all of the mesh objects that we have as children.
444 foreach (QObject *obj, children()) {
445 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
446 if (meshobj)
447 meshobj->draw(painter, cameraPlane);
448 }
449
450 // update bounding box prior to selection
451 if (!isBoundingBoxUptodate)
452 updateBoundingBox();
453
454 painter->modelViewMatrix().push();
455 painter->modelViewMatrix().translate(m_position);
456 if (m_rotationAngle != 0.0f)
457 painter->modelViewMatrix().rotate(m_rotationAngle, m_rotationVector);
458 if ((m_scaleX != 1.0f) || (m_scaleY != 1.0f) || (m_scaleZ != 1.0f))
459 painter->modelViewMatrix().scale(m_scaleX, m_scaleY, m_scaleZ);
460
461 // Draw a box around the mesh, if selected.
462 if (m_selected)
463 drawSelectionBox(painter);
464
465 // Restore the modelview matrix.
466 painter->modelViewMatrix().pop();
467 }
468}
469
470/** Adds an atom of this molecule to the scene.
471 *
472 * @param _atom atom to add
473 */
474void GLMoleculeObject_molecule::atomInserted(const atomicNumber_t _id)
475{
476 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomInserted for atom "+toString(_id)+".");
477
478 TesselationHullUptodate = false;
479 isBoundingBoxUptodate = false;
480
481 GLMoleculeObject_atom *atomObject = new GLMoleculeObject_atom(GLMoleculeObject::meshSphere, this, _id);
482 ASSERT( atomObject != NULL,
483 "GLMoleculeObject_molecule::atomInserted - could not create atom object for "+toString(_id));
484 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
485 ASSERT(iter == AtomsinSceneMap.end(),
486 "GLMoleculeObject_molecule::atomInserted - same atom with id "+toString(_id)+" added again.");
487 AtomsinSceneMap.insert( make_pair(_id, atomObject) );
488
489 qRegisterMetaType<atomId_t>("atomId_t");
490 qRegisterMetaType<bond::ptr>("bond::ptr");
491 qRegisterMetaType<GLMoleculeObject_bond::SideOfBond>("GLMoleculeObject_bond::SideOfBond");
492 connect (atomObject, SIGNAL(clicked(atomId_t)), this, SIGNAL(atomClicked(atomId_t)));
493 connect (atomObject, SIGNAL(changed()), this, SIGNAL(changed()));
494 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
495 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
496 connect (atomObject, SIGNAL(selectionChanged()), this, SIGNAL(changed()));
497 connect (atomObject, SIGNAL(BondsInserted(const bond::ptr , const GLMoleculeObject_bond::SideOfBond)), this, SLOT(bondInserted(const bond::ptr , const GLMoleculeObject_bond::SideOfBond)));
498 connect (atomObject, SIGNAL(indexChanged(GLMoleculeObject_atom*, int, int)), this, SLOT(changeAtomId(GLMoleculeObject_atom*, int, int)));
499
500 isBoundingBoxUptodate = false;
501
502 if (m_objectId == -1)
503 setObjectId(_id);
504
505 // add all bonds
506 const atom * const Walker = const_cast<const World &>(World::getInstance()).
507 getAtom(AtomById(_id));
508 if (Walker != NULL)
509 addAtomBonds(Walker);
510 else
511 ELOG(1, "GLMoleculeObject_atom disappeared while about to add bonds.");
512
513 emit changeOccured();
514}
515
516/** Removes an atom of this molecule from the scene.
517 *
518 * We just the id as the atom might have already been destroyed.
519 *
520 * @param _id id of atom to remove
521 */
522void GLMoleculeObject_molecule::atomRemoved(const atomicNumber_t _id)
523{
524 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomRemoved for atom "+toString(_id)+".");
525 // bonds are removed by signal coming from ~bond
526
527 TesselationHullUptodate = false;
528 isBoundingBoxUptodate = false;
529
530 if ((unsigned int)m_objectId == _id)
531 setObjectId(-1);
532
533 // remove atoms
534 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
535 ASSERT(iter != AtomsinSceneMap.end(),
536 "GLWorldScene::atomRemoved() - atom "+toString(_id)+" not on display.");
537 GLMoleculeObject_atom *atomObject = iter->second;
538 AtomsinSceneMap.erase(iter);
539 atomObject->disconnect();
540 delete atomObject;
541
542 isBoundingBoxUptodate = false;
543
544 emit changeOccured();
545}
546
547void GLMoleculeObject_molecule::hoverChangedSignalled(GLMoleculeObject *ob)
548{
549 // Find the atom, ob corresponds to.
550 hoverAtomId = -1;
551 GLMoleculeObject_atom *atomObject = dynamic_cast<GLMoleculeObject_atom *>(ob);
552 if (atomObject){
553 for (AtomNodeMap::iterator iter = AtomsinSceneMap.begin();iter != AtomsinSceneMap.end(); ++ iter){
554 if (iter->second == atomObject)
555 hoverAtomId = iter->first;
556 }
557
558 // Propagate signal.
559 emit hoverChanged(hoverAtomId);
560 } else {
561 // Find the atom, ob corresponds to.
562 GLMoleculeObject_molecule *moleculeObject = dynamic_cast<GLMoleculeObject_molecule *>(ob);
563 if (moleculeObject == this){
564 // Propagate signal.
565 emit hoverChanged(moleculeid, 0);
566 }
567 }
568}
569
570
571/** Helper function to get bond ids in the correct order for BondNodeMap.
572 *
573 * \return pair of ids in correct order.
574 */
575GLMoleculeObject_molecule::BondIds GLMoleculeObject_molecule::getBondIds(
576 const bond::ptr _bond,
577 const enum GLMoleculeObject_bond::SideOfBond _side)
578{
579 BondIds ids;
580 switch (_side) {
581 case GLMoleculeObject_bond::left:
582 ids = std::make_pair(_bond->leftatom->getId(), _bond->rightatom->getId());
583 break;
584 case GLMoleculeObject_bond::right:
585 ids = std::make_pair(_bond->rightatom->getId(), _bond->leftatom->getId());
586 break;
587 }
588 return ids;
589}
590
591/** Adds a bond to the scene.
592 *
593 * @param _bond bond to add
594 * @param side which side of the bond (left or right)
595 */
596void GLMoleculeObject_molecule::bondInserted(const bond::ptr _bond, const enum GLMoleculeObject_bond::SideOfBond _side)
597{
598 LOG(3, "INFO: GLWorldScene::bondInserted() - Adding bond "+toString(*_bond)+".");
599 //LOG(4, "INFO: Currently present bonds " << BondsinSceneMap << ".");
600
601 const BondIds ids = getBondIds(_bond, _side);
602 BondNodeMap::iterator iter = BondsinSceneMap.find(ids);
603 if (iter == BondsinSceneMap.end()) {
604 GLMoleculeObject_bond * bondObject =
605 new GLMoleculeObject_bond(GLMoleculeObject::meshCylinder, this, _bond, _side);
606 connect (
607 bondObject, SIGNAL(BondRemoved(const atomId_t, const atomId_t)),
608 this, SLOT(bondRemoved(const atomId_t, const atomId_t)));
609 connect (bondObject, SIGNAL(changed()), this, SIGNAL(changed()));
610 BondsinSceneMap.insert( make_pair(ids, bondObject) );
611 // BondIdsinSceneMap.insert( Leftids );
612 } else {
613 iter->second->resetPosition();
614 iter->second->resetWidth();
615 }
616 emit changeOccured();
617}
618
619/** Removes a bond from the scene.
620 *
621 * @param _bond bond to remove
622 */
623void GLMoleculeObject_molecule::bondRemoved(const atomId_t leftnr, const atomId_t rightnr)
624{
625 LOG(3, "INFO: GLWorldScene::bondRemoved() - Removing bond between "+toString(leftnr)+" and "+toString(rightnr)+".");
626 {
627 // left bond
628 const BondIds Leftids( make_pair(leftnr, rightnr) );
629 BondNodeMap::iterator leftiter = BondsinSceneMap.find( Leftids );
630 ASSERT(leftiter != BondsinSceneMap.end(),
631 "GLWorldScene::bondRemoved() - bond "+toString(leftnr)+"-"
632 +toString(rightnr)+" not on display.");
633 GLMoleculeObject_bond *bondObject = leftiter->second;
634 bondObject->disconnect();
635 BondsinSceneMap.erase(leftiter);
636 delete bondObject; // is done by signal from bond itself
637 //LOG(4, "INFO: Still present bonds " << BondsinSceneMap << ".");
638 }
639
640 emit changeOccured();
641}
642
643void GLMoleculeObject_molecule::setVisible(bool value)
644{
645 // first update the mesh if we are going to be visible now
646 if (value)
647 updateTesselationHull();
648 // then emit onward
649 GLMoleculeObject::setVisible(value);
650}
651
652void GLMoleculeObject_molecule::updateTesselationHull()
653{
654 if (!TesselationHullUptodate) {
655 updateMesh(createMoleculeMesh(moleculeid, parent()));
656 TesselationHullUptodate = true;
657 }
658}
659
660std::ostream &operator<<(std::ostream &ost, const GLMoleculeObject_molecule::BondIds &t)
661{
662 ost << t.first << "," << t.second;
663 return ost;
664}
665
666void GLMoleculeObject_molecule::wasClicked()
667{
668 LOG(4, "INFO: GLMoleculeObject_molecule: atom " << moleculeid << " has been clicked");
669 emit moleculeClicked(moleculeid);
670}
671
672void GLMoleculeObject_molecule::changeAtomId(GLMoleculeObject_atom *ob, int oldId, int newId)
673{
674 LOG(3, "INFO: GLMoleculeObject_molecule - change atom id " << oldId << " to " << newId << ".");
675
676 // Remove from map.
677 AtomNodeMap::iterator iter = AtomsinSceneMap.find(oldId);
678 ASSERT(iter != AtomsinSceneMap.end(),
679 "GLMoleculeObject_molecule::changeAtomId() - atom with old id "+toString(oldId)+" not on display.");
680 ASSERT(iter->second == ob,
681 "GLMoleculeObject_molecule::changeAtomId() - atom with id "
682 +toString(oldId)+" does not match with object in AtomsinSceneMap.");
683 AtomsinSceneMap.erase(iter);
684
685 // Reinsert with new id.
686 {
687 AtomNodeMap::iterator iter = AtomsinSceneMap.find(newId);
688 ASSERT(iter == AtomsinSceneMap.end(),
689 "GLMoleculeObject_molecule::changeAtomId() - atom with new id "+toString(newId)+" already known.");
690 }
691 AtomsinSceneMap.insert( make_pair(newId, ob) );
692}
Note: See TracBrowser for help on using the repository browser.