/*
* Project: MoleCuilder
* Description: creates and alters molecular systems
* Copyright (C) 2010-2012 University of Bonn. All rights reserved.
* Copyright (C) 2013 Frederik Heber. All rights reserved.
*
*
* This file is part of MoleCuilder.
*
* MoleCuilder is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* MoleCuilder is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MoleCuilder. If not, see .
*/
/*
* GLMoleculeObject_molecule.cpp
*
* Created on: Mar 30, 2012
* Author: ankele
*/
// include config.h
#ifdef HAVE_CONFIG_H
#include
#endif
#include "GLMoleculeObject_molecule.hpp"
#include
#include
#include "UIElements/Views/Qt4/Qt3D/GLMoleculeObject_atom.hpp"
#include "CodePatterns/MemDebug.hpp"
#include
#include "CodePatterns/Assert.hpp"
#include "CodePatterns/IteratorAdaptors.hpp"
#include "CodePatterns/Log.hpp"
#include "LinearAlgebra/Vector.hpp"
#include "LinkedCell/PointCloudAdaptor.hpp"
#include "LinkedCell/linkedcell.hpp"
#include "Tesselation/tesselation.hpp"
#include "Tesselation/BoundaryLineSet.hpp"
#include "Tesselation/BoundaryTriangleSet.hpp"
#include "Tesselation/CandidateForTesselation.hpp"
#include "UIElements/Qt4/InstanceBoard/QtObservedInstanceBoard.hpp"
#include "Atom/TesselPoint.hpp"
#include "World.hpp"
using namespace boost::assign;
static Observable::channels_t getAllAtomicChangesChannels()
{
Observable::channels_t channels;
channels += molecule::AtomInserted, molecule::AtomRemoved, molecule::AtomMoved;
return channels;
}
const Observable::channels_t GLMoleculeObject_molecule::HullChannels(getAllAtomicChangesChannels());
static QGLSceneNode *createMoleculeMesh(const QGeometryData &_geo)
{
// Build a mesh from the geometry.
QGLBuilder builder;
builder.addTriangles(_geo);
QGLSceneNode *mesh = builder.finalizedSceneNode();
return mesh;
}
GLMoleculeObject_molecule::GLMoleculeObject_molecule(
QObject *parent,
QtObservedInstanceBoard &_board,
QtObservedMolecule::ptr &_ObservedMolecule) :
GLMoleculeObject((QGLSceneNode *)NULL, parent),
owner(NULL),
hoverAtomId(-1),
board(_board),
ObservedMolecule(_ObservedMolecule)
{
init();
}
GLMoleculeObject_molecule::GLMoleculeObject_molecule(
QGLSceneNode *mesh[],
QObject *parent,
QtObservedInstanceBoard &_board,
QtObservedMolecule::ptr &_ObservedMolecule) :
GLMoleculeObject(mesh, parent),
owner(NULL),
hoverAtomId(-1),
board(_board),
ObservedMolecule(_ObservedMolecule)
{
init();
}
void GLMoleculeObject_molecule::init()
{
setObjectId(ObservedMolecule->getMolIndex());
setMaterial(getMaterial(1));
m_selected = ObservedMolecule->getMolSelected();
// initially, atoms and bonds should be visible
m_visible = false;
connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
connect (ObservedMolecule.get(), SIGNAL(tesselationhullChanged()), this, SLOT(resetTesselationHull()));
connect (ObservedMolecule.get(), SIGNAL(boundingboxChanged()), this, SLOT(resetBoundingBox()));
connect (ObservedMolecule.get(), SIGNAL(indexChanged(const moleculeId_t, const moleculeId_t)),
this, SLOT(resetIndex(const moleculeId_t, const moleculeId_t)));
/// these are channeled through GLWorldScene instead to ensure synchronicity
// connect (ObservedMolecule.get(), SIGNAL(atomInserted(QtObservedAtom::ptr)),
// this, SLOT(atomInserted(QtObservedAtom::ptr)) );
// connect (ObservedMolecule.get(), SIGNAL(atomRemoved(const atomId_t)),
// this, SLOT(atomRemoved(const atomId_t)) );
connect (ObservedMolecule.get(), SIGNAL(selectedChanged()), this, SLOT(resetSelected()));
connect( this, SIGNAL(clicked()), this, SLOT(wasClicked()));
}
GLMoleculeObject_molecule::~GLMoleculeObject_molecule()
{}
QGeometryData GLMoleculeObject_molecule::updateTesselationHull() const
{
QGeometryData geo;
const molecule * const molref =
QtObservedMolecule::getMolecule(ObservedMolecule->getMolIndex());
if (molref == NULL) {
ELOG(1, "Could not createMoleculeMesh, molecule with id "
<< ObservedMolecule->getMolIndex() << " already gone.");
return geo;
}
double minradius = 2.; // TODO: set to maximum bond length value
LOG(3, "DEBUG: Molecule fits into sphere of radius " << minradius);
// check minimum bond radius in molecule
double minlength = std::numeric_limits::max();
for (molecule::const_iterator iter = molref->begin();
iter != molref->end(); ++iter) {
const BondList &ListOfBonds = (*iter)->getListOfBonds();
for (BondList::const_iterator bonditer = ListOfBonds.begin();
bonditer != ListOfBonds.end(); ++bonditer) {
const double bond_distance = (*bonditer)->GetDistance();
minlength = std::min(bond_distance, minlength);
}
}
minradius = std::max( std::max(minradius, minlength), 1.);
// we need at least three points for tesselation
if (AtomsinSceneMap.size() >= 3) {
// Tesselate the points.
Tesselation T;
PointCloudAdaptor cloud(
const_cast(molref),
ObservedMolecule->getMolName());
T(cloud, minradius);
// Fill the points into a Qt geometry.
LinkedCell_deprecated LinkedList(cloud, minradius);
std::map indices;
std::map normals;
int index = 0;
for (PointMap::const_iterator piter = T.PointsOnBoundary.begin();
piter != T.PointsOnBoundary.end(); ++piter) {
const Vector &point = piter->second->getPosition();
// add data to the primitive
geo.appendVertex(QVector3D(point[0], point[1], point[2]));
Vector normalvector;
for (LineMap::const_iterator lineiter = piter->second->lines.begin();
lineiter != piter->second->lines.end(); ++lineiter)
for (TriangleMap::const_iterator triangleiter = lineiter->second->triangles.begin();
triangleiter != lineiter->second->triangles.end(); ++triangleiter)
normalvector +=
triangleiter->second->NormalVector;
normalvector.Normalize();
geo.appendNormal(QVector3D(normalvector[0], normalvector[1], normalvector[2]));
geo.appendColor(QColor(1, 1, 1, 1));
geo.appendTexCoord(QVector2D(0, 0));
indices.insert( std::make_pair( piter->second->getNr(), index++));
}
// Fill the tesselated triangles into the geometry.
for (TriangleMap::const_iterator runner = T.TrianglesOnBoundary.begin();
runner != T.TrianglesOnBoundary.end(); runner++) {
int v[3];
for (size_t i=0; i<3; ++i)
v[i] = runner->second->endpoints[i]->getNr();
// Sort the vertices so the triangle is clockwise (relative to the normal vector).
Vector cross = T.PointsOnBoundary[v[1]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition();
cross.VectorProduct(T.PointsOnBoundary[v[2]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition());
if (cross.ScalarProduct(runner->second->NormalVector) > 0)
geo.appendIndices(indices[v[0]], indices[v[1]], indices[v[2]]);
else
geo.appendIndices(indices[v[0]], indices[v[2]], indices[v[1]]);
}
}
return geo;
}
void GLMoleculeObject_molecule::resetTesselationHull()
{
if (owner != NULL) {
TesselationHull = updateTesselationHull();
updateMesh(createMoleculeMesh(TesselationHull));
}
}
void GLMoleculeObject_molecule::resetBoundingBox()
{
molecule::BoundingBoxInfo info = ObservedMolecule->getBoundingBox();
setPosition(QVector3D(info.position[0], info.position[1], info.position[2]));
setScale(info.radius + 0.3); // getBoundingSphere() only sees atoms as points, so make the box a bit bigger
}
void GLMoleculeObject_molecule::resetIndex(const moleculeId_t, const moleculeId_t)
{
const atomId_t newId = ObservedMolecule->getMolIndex();
const size_t oldId = objectId();
ASSERT( newId != oldId,
"GLMoleculeObject_molecule::resetIndex() - index "+toString(newId)+" did not change.");
LOG(4, "INFO: GLMoleculeObject_molecule: new index is "+toString(newId)+".");
setObjectId(newId);
}
void GLMoleculeObject_molecule::resetSelected()
{
const bool new_selected = ObservedMolecule->getMolSelected();
m_selected = new_selected;
emit changed();
}
void GLMoleculeObject_molecule::initialize(QGLView *view, QGLPainter *painter)
{
// Initialize all of the mesh objects that we have as children.
if (m_visible) {
GLMoleculeObject::initialize(view, painter);
} else {
foreach (QObject *obj, children()) {
GLMoleculeObject *meshobj = qobject_cast(obj);
if (meshobj)
meshobj->initialize(view, painter);
}
}
}
void GLMoleculeObject_molecule::draw(QGLPainter *painter, const QVector4D &cameraPlane)
{
// draw either molecule's mesh or all atoms and bonds
if (m_visible) {
resetTesselationHull();
painter->modelViewMatrix().push();
// Apply the material and effect to the painter.
QGLMaterial *material;
if (m_hovering)
material = m_hoverMaterial;
else if (m_selected)
material = m_selectionMaterial;
else
material = m_material;
ASSERT(material, "GLMoleculeObject::draw: chosen material is NULL");
painter->setColor(material->diffuseColor());
painter->setFaceMaterial(QGL::AllFaces, material);
if (m_effect)
painter->setUserEffect(m_effect);
else
painter->setStandardEffect(QGL::LitMaterial);
// Mark the object for object picking purposes.
int prevObjectId = painter->objectPickId();
if (m_objectId != -1)
painter->setObjectPickId(m_objectId);
m_mesh[0]->draw(painter);
// Turn off the user effect, if present.
if (m_effect)
painter->setStandardEffect(QGL::LitMaterial);
// Revert to the previous object identifier.
painter->setObjectPickId(prevObjectId);
// Restore the modelview matrix.
painter->modelViewMatrix().pop();
// GLMoleculeObject::draw(painter, cameraPlane);
} else {
// Draw all of the mesh objects that we have as children.
foreach (QObject *obj, children()) {
GLMoleculeObject *meshobj = qobject_cast(obj);
if (meshobj)
meshobj->draw(painter, cameraPlane);
}
// update bounding box prior to selection
resetBoundingBox();
painter->modelViewMatrix().push();
painter->modelViewMatrix().translate(m_position);
if (m_rotationAngle != 0.0f)
painter->modelViewMatrix().rotate(m_rotationAngle, m_rotationVector);
if ((m_scaleX != 1.0f) || (m_scaleY != 1.0f) || (m_scaleZ != 1.0f))
painter->modelViewMatrix().scale(m_scaleX, m_scaleY, m_scaleZ);
// Draw a box around the mesh, if selected.
if (m_selected)
drawSelectionBox(painter);
// Restore the modelview matrix.
painter->modelViewMatrix().pop();
}
}
/** Adds an atom of this molecule to the scene.
*
* @param _atom atom to add
*/
void GLMoleculeObject_molecule::atomInserted(QtObservedAtom::ptr _atom)
{
const ObservedValue_Index_t atomid = _atom->getIndex();
LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomInserted for atom "
<< _atom->getAtomIndex());
if (_atom) {
GLMoleculeObject_atom *atomObject =
new GLMoleculeObject_atom(
GLMoleculeObject::meshSphere,
this,
_atom);
ASSERT( atomObject != NULL,
"GLMoleculeObject_molecule::atomInserted - could not create atom object for "
+toString(_atom->getAtomIndex()));
AtomNodeMap::iterator iter = AtomsinSceneMap.find(atomid);
ASSERT(iter == AtomsinSceneMap.end(),
"GLMoleculeObject_molecule::atomInserted - same atom with id "
+toString(_atom->getAtomIndex())+" added again.");
AtomsinSceneMap.insert( make_pair(atomid, atomObject) );
qRegisterMetaType("atomId_t");
qRegisterMetaType("GLMoleculeObject_bond::SideOfBond");
connect (atomObject, SIGNAL(clicked(atomId_t)), this, SIGNAL(atomClicked(atomId_t)));
connect (atomObject, SIGNAL(changed()), this, SIGNAL(changed()));
connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
if (m_objectId == -1)
setObjectId(_atom->getAtomIndex());
emit changed();
emit changeOccured();
}
}
/** Removes an atom of this molecule from the scene.
*
* We just the id as the atom might have already been destroyed.
*
* @param _id id of atom to remove
*/
void GLMoleculeObject_molecule::atomRemoved(ObservedValue_Index_t _id)
{
LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomRemoved for atom "+toString(_id)+".");
// bonds are removed by signal coming from ~bond
// remove atoms
AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
ASSERT(iter != AtomsinSceneMap.end(),
"GLMoleculeObject_molecule::atomRemoved() - atom "+toString(_id)+" not on display.");
GLMoleculeObject_atom *atomObject = iter->second;
AtomsinSceneMap.erase(iter);
atomObject->disconnect();
delete atomObject;
emit changed();
emit changeOccured();
if (AtomsinSceneMap.empty())
emit moleculeEmptied(ObservedMolecule);
}
void GLMoleculeObject_molecule::hoverChangedSignalled(GLMoleculeObject *ob)
{
// Find the atom, ob corresponds to.
hoverAtomId = -1;
GLMoleculeObject_atom *atomObject = dynamic_cast(ob);
if (atomObject){
for (AtomNodeMap::iterator iter = AtomsinSceneMap.begin();iter != AtomsinSceneMap.end(); ++ iter){
if (iter->second == atomObject)
hoverAtomId = iter->second->objectId();
}
// Propagate signal.
emit hoverChanged(hoverAtomId);
} else {
// Find the atom, ob corresponds to.
GLMoleculeObject_molecule *moleculeObject = dynamic_cast(ob);
if (moleculeObject == this){
// Propagate signal.
emit hoverChanged(ObservedMolecule->getMolIndex(), 0);
}
}
}
/** Adds a bond to the scene.
*
* @param _bond bond to add
*/
void GLMoleculeObject_molecule::bondInserted(
QtObservedBond::ptr _bond)
{
static const std::vector< GLMoleculeObject_bond::SideOfBond > bondsides =
boost::assign::list_of
(GLMoleculeObject_bond::left)
(GLMoleculeObject_bond::right);
LOG(3, "INFO: GLWorldScene::bondInserted() - Adding bonds " << _bond->getBondIndex());
//LOG(4, "INFO: Currently present bonds " << BondsinSceneMap << ".");
const ObservedValue_Index_t bondid = _bond->getIndex();
const std::pair iters =
BondsinSceneMap.equal_range(bondid);
if (iters.first == iters.second) {
for (size_t i=0;i<2;++i) {
GLMoleculeObject_bond * bondObject =
new GLMoleculeObject_bond(GLMoleculeObject::meshCylinder, this, _bond, bondsides[i]);
connect (bondObject, SIGNAL(changed()), this, SIGNAL(changed()));
BondsinSceneMap.insert( std::make_pair(bondid, bondObject) );
}
} else {
for (BondNodeMap::iterator iter = iters.first; iter != iters.second; ++iter) {
iter->second->resetPosition();
iter->second->resetWidth();
}
}
emit changed();
emit changeOccured();
}
/** Removes a bond from the scene.
*
* @param _bond bond to remove
*/
void GLMoleculeObject_molecule::bondRemoved(ObservedValue_Index_t _id)
{
LOG(3, "INFO: GLWorldScene::bondRemoved() - Removing bond to id " << _id);
{
// left bond
const std::pair iters =
BondsinSceneMap.equal_range(_id);
for (BondNodeMap::iterator iter = iters.first; iter != iters.second; ++iter) {
GLMoleculeObject_bond *bondObject = iter->second;
bondObject->disconnect();
delete bondObject; // is done by signal from bond itself
//LOG(4, "INFO: Still present bonds " << BondsinSceneMap << ".");
}
BondsinSceneMap.erase(_id);
}
emit changed();
emit changeOccured();
}
void GLMoleculeObject_molecule::setVisible(bool value)
{
// first update the mesh if we are going to be visible now
if (value)
updateTesselationHull();
// then emit onward
GLMoleculeObject::setVisible(value);
emit changed();
emit changeOccured();
}
std::ostream &operator<<(std::ostream &ost, const GLMoleculeObject_molecule::BondIds &t)
{
ost << t.first << "," << t.second;
return ost;
}
void GLMoleculeObject_molecule::wasClicked()
{
LOG(4, "INFO: GLMoleculeObject_molecule: atom "
<< ObservedMolecule->getMolIndex() << " has been clicked");
emit moleculeClicked(ObservedMolecule->getMolIndex());
}