source: src/UIElements/Views/Qt4/Qt3D/GLWorldView.cpp@ b3a33d

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

Removed init() and signal WorldSelectionChanged() from GLWorldScene.

  • Property mode set to 100644
File size: 28.6 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 * 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 * GLWorldView.cpp
26 *
27 * Created on: Aug 1, 2010
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "GLWorldView.hpp"
37
38#include <Qt/qevent.h>
39#include <Qt/qaction.h>
40#include <QtGui/QMenu>
41#include <QtGui/QToolBar>
42#include <QtGui/QToolButton>
43#include <Qt/qtimer.h>
44#include <Qt/qsettings.h>
45#include <Qt3D/qglbuilder.h>
46#include <Qt3D/qglscenenode.h>
47#include <Qt3D/qglsphere.h>
48#include <Qt3D/qglcylinder.h>
49#include <Qt3D/qglcube.h>
50
51#include "GLWorldScene.hpp"
52
53#include "CodePatterns/MemDebug.hpp"
54
55#include "Atom/AtomObserver.hpp"
56#include "Atom/atom_observable.hpp"
57#include "Box.hpp"
58#include "CodePatterns/Log.hpp"
59#include "CodePatterns/Observer/Notification.hpp"
60#include "CodePatterns/Observer/ObserverLog.hpp"
61#include "Descriptors/MoleculeIdDescriptor.hpp"
62#include "molecule.hpp"
63#include "Shapes/ShapeRegistry.hpp"
64#include "World.hpp"
65#include "WorldTime.hpp"
66
67GLWorldView::GLWorldView(QWidget *parent)
68 : QGLView(parent), Observer("GLWorldView"), worldscene(NULL), changesPresent(false), needsRedraw(false)
69{
70 worldscene = new GLWorldScene(this);
71
72 setOption(QGLView::ObjectPicking, true);
73 setOption(QGLView::CameraNavigation, false);
74 setFocusPolicy(Qt::StrongFocus);
75 setCameraControlMode(Rotate);
76 defaultEyeSeparation = 4.0;
77
78 createDomainBox();
79 createDreiBein();
80 //changeMaterials(false);
81
82 qRegisterMetaType<atomId_t>("atomId_t");
83 qRegisterMetaType<moleculeId_t>("moleculeId_t");
84
85 connect(this, SIGNAL(ShapeAdded()), worldscene, SLOT(addShape()));
86 connect(this, SIGNAL(ShapeRemoved()), worldscene, SLOT(removeShape()));
87 connect(this, SIGNAL(TimeChanged()), worldscene, SIGNAL(updated()));
88 connect(worldscene, SIGNAL(changeOccured()), this, SLOT(changeSignalled()));
89 connect(worldscene, SIGNAL(changed()), this, SIGNAL(changed()));
90 connect(worldscene, SIGNAL(hoverChanged(const atomId_t)), this, SLOT(sceneHoverSignalled(const atomId_t)));
91 connect(worldscene, SIGNAL(hoverChanged(const moleculeId_t, int)), this, SLOT(sceneHoverSignalled(const moleculeId_t, int)));
92 connect(this, SIGNAL(atomRemoved(const moleculeId_t, const atomId_t)), worldscene, SLOT(atomRemoved(const moleculeId_t, const atomId_t)), Qt::DirectConnection);
93 connect(this, SIGNAL(atomInserted(const moleculeId_t, const atomId_t)), worldscene, SLOT(atomInserted(const moleculeId_t, const atomId_t)), Qt::DirectConnection);
94 connect(this, SIGNAL(moleculeRemoved(const moleculeId_t)), worldscene, SLOT(moleculeRemoved(const moleculeId_t)), Qt::DirectConnection);
95 connect(this, SIGNAL(moleculeInserted(const moleculeId_t)), worldscene, SLOT(moleculeInserted(const moleculeId_t)), Qt::DirectConnection);
96 //connect(this, SIGNAL(changed()), this, SLOT(updateGL()));
97 connect(this, SIGNAL(changed()), this, SLOT(sceneChangeSignalled()));
98 connect(this, SIGNAL(moleculesVisibilityChanged(const moleculeId_t,bool)), worldscene, SLOT(moleculesVisibilityChanged(const moleculeId_t,bool)));
99
100 // sign on to changes in the world
101 World::getInstance().signOn(this);
102 World::getInstance().signOn(this, World::MoleculeInserted);
103 World::getInstance().signOn(this, World::SelectionChanged);
104 WorldTime::getInstance().signOn(this, WorldTime::TimeChanged);
105 AtomObserver::getInstance().signOn(this, AtomObservable::PositionChanged);
106
107 ShapeRegistry::getInstance().signOn(this);
108 ShapeRegistry::getInstance().signOn(this, ShapeRegistry::ShapeInserted);
109 ShapeRegistry::getInstance().signOn(this, ShapeRegistry::ShapeRemoved);
110 ShapeRegistry::getInstance().signOn(this, ShapeRegistry::SelectionChanged);
111
112 redrawTimer = new QTimer(this);
113}
114
115GLWorldView::~GLWorldView()
116{
117 // remove me from all observed molecules
118 for (ObservedMolecules_t::iterator iter = ObservedMolecules.begin();
119 !ObservedMolecules.empty();
120 iter = ObservedMolecules.begin())
121 signOffFromMolecule(*iter);
122
123 QSettings settings;
124 settings.beginGroup("WorldView");
125 settings.setValue("domainBoxEnabled", (meshDomainBox->options() & QGLSceneNode::HideNode) == 0);
126 settings.setValue("dreiBeinEnabled", (meshDreiBein->options() & QGLSceneNode::HideNode) == 0);
127 settings.endGroup();
128
129
130 World::getInstance().signOff(this);
131 World::getInstance().signOff(this, World::MoleculeInserted);
132 World::getInstance().signOff(this, World::SelectionChanged);
133 WorldTime::getInstance().signOff(this, WorldTime::TimeChanged);
134 AtomObserver::getInstance().signOff(this, AtomObservable::PositionChanged);
135 ShapeRegistry::getInstance().signOff(this);
136 ShapeRegistry::getInstance().signOff(this, ShapeRegistry::ShapeInserted);
137 ShapeRegistry::getInstance().signOff(this, ShapeRegistry::ShapeRemoved);
138 ShapeRegistry::getInstance().signOff(this, ShapeRegistry::SelectionChanged);
139 delete worldscene;
140
141 delete(domainBoxMaterial);
142 for (int i=0;i<3;i++)
143 delete(dreiBeinMaterial[i]);
144}
145
146
147/**
148 * Add some widget specific actions to the toolbar:
149 * - camera rotation/translation mode
150 * - camera fit to domain
151 */
152void GLWorldView::addToolBarActions(QToolBar *toolbar)
153{
154 // camera control mode
155 toolbar->addSeparator();
156 QAction *transAction = new QAction(QIcon::fromTheme("forward"), tr("camera translation mode"), this);
157 connect(transAction, SIGNAL(triggered()), this, SLOT(setCameraControlModeTranslation()));
158 toolbar->addAction(transAction);
159 QAction *rotAction = new QAction(QIcon::fromTheme("object-rotate-left"), tr("camera rotation mode"), this);
160 connect(rotAction, SIGNAL(triggered()), this, SLOT(setCameraControlModeRotation()));
161 toolbar->addAction(rotAction);
162 QAction *fitAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("camera fit to domain"), this);
163 connect(fitAction, SIGNAL(triggered()), this, SLOT(fitCameraToDomain()));
164 toolbar->addAction(fitAction);
165
166 // stereo mode
167 QToolButton *stereoButton = new QToolButton(toolbar);
168 QMenu *stereoMenu = new QMenu();
169 QAction *stereoDisableAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("disable"), this);
170 connect(stereoDisableAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeDisable()));
171 stereoMenu->addAction(stereoDisableAction);
172 QAction *stereoHardwareAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("hardware"), this);
173 connect(stereoHardwareAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeHardware()));
174 stereoMenu->addAction(stereoHardwareAction);
175 QAction *stereoLeftRightAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("left right"), this);
176 connect(stereoLeftRightAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeLeftRight()));
177 stereoMenu->addAction(stereoLeftRightAction);
178 QAction *stereoRightLeftAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("right left"), this);
179 connect(stereoRightLeftAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeRightLeft()));
180 stereoMenu->addAction(stereoRightLeftAction);
181 QAction *stereoTopBottomAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("top bottom"), this);
182 connect(stereoTopBottomAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeTopBottom()));
183 stereoMenu->addAction(stereoTopBottomAction);
184 QAction *stereoBottomTopAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("bottom top"), this);
185 connect(stereoBottomTopAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeBottomTop()));
186 stereoMenu->addAction(stereoBottomTopAction);
187 QAction *stereoAnaglyphAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("anaglyph"), this);
188 connect(stereoAnaglyphAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeAnaglyph()));
189 stereoMenu->addAction(stereoAnaglyphAction);
190 stereoButton->setMenu(stereoMenu);
191 stereoButton->setIcon(QIcon(QPixmap(":/icon_view_stereo.png")));
192 stereoButton->setPopupMode(QToolButton::InstantPopup);
193 toolbar->addWidget(stereoButton);
194
195 // selection mode
196 toolbar->addSeparator();
197 QAction *selAtomAction = new QAction(QIcon(QPixmap(":/icon_select_atom.png")), tr("select atom by clicking"), this);
198 connect(selAtomAction, SIGNAL(triggered()), worldscene, SLOT(setSelectionModeAtom()));
199 toolbar->addAction(selAtomAction);
200 QAction *selMolAction = new QAction(QIcon(QPixmap(":/icon_select_molecule.png")), tr("select molecule by clicking"), this);
201 connect(selMolAction, SIGNAL(triggered()), worldscene, SLOT(setSelectionModeMolecule()));
202 toolbar->addAction(selMolAction);
203
204 // dreiBein/domain enabler
205 toolbar->addSeparator();
206 QAction *seldreiBein = new QAction(QIcon(QPixmap(":/icon_dreiBein.png")), tr("enable/disable dreiBein"), this);
207 connect(seldreiBein, SIGNAL(triggered()), this, SLOT(changeDreiBein()));
208 toolbar->addAction(seldreiBein);
209 QAction *seldomain = new QAction(QIcon(QPixmap(":/icon_domain.png")), tr("enable/disable domain box"), this);
210 connect(seldomain, SIGNAL(triggered()), this, SLOT(changeDomain()));
211 toolbar->addAction(seldomain);
212}
213
214void GLWorldView::createDomainBox()
215{
216 QSettings settings;
217 settings.beginGroup("WorldView");
218 QColor colorFrame = settings.value("domainBoxColorFrame", QColor(150,160,200,255)).value<QColor>();
219 QColor colorAmbient = settings.value("domainBoxColorAmbient", QColor(50,60,100,255)).value<QColor>();
220 QColor colorDiffuse = settings.value("domainBoxColorDiffuse", QColor(150,160,200,180)).value<QColor>();
221 settings.setValue("domainBoxColorFrame", colorFrame);
222 settings.setValue("domainBoxColorAmbient", colorAmbient);
223 settings.setValue("domainBoxColorDiffuse", colorDiffuse);
224 const bool status = settings.value("domainBoxEnabled").toBool();
225 settings.endGroup();
226
227 domainBoxMaterial = new QGLMaterial;
228 domainBoxMaterial->setAmbientColor(QColor(0,0,0,255));
229 domainBoxMaterial->setDiffuseColor(QColor(0,0,0,255));
230 domainBoxMaterial->setEmittedLight(colorFrame);
231
232
233 QGLMaterial *material = new QGLMaterial;
234 material->setAmbientColor(colorAmbient);
235 material->setDiffuseColor(colorDiffuse);
236
237 QGLBuilder builder;
238 builder << QGL::Faceted;
239 builder << QGLCube(-1.0); // "inverted" => inside faces are used as front.
240 meshDomainBox = builder.finalizedSceneNode();
241 QMatrix4x4 mat;
242 mat.translate(0.5f, 0.5f, 0.5f);
243 meshDomainBox->setLocalTransform(mat);
244 meshDomainBox->setMaterial(material);
245
246 setDomainStatus( status );
247}
248
249void GLWorldView::createDreiBein()
250{
251 QSettings settings;
252 settings.beginGroup("WorldView");
253 QColor colorX = settings.value("dreiBeinColorX", QColor(255,50,50,255)).value<QColor>();
254 QColor colorY = settings.value("dreiBeinColorY", QColor(50,255,50,255)).value<QColor>();
255 QColor colorZ = settings.value("dreiBeinColorZ", QColor(50,50,255,255)).value<QColor>();
256 settings.setValue("dreiBeinColorX", colorX);
257 settings.setValue("dreiBeinColorY", colorY);
258 settings.setValue("dreiBeinColorZ", colorZ);
259 const bool status = settings.value("dreiBeinEnabled").toBool();
260 settings.endGroup();
261
262 // Create 3 color for the 3 axes.
263 dreiBeinMaterial[0] = new QGLMaterial;
264 dreiBeinMaterial[0]->setColor(colorX);
265 dreiBeinMaterial[1] = new QGLMaterial;
266 dreiBeinMaterial[1]->setColor(colorY);
267 dreiBeinMaterial[2] = new QGLMaterial;
268 dreiBeinMaterial[2]->setColor(colorZ);
269
270 // Create the basic meshes (cylinder and cone).
271 QGLBuilder builderCyl;
272 builderCyl << QGLCylinder(.15,.15,1.6,16);
273 QGLSceneNode *cyl = builderCyl.finalizedSceneNode();
274
275 QGLBuilder builderCone;
276 builderCone << QGLCylinder(0,.4,0.4,16);
277 QGLSceneNode *cone = builderCone.finalizedSceneNode();
278 {
279 QMatrix4x4 mat;
280 mat.translate(0.0f, 0.0f, 1.0f);
281 cone->setLocalTransform(mat);
282 }
283
284 // Create a scene node from the 3 axes.
285 meshDreiBein = new QGLSceneNode(this);
286
287 // X-direction
288 QGLSceneNode *node = new QGLSceneNode(meshDreiBein);
289 node->setMaterial(dreiBeinMaterial[0]);
290 node->addNode(cyl);
291 node->setPosition(QVector3D(.8f, 0.f, 0.f));
292 node->addNode(cone);
293 {
294 QMatrix4x4 mat;
295 mat.rotate(90, 0.0f, 1.0f, 0.0f);
296 node->setLocalTransform(mat);
297 }
298
299 // Y-direction
300 node = new QGLSceneNode(meshDreiBein);
301 node->setMaterial(dreiBeinMaterial[1]);
302 node->addNode(cyl);
303 node->addNode(cone);
304 {
305 QMatrix4x4 mat;
306 mat.rotate(-90, 1.0f, 0.0f, 0.0f);
307 node->setLocalTransform(mat);
308 }
309 node->setPosition(QVector3D(0.f, .8f, 0.f));
310
311 // Z-direction
312 node = new QGLSceneNode(meshDreiBein);
313 node->setMaterial(dreiBeinMaterial[2]);
314 node->addNode(cyl);
315 node->addNode(cone);
316 node->setPosition(QVector3D(0.f, 0.f, .8f));
317
318 setdreiBeinStatus( status );
319}
320
321/**
322 * Update operation which can be invoked by the observable (which should be the
323 * change tracker here).
324 */
325void GLWorldView::update(Observable *publisher)
326{
327 emit changed();
328}
329
330void GLWorldView::signOnToMolecule(const molecule *_mol)
331{
332 ASSERT( _mol != NULL,
333 "GLWorldView::signOnToMolecule() - molecule ref is NULL.");
334 _mol->signOn(this, molecule::AtomInserted);
335 _mol->signOn(this, molecule::AtomRemoved);
336
337 ObservedMolecules.insert(const_cast<molecule *>(_mol));
338}
339
340void GLWorldView::signOffFromMolecule(const molecule *_mol)
341{
342 ObservedMolecules_t::const_iterator iter = ObservedMolecules.find(
343 const_cast<molecule *>(_mol));
344 ASSERT( iter != ObservedMolecules.end(),
345 "GLWorldView::signOffFromMolecule() - molecule "+toString(_mol)
346 +" gave subjectKilled we are not signed on.");
347// LOG(1, "INFO: Erasing " << mol << " from ObservedMolecules.");
348 ObservedMolecules.erase(iter);
349
350 ASSERT( _mol != NULL,
351 "GLWorldView::signOffFromMolecule() - molecule ref is NULL.");
352 _mol->signOff(this, molecule::AtomInserted);
353 _mol->signOff(this, molecule::AtomRemoved);
354}
355
356/**
357 * The observable can tell when it dies.
358 */
359void GLWorldView::subjectKilled(Observable *publisher)
360{
361 molecule * mol = static_cast<molecule *>(publisher);
362
363// std::copy(ObservedMolecules.begin(), ObservedMolecules.end(),
364// std::ostream_iterator<molecule *>(std::cout, "\n"));
365
366 if (mol != NULL) {
367
368 // sign off
369 signOffFromMolecule(mol);
370
371 // emit removed signal
372 const moleculeId_t _id = World::getInstance().lastChanged<molecule>()->getId();
373 emit moleculeRemoved(_id);
374 }
375}
376
377/** Listen to specific changes to the world.
378 *
379 * @param publisher ref to observable.
380 * @param notification type of notification
381 */
382void GLWorldView::recieveNotification(Observable *publisher, Notification_ptr notification)
383{
384 if (static_cast<World *>(publisher) == World::getPointer()) {
385 switch (notification->getChannelNo()) {
386 case World::SelectionChanged:
387 {
388 #ifdef LOG_OBSERVER
389 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that selection has changed.";
390 #endif
391 emit worldSelectionChanged();
392 break;
393 }
394 case World::MoleculeInserted:
395 {
396 const moleculeId_t _id = World::getInstance().lastChanged<molecule>()->getId();
397 #ifdef LOG_OBSERVER
398 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that molecule "+toString(_id)+" has been inserted.";
399 #endif
400 const molecule * const _molecule = const_cast<const World &>(World::getInstance()).
401 getMolecule(MoleculeById(_id));
402 if (_molecule != NULL) {
403 signOnToMolecule(_molecule);
404
405 emit moleculeInserted(_id);
406 }
407 break;
408 }
409 default:
410 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for World.");
411 break;
412 }
413 } else if (static_cast<WorldTime *>(publisher) == WorldTime::getPointer()) {
414 switch (notification->getChannelNo()) {
415 case WorldTime::TimeChanged:
416 {
417#ifdef LOG_OBSERVER
418 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that WorldTime's time has changed.";
419#endif
420 emit changed();
421 emit TimeChanged();
422 break;
423 }
424 default:
425 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for WorldTime.");
426 break;
427 }
428 } else if (dynamic_cast<molecule *>(publisher) != NULL) {
429 const molecule * mol = const_cast<const molecule * const>(dynamic_cast<molecule *>(publisher));
430 const atomId_t atomid = mol->lastChanged()->getId();
431 const moleculeId_t molid = mol->getId();
432 switch (notification->getChannelNo()) {
433 case molecule::AtomInserted:
434 {
435#ifdef LOG_OBSERVER
436 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this))
437 << " received notification that atom "+toString(atomid)+" has been inserted into molecule "+toString(molid)+".";
438#endif
439 emit atomInserted(molid, atomid);
440 break;
441 }
442 case World::AtomRemoved:
443 {
444#ifdef LOG_OBSERVER
445 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this))
446 << " received notification that atom "+toString(atomid)+" has been removed from molecule "+toString(molid)+".";
447#endif
448 emit atomRemoved(molid, atomid);
449 break;
450 }
451 default:
452 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for molecule.");
453 break;
454 }
455 } else if (dynamic_cast<AtomObservable *>(publisher) != NULL) {
456 switch (notification->getChannelNo()) {
457 case AtomObservable::PositionChanged:
458 {
459 #ifdef LOG_OBSERVER
460 const atom *_atom = dynamic_cast<const atom *>(publisher);
461 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_atom->getId())+" has changed its position.";
462 #endif
463 emit changed();
464 break;
465 }
466 default:
467 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for AtomObservable.");
468 break;
469 }
470 } else if (static_cast<ShapeRegistry*>(publisher) == ShapeRegistry::getPointer()) {
471 switch (notification->getChannelNo()) {
472 case ShapeRegistry::ShapeInserted:
473 {
474 emit ShapeAdded();
475 break;
476 }
477 case ShapeRegistry::ShapeRemoved:
478 {
479 emit ShapeRemoved();
480 break;
481 }
482 case ShapeRegistry::SelectionChanged:
483 {
484 worldscene->updateSelectedShapes();
485 break;
486 }
487 default:
488 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for ShapeRegistry.");
489 break;
490 }
491 } else
492 ASSERT(0, "GLWorldView::recieveNotification() - received notification from unknown source.");
493}
494
495void GLWorldView::checkChanges()
496{
497 updateGL();
498 needsRedraw = false;
499}
500
501void GLWorldView::changeDreiBein()
502{
503 // invert to new status
504 const bool status = ((meshDreiBein->options() & QGLSceneNode::HideNode) == 0);
505 setdreiBeinStatus(!status);
506 // realize
507 updateGL();
508 needsRedraw = true;
509}
510
511void GLWorldView::setdreiBeinStatus(const bool status)
512{
513 if (status)
514 meshDreiBein->setOptions( meshDreiBein->options() & (255-QGLSceneNode::HideNode) );
515 else
516 meshDreiBein->setOptions( meshDreiBein->options() | QGLSceneNode::HideNode );
517}
518
519void GLWorldView::changeDomain()
520{
521 // invert to new status
522 const bool status = ((meshDomainBox->options() & QGLSceneNode::HideNode) == 0);
523 setDomainStatus(!status);
524 // realize
525 updateGL();
526 needsRedraw = true;
527}
528
529void GLWorldView::setDomainStatus(const bool status)
530{
531 if (status)
532 meshDomainBox->setOptions( meshDomainBox->options() & (255-QGLSceneNode::HideNode) );
533 else
534 meshDomainBox->setOptions( meshDomainBox->options() | QGLSceneNode::HideNode );
535}
536
537void GLWorldView::sceneChangeSignalled()
538{
539 if (!needsRedraw){
540 redrawTimer->singleShot(0, this, SLOT(checkChanges()));
541 needsRedraw = true;
542 redrawTimer->start();
543 }
544}
545
546void GLWorldView::initializeGL(QGLPainter *painter)
547{
548 worldscene->initialize(this, painter);
549 changesPresent = false;
550}
551
552void GLWorldView::paintGL(QGLPainter *painter)
553{
554 if (changesPresent) {
555 initializeGL(painter);
556 changesPresent = false;
557 }
558
559 QVector3D cameraDir = camera()->center() - camera()->eye();
560 cameraDir.normalize();
561 QVector4D cameraPlane(cameraDir, QVector3D::dotProduct(cameraDir, camera()->eye()));
562 worldscene->draw(painter, cameraPlane);
563
564 drawDreiBein(painter);
565
566 // Domain box has to be last because of its transparency.
567 drawDomainBox(painter);
568}
569
570void GLWorldView::keyPressEvent(QKeyEvent *e)
571{
572 // Find the distance between the eye and focus point.
573 QVector3D d = camera()->eye() - camera()->center();
574// LOG(1, "Distance vector eye and center is "
575// << d.x() << "," << d.y() << "," << d.z());
576 // scale the move unit by the eye <-> domain center distance
577 const double key_move_unit = 0.04*(d.length()/50.);
578
579 if (e->key() == Qt::Key_Tab) {
580 // The Tab key turns the ShowPicking option on and off,
581 // which helps show what the pick buffer looks like.
582 setOption(QGLView::ShowPicking, ((options() & QGLView::ShowPicking) == 0));
583 updateGL();
584 } else if ((e->key() == Qt::Key_Minus) || (e->key() == Qt::Key_Plus)) {
585 // Scale the distance.
586 if (e->key() == Qt::Key_Minus)
587 d *= 1.2;
588 else if (e->key() == Qt::Key_Plus)
589 d /= 1.2;
590 // Set new eye position.
591 camera()->setEye(camera()->center() + d);
592 } else if ((e->key() == Qt::Key_Left) || (e->key() == Qt::Key_Right)) {
593 // Translate the camera.
594 const double d = (e->key() == Qt::Key_Left) ? -key_move_unit : key_move_unit;
595 camera()->translateCenter( d, 0., 0);
596 camera()->translateEye( d, 0., 0);
597 } else if ((e->key() == Qt::Key_Up) || (e->key() == Qt::Key_Down)) {
598 // Translate the camera.
599 const double d = (e->key() == Qt::Key_Up) ? -key_move_unit : key_move_unit;
600 camera()->translateCenter( 0., d, 0);
601 camera()->translateEye( 0., d, 0);
602 } else if ((e->key() == Qt::Key_PageUp) || (e->key() == Qt::Key_PageDown)) {
603 // Translate the camera.
604 const double d = (e->key() == Qt::Key_PageUp) ? -key_move_unit : key_move_unit;
605 camera()->translateCenter( 0., 0., d);
606 camera()->translateEye( 0., 0., d);
607 }
608 QGLView::keyPressEvent(e);
609}
610
611void GLWorldView::changeSignalled()
612{
613 changesPresent = true;
614}
615
616
617/**
618 * Set the current camera control mode.
619 */
620void GLWorldView::setCameraControlMode(GLWorldView::CameraControlModeType mode)
621{
622 cameraControlMode = mode;
623}
624
625void GLWorldView::setCameraControlModeRotation()
626{
627 setCameraControlMode(Rotate);
628}
629
630void GLWorldView::setCameraControlModeTranslation()
631{
632 setCameraControlMode(Translate);
633}
634
635/**
636 * Returns the current camera control mode.
637 * This needs to be invertable (rotation - translation), if the shift key is pressed.
638 */
639GLWorldView::CameraControlModeType GLWorldView::getCameraControlMode(bool inverted)
640{
641 if (inverted){
642 if (cameraControlMode == Rotate)
643 return Translate;
644 if (cameraControlMode == Translate)
645 return Rotate;
646 return Rotate;
647 }else
648 return cameraControlMode;
649}
650
651/**
652 * Set the camera so it can oversee the whole domain.
653 */
654void GLWorldView::fitCameraToDomain()
655{
656 // Move the camera focus point to the center of the domain box.
657 Vector v = World::getInstance().getDomain().translateIn(Vector(0.5, 0.5, 0.5));
658 camera()->setCenter(QVector3D(v[0], v[1], v[2]));
659
660 // Guess some eye distance.
661 double dist = v.Norm() * 3;
662 camera()->setEye(QVector3D(v[0], v[1], v[2] + dist));
663 camera()->setUpVector(QVector3D(0, 1, 0));
664}
665
666void GLWorldView::setCameraStereoModeDisable()
667{
668 setStereoType(QGLView::Hardware);
669 camera()->setEyeSeparation(0.0);
670 updateGL();
671}
672
673void GLWorldView::setCameraStereoModeHardware()
674{
675 setStereoType(QGLView::Hardware);
676 camera()->setEyeSeparation(defaultEyeSeparation);
677 updateGL();
678}
679
680void GLWorldView::setCameraStereoModeLeftRight()
681{
682 setStereoType(QGLView::LeftRight);
683 camera()->setEyeSeparation(defaultEyeSeparation);
684 updateGL();
685}
686
687void GLWorldView::setCameraStereoModeRightLeft()
688{
689 setStereoType(QGLView::RightLeft);
690 camera()->setEyeSeparation(defaultEyeSeparation);
691 updateGL();
692}
693
694void GLWorldView::setCameraStereoModeTopBottom()
695{
696 setStereoType(QGLView::TopBottom);
697 camera()->setEyeSeparation(defaultEyeSeparation);
698 updateGL();
699}
700
701void GLWorldView::setCameraStereoModeBottomTop()
702{
703 setStereoType(QGLView::BottomTop);
704 camera()->setEyeSeparation(defaultEyeSeparation);
705 updateGL();
706}
707
708void GLWorldView::setCameraStereoModeAnaglyph()
709{
710 setStereoType(QGLView::RedCyanAnaglyph);
711 camera()->setEyeSeparation(defaultEyeSeparation);
712 updateGL();
713}
714
715void GLWorldView::mousePressEvent(QMouseEvent *event)
716{
717 QGLView::mousePressEvent(event);
718
719 // Reset the saved mouse position.
720 lastMousePos = event->posF();
721}
722
723/**
724 * Handle a mouse move event.
725 * This is used to control the camera (rotation and translation) when the left button is being pressed.
726 */
727void GLWorldView::mouseMoveEvent(QMouseEvent *event)
728{
729 if (event->buttons() & Qt::LeftButton){
730 // Find the mouse distance since the last event.
731 QPointF d = event->posF() - lastMousePos;
732 lastMousePos = event->posF();
733
734 // Rotate or translate? (inverted by shift key)
735 CameraControlModeType mode = getCameraControlMode(event->modifiers() & Qt::ShiftModifier);
736
737 if (mode == Rotate){
738 // Rotate the camera.
739 d *= 0.3;
740 camera()->tiltPanRollCenter(- d.y(), - d.x(), 0);
741 }else if (mode == Translate){
742 // Translate the camera.
743 d *= 0.02;
744 camera()->translateCenter(- d.x(), d.y(), 0);
745 camera()->translateEye(- d.x(), d.y(), 0);
746 }
747 }else{
748 // Without this Qt would not test for hover events (i.e. mouse over an atom).
749 QGLView::mouseMoveEvent(event);
750 }
751}
752
753/**
754 * When the mouse wheel is used, zoom in or out.
755 */
756void GLWorldView::wheelEvent(QWheelEvent *event)
757{
758 // Find the distance between the eye and focus point.
759 QVector3D d = camera()->eye() - camera()->center();
760
761 // Scale the distance.
762 if (event->delta() < 0)
763 d *= 1.2;
764 else if (event->delta() > 0)
765 d /= 1.2;
766
767 // Set new eye position.
768 camera()->setEye(camera()->center() + d);
769}
770
771/**
772 * Draw a transparent cube representing the domain.
773 */
774void GLWorldView::drawDomainBox(QGLPainter *painter) const
775{
776 // Apply the domain matrix.
777 RealSpaceMatrix m = World::getInstance().getDomain().getM();
778 painter->modelViewMatrix().push();
779 painter->modelViewMatrix() *= QMatrix4x4(m.at(0,0), m.at(0,1), m.at(0,2), 0.0,
780 m.at(1,0), m.at(1,1), m.at(1,2), 0.0,
781 m.at(2,0), m.at(2,1), m.at(2,2), 0.0,
782 0.0, 0.0, 0.0, 1.0);
783
784 // Draw the transparent cube.
785 painter->setStandardEffect(QGL::LitMaterial);
786 glCullFace(GL_BACK);
787 glEnable(GL_CULL_FACE);
788 glEnable(GL_BLEND);
789 glDepthMask(0);
790 //glDisable(GL_DEPTH_TEST);
791 meshDomainBox->draw(painter);
792 //glEnable(GL_DEPTH_TEST);
793 glDepthMask(1);
794 glDisable(GL_BLEND);
795 glDisable(GL_CULL_FACE);
796
797 // Draw the outlines (if we have drawn the box itself)
798 if ((meshDomainBox->options() & QGLSceneNode::HideNode) == 0) {
799 painter->setFaceMaterial(QGL::AllFaces, domainBoxMaterial);
800 //glEnable(GL_LINE_SMOOTH);
801 QVector3DArray array;
802 array.append(0, 0, 0); array.append(1, 0, 0);
803 array.append(1, 0, 0); array.append(1, 1, 0);
804 array.append(1, 1, 0); array.append(0, 1, 0);
805 array.append(0, 1, 0); array.append(0, 0, 0);
806
807 array.append(0, 0, 1); array.append(1, 0, 1);
808 array.append(1, 0, 1); array.append(1, 1, 1);
809 array.append(1, 1, 1); array.append(0, 1, 1);
810 array.append(0, 1, 1); array.append(0, 0, 1);
811
812 array.append(0, 0, 0); array.append(0, 0, 1);
813 array.append(1, 0, 0); array.append(1, 0, 1);
814 array.append(0, 1, 0); array.append(0, 1, 1);
815 array.append(1, 1, 0); array.append(1, 1, 1);
816 painter->clearAttributes();
817 painter->setVertexAttribute(QGL::Position, array);
818 painter->draw(QGL::Lines, 24);
819 }
820
821 painter->modelViewMatrix().pop();
822}
823
824void GLWorldView::drawDreiBein(QGLPainter *painter)
825{
826 painter->modelViewMatrix().push();
827 painter->modelViewMatrix().translate(camera()->center());
828 painter->setStandardEffect(QGL::LitMaterial);
829 painter->setFaceMaterial(QGL::FrontFaces, NULL);
830 meshDreiBein->draw(painter);
831 painter->modelViewMatrix().pop();
832}
833
834void GLWorldView::sceneHoverSignalled(const atomId_t _id)
835{
836 emit hoverChanged(_id);
837}
838
839void GLWorldView::sceneHoverSignalled(const moleculeId_t _id, int _i)
840{
841 emit hoverChanged(_id, _i);
842}
Note: See TracBrowser for help on using the repository browser.