diff --git a/avogadro/qtplugins/centroid/centroid.cpp b/avogadro/qtplugins/centroid/centroid.cpp index b5c731893d..cfd4c658e4 100644 --- a/avogadro/qtplugins/centroid/centroid.cpp +++ b/avogadro/qtplugins/centroid/centroid.cpp @@ -7,6 +7,7 @@ #include #include +#include #include @@ -54,23 +55,22 @@ void Centroid::addCentroid() if (m_molecule == nullptr || m_molecule->atomCount() == 0) return; - if (m_molecule->isSelectionEmpty()) { - m_molecule->addAtom(0, m_molecule->centerOfGeometry()); - } else { - Vector3 center; - Index selectedCount = 0; - for (Index i = 0; i < m_molecule->atomCount(); ++i) { - if (!m_molecule->atomSelected(i)) - continue; - - center += m_molecule->atomPosition3d(i); - ++selectedCount; - } - center /= selectedCount; - - m_molecule->addAtom(0, center); + Vector3 center; + Index count = 0; + bool hasSelection = !m_molecule->isSelectionEmpty(); + for (Index i = 0; i < m_molecule->atomCount(); ++i) { + if (hasSelection && !m_molecule->atomSelected(i)) + continue; + // don't count dummy atoms + if (m_molecule->atomicNumber(i) == 0) + continue; + + center += m_molecule->atomPosition3d(i); + ++count; } + center /= count; + m_molecule->undoMolecule()->addAtom(0, center); m_molecule->emitChanged(QtGui::Molecule::Atoms | QtGui::Molecule::Added); } @@ -79,29 +79,28 @@ void Centroid::addCenterOfMass() if (m_molecule == nullptr || m_molecule->atomCount() == 0) return; - if (m_molecule->isSelectionEmpty()) { - m_molecule->addAtom(0, m_molecule->centerOfMass()); - } else { - Vector3 center; - Index selectedCount = 0; - Real totalMass = 0.0; + Vector3 center; + Real totalMass = 0.0; + Index count = 0; + bool hasSelection = !m_molecule->isSelectionEmpty(); - for (Index i = 0; i < m_molecule->atomCount(); ++i) { - if (!m_molecule->atomSelected(i)) - continue; - - Real mass = Elements::mass(m_molecule->atomicNumber(i)); - center += m_molecule->atomPosition3d(i) * mass; + // we have to first find the centroid + for (Index i = 0; i < m_molecule->atomCount(); ++i) { + if (hasSelection && !m_molecule->atomSelected(i)) + continue; + // skip it if it's a dummy atom + if (m_molecule->atomicNumber(i) == 0) + continue; - totalMass += mass; - ++selectedCount; - } - center /= selectedCount; - center /= totalMass; + Real mass = Elements::mass(m_molecule->atomicNumber(i)); + center += m_molecule->atomPosition3d(i) * mass; - m_molecule->addAtom(0, center); + totalMass += mass; + ++count; } + center /= totalMass; + m_molecule->undoMolecule()->addAtom(0, center); m_molecule->emitChanged(QtGui::Molecule::Atoms | QtGui::Molecule::Added); }