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

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

Only GLWorldScene creates stuff, GLMoleculeObject_.. are just visual reps.

  • Property mode set to 100644
File size: 10.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 "UIElements/Views/Qt4/Qt3D/GLMoleculeObject_atom.hpp"
43
44#include "CodePatterns/MemDebug.hpp"
45
46#include "CodePatterns/Assert.hpp"
47#include "CodePatterns/IteratorAdaptors.hpp"
48#include "CodePatterns/Log.hpp"
49
50#include "LinearAlgebra/Vector.hpp"
51#include "LinkedCell/PointCloudAdaptor.hpp"
52#include "LinkedCell/linkedcell.hpp"
53#include "Tesselation/tesselation.hpp"
54#include "Tesselation/BoundaryLineSet.hpp"
55#include "Tesselation/BoundaryTriangleSet.hpp"
56#include "Tesselation/CandidateForTesselation.hpp"
57#include "UIElements/Qt4/InstanceBoard/QtObservedInstanceBoard.hpp"
58#include "Atom/TesselPoint.hpp"
59#include "World.hpp"
60
61static QGLSceneNode *createMoleculeMesh(const QGeometryData &_geo)
62{
63 // Build a mesh from the geometry.
64 QGLBuilder builder;
65 builder.addTriangles(_geo);
66 QGLSceneNode *mesh = builder.finalizedSceneNode();
67 return mesh;
68}
69
70GLMoleculeObject_molecule::GLMoleculeObject_molecule(
71 QObject *parent,
72 QtObservedMolecule::ptr &_ObservedMolecule) :
73 GLMoleculeObject((QGLSceneNode *)NULL, parent),
74 hoverAtomId(-1),
75 ObservedMolecule(_ObservedMolecule)
76{
77 init();
78}
79
80GLMoleculeObject_molecule::GLMoleculeObject_molecule(
81 QGLSceneNode *mesh[],
82 QObject *parent,
83 QtObservedMolecule::ptr &_ObservedMolecule) :
84 GLMoleculeObject(mesh, parent),
85 hoverAtomId(-1),
86 ObservedMolecule(_ObservedMolecule)
87{
88 init();
89}
90
91void GLMoleculeObject_molecule::init()
92{
93 setObjectId(ObservedMolecule->getMolIndex());
94 setMaterial(getMaterial(1));
95
96 m_selected = ObservedMolecule->getMolSelected();
97
98 // initially, atoms and bonds should be visible
99 m_visible = false;
100
101 connect (ObservedMolecule.get(), SIGNAL(tesselationhullChanged()), this, SLOT(resetTesselationHull()));
102 connect (ObservedMolecule.get(), SIGNAL(boundingboxChanged()), this, SLOT(resetBoundingBox()));
103 connect (ObservedMolecule.get(), SIGNAL(indexChanged(const moleculeId_t, const moleculeId_t)),
104 this, SLOT(resetIndex(const moleculeId_t, const moleculeId_t)));
105 /// these are channeled through GLWorldScene instead to ensure synchronicity
106// connect (ObservedMolecule.get(), SIGNAL(atomInserted(QtObservedAtom::ptr)),
107// this, SLOT(atomInserted(QtObservedAtom::ptr)) );
108// connect (ObservedMolecule.get(), SIGNAL(atomRemoved(const atomId_t)),
109// this, SLOT(atomRemoved(const atomId_t)) );
110 connect (ObservedMolecule.get(), SIGNAL(selectedChanged()), this, SLOT(resetSelected()));
111}
112
113GLMoleculeObject_molecule::~GLMoleculeObject_molecule()
114{}
115
116QGeometryData GLMoleculeObject_molecule::updateTesselationHull() const
117{
118 QGeometryData geo;
119
120 const molecule * const molref =
121 QtObservedMolecule::getMolecule(ObservedMolecule->getMolIndex());
122 if (molref == NULL) {
123 ELOG(1, "Could not createMoleculeMesh, molecule with id "
124 << ObservedMolecule->getMolIndex() << " already gone.");
125 return geo;
126 }
127 double minradius = 2.; // TODO: set to maximum bond length value
128 LOG(3, "DEBUG: Molecule fits into sphere of radius " << minradius);
129 // check minimum bond radius in molecule
130 double minlength = std::numeric_limits<double>::max();
131 size_t NoAtoms = 0;
132 for (molecule::const_iterator iter = molref->begin();
133 iter != molref->end(); ++iter) {
134 const BondList &ListOfBonds = (*iter)->getListOfBonds();
135 for (BondList::const_iterator bonditer = ListOfBonds.begin();
136 bonditer != ListOfBonds.end(); ++bonditer) {
137 const double bond_distance = (*bonditer)->GetDistance();
138 minlength = std::min(bond_distance, minlength);
139 }
140 ++NoAtoms;
141 }
142 minradius = std::max( std::max(minradius, minlength), 1.);
143
144 // we need at least three points for tesselation
145 if (NoAtoms >= 3) {
146 // Tesselate the points.
147 Tesselation T;
148 PointCloudAdaptor<molecule> cloud(
149 const_cast<molecule *>(molref),
150 ObservedMolecule->getMolName());
151 T(cloud, minradius);
152
153 // Fill the points into a Qt geometry.
154 LinkedCell_deprecated LinkedList(cloud, minradius);
155 std::map<int, int> indices;
156 std::map<int, Vector> normals;
157 int index = 0;
158 for (PointMap::const_iterator piter = T.PointsOnBoundary.begin();
159 piter != T.PointsOnBoundary.end(); ++piter) {
160 const Vector &point = piter->second->getPosition();
161 // add data to the primitive
162 geo.appendVertex(QVector3D(point[0], point[1], point[2]));
163 Vector normalvector;
164 for (LineMap::const_iterator lineiter = piter->second->lines.begin();
165 lineiter != piter->second->lines.end(); ++lineiter)
166 for (TriangleMap::const_iterator triangleiter = lineiter->second->triangles.begin();
167 triangleiter != lineiter->second->triangles.end(); ++triangleiter)
168 normalvector +=
169 triangleiter->second->NormalVector;
170 normalvector.Normalize();
171 geo.appendNormal(QVector3D(normalvector[0], normalvector[1], normalvector[2]));
172 geo.appendColor(QColor(1, 1, 1, 1));
173 geo.appendTexCoord(QVector2D(0, 0));
174 indices.insert( std::make_pair( piter->second->getNr(), index++));
175 }
176
177 // Fill the tesselated triangles into the geometry.
178 for (TriangleMap::const_iterator runner = T.TrianglesOnBoundary.begin();
179 runner != T.TrianglesOnBoundary.end(); runner++) {
180 int v[3];
181 for (size_t i=0; i<3; ++i)
182 v[i] = runner->second->endpoints[i]->getNr();
183
184 // Sort the vertices so the triangle is clockwise (relative to the normal vector).
185 Vector cross = T.PointsOnBoundary[v[1]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition();
186 cross.VectorProduct(T.PointsOnBoundary[v[2]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition());
187 if (cross.ScalarProduct(runner->second->NormalVector) > 0)
188 geo.appendIndices(indices[v[0]], indices[v[1]], indices[v[2]]);
189 else
190 geo.appendIndices(indices[v[0]], indices[v[2]], indices[v[1]]);
191 }
192 }
193
194 return geo;
195}
196
197void GLMoleculeObject_molecule::resetTesselationHull()
198{
199 TesselationHull = updateTesselationHull();
200 updateMesh(createMoleculeMesh(TesselationHull));
201}
202
203void GLMoleculeObject_molecule::resetBoundingBox()
204{
205 molecule::BoundingBoxInfo info = ObservedMolecule->getBoundingBox();
206 setPosition(QVector3D(info.position[0], info.position[1], info.position[2]));
207 setScale(info.radius + 0.3); // getBoundingSphere() only sees atoms as points, so make the box a bit bigger
208}
209
210void GLMoleculeObject_molecule::resetIndex(const moleculeId_t, const moleculeId_t)
211{
212 const atomId_t newId = ObservedMolecule->getMolIndex();
213 const size_t oldId = objectId();
214 ASSERT( newId != oldId,
215 "GLMoleculeObject_molecule::resetIndex() - index "+toString(newId)+" did not change.");
216 LOG(4, "INFO: GLMoleculeObject_molecule: new index is "+toString(newId)+".");
217 setObjectId(newId);
218}
219
220void GLMoleculeObject_molecule::resetSelected()
221{
222 const bool new_selected = ObservedMolecule->getMolSelected();
223 m_selected = new_selected;
224
225 emit changed();
226}
227
228void GLMoleculeObject_molecule::initialize(QGLView *view, QGLPainter *painter)
229{
230 // Initialize all of the mesh objects that we have as children.
231 if (m_visible) {
232 GLMoleculeObject::initialize(view, painter);
233 } else {
234 foreach (QObject *obj, children()) {
235 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
236 if (meshobj)
237 meshobj->initialize(view, painter);
238 }
239 }
240}
241
242void GLMoleculeObject_molecule::draw(QGLPainter *painter, const QVector4D &cameraPlane)
243{
244 // draw either molecule's mesh or all atoms and bonds
245 if (m_visible) {
246 resetTesselationHull();
247
248 painter->modelViewMatrix().push();
249
250 // Apply the material and effect to the painter.
251 QGLMaterial *material;
252 if (m_hovering)
253 material = m_hoverMaterial;
254 else if (m_selected)
255 material = m_selectionMaterial;
256 else
257 material = m_material;
258
259 ASSERT(material, "GLMoleculeObject::draw: chosen material is NULL");
260
261 painter->setColor(material->diffuseColor());
262 painter->setFaceMaterial(QGL::AllFaces, material);
263 if (m_effect)
264 painter->setUserEffect(m_effect);
265 else
266 painter->setStandardEffect(QGL::LitMaterial);
267
268 // Mark the object for object picking purposes.
269 int prevObjectId = painter->objectPickId();
270 if (m_objectId != -1)
271 painter->setObjectPickId(m_objectId);
272
273 m_mesh[0]->draw(painter);
274
275 // Turn off the user effect, if present.
276 if (m_effect)
277 painter->setStandardEffect(QGL::LitMaterial);
278
279 // Revert to the previous object identifier.
280 painter->setObjectPickId(prevObjectId);
281
282 // Restore the modelview matrix.
283 painter->modelViewMatrix().pop();
284
285 // GLMoleculeObject::draw(painter, cameraPlane);
286 } else {
287 // Draw all of the mesh objects that we have as children.
288 foreach (QObject *obj, children()) {
289 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
290 if (meshobj)
291 meshobj->draw(painter, cameraPlane);
292 }
293
294 // update bounding box prior to selection
295 resetBoundingBox();
296
297 painter->modelViewMatrix().push();
298 painter->modelViewMatrix().translate(m_position);
299 if (m_rotationAngle != 0.0f)
300 painter->modelViewMatrix().rotate(m_rotationAngle, m_rotationVector);
301 if ((m_scaleX != 1.0f) || (m_scaleY != 1.0f) || (m_scaleZ != 1.0f))
302 painter->modelViewMatrix().scale(m_scaleX, m_scaleY, m_scaleZ);
303
304 // Draw a box around the mesh, if selected.
305 if (m_selected)
306 drawSelectionBox(painter);
307
308 // Restore the modelview matrix.
309 painter->modelViewMatrix().pop();
310 }
311}
312
313void GLMoleculeObject_molecule::setVisible(bool value)
314{
315 // first update the mesh if we are going to be visible now
316 if (value)
317 updateTesselationHull();
318 // then emit onward
319 GLMoleculeObject::setVisible(value);
320
321 emit changed();
322 emit changeOccured();
323}
324
325std::ostream &operator<<(std::ostream &ost, const GLMoleculeObject_molecule::BondIds &t)
326{
327 ost << t.first << "," << t.second;
328 return ost;
329}
Note: See TracBrowser for help on using the repository browser.