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

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

FIX: GLMoleculeObject_molecule::subjectKilled() should not call deactivateObserver().

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