moldyn.cpp 34.8 KB
Newer Older
1
/**
Tobias WEBER's avatar
Tobias WEBER committed
2
 * atom dynamics
3 4 5 6 7
 * @author Tobias Weber <tweber@ill.fr>
 * @date Dec-2019
 * @license GPLv3, see 'LICENSE' file
 */

Tobias WEBER's avatar
Tobias WEBER committed
8
#include "moldyn.h"
9

Tobias WEBER's avatar
Tobias WEBER committed
10
#include <QtWidgets/QApplication>
Tobias WEBER's avatar
Tobias WEBER committed
11
#include <QtWidgets/QGridLayout>
Tobias WEBER's avatar
Tobias WEBER committed
12
#include <QtWidgets/QFileDialog>
Tobias WEBER's avatar
Tobias WEBER committed
13
#include <QtWidgets/QSpinBox>
Tobias WEBER's avatar
Tobias WEBER committed
14
#include <QtWidgets/QComboBox>
Tobias WEBER's avatar
Tobias WEBER committed
15
#include <QtWidgets/QMessageBox>
16
#include <QtWidgets/QProgressDialog>
17

Tobias WEBER's avatar
Tobias WEBER committed
18 19
#include <iostream>
#include <tuple>
Tobias WEBER's avatar
Tobias WEBER committed
20
#include <memory>
21

Tobias WEBER's avatar
Tobias WEBER committed
22 23 24 25 26 27 28 29 30
#include "libs/algos.h"
#include "libs/helper.h"

using namespace m_ops;

constexpr t_real g_eps = 1e-6;
constexpr int g_prec = 6;


Tobias WEBER's avatar
Tobias WEBER committed
31
#define PROG_NAME "Molecular Dynamics Tool"
32
#define PROG_VER "0.2"
Tobias WEBER's avatar
Tobias WEBER committed
33 34


Tobias WEBER's avatar
Tobias WEBER committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

// ----------------------------------------------------------------------------
/**
 * File dialog with options
 */
class MolDynFileDlg : public QFileDialog
{
	public:
		MolDynFileDlg(QWidget *parent, const QString& title, const QString& dir, const QString& filter)
			: QFileDialog(parent, title, dir, filter)
		{
			// options panel with frame skip
			QLabel *labelFrameSkip = new QLabel("Frame Skip: ", this);
			m_spinFrameSkip = new QSpinBox(this);
			m_spinFrameSkip->setValue(10);
Tobias WEBER's avatar
Tobias WEBER committed
50 51
			m_spinFrameSkip->setSingleStep(1);
			m_spinFrameSkip->setRange(0, 9999999);
Tobias WEBER's avatar
Tobias WEBER committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

			labelFrameSkip->setSizePolicy(QSizePolicy{QSizePolicy::Fixed, QSizePolicy::Fixed});
			m_spinFrameSkip->setSizePolicy(QSizePolicy{QSizePolicy::Expanding, QSizePolicy::Fixed});

			QWidget *pPanel = new QWidget();
			auto pPanelGrid = new QGridLayout(pPanel);
			pPanelGrid->setSpacing(2);
			pPanelGrid->setContentsMargins(4,4,4,4);

			pPanelGrid->addWidget(labelFrameSkip, 0,0,1,1);
			pPanelGrid->addWidget(m_spinFrameSkip, 0,1,1,1);

			// add the options panel to the layout
			setOptions(QFileDialog::DontUseNativeDialog);
			QGridLayout *pGrid = reinterpret_cast<QGridLayout*>(layout());
			if(pGrid)
				pGrid->addWidget(pPanel, pGrid->rowCount(), 0, 1, pGrid->columnCount());
		}


		int GetFrameSkip() const
		{
			return m_spinFrameSkip->value();
		}


	private:
		QSpinBox *m_spinFrameSkip = nullptr;
};
Tobias WEBER's avatar
Tobias WEBER committed
81
// ----------------------------------------------------------------------------
Tobias WEBER's avatar
Tobias WEBER committed
82 83 84



Tobias WEBER's avatar
Tobias WEBER committed
85 86 87 88
// ----------------------------------------------------------------------------
MolDynDlg::MolDynDlg(QWidget* pParent) : QMainWindow{pParent},
	m_sett{new QSettings{"tobis_stuff", "moldyn"}}
{
89
	setWindowTitle(QString(PROG_NAME) + QString(" Version ") + QString(PROG_VER));
Tobias WEBER's avatar
Tobias WEBER committed
90 91 92
	this->setObjectName("moldyn");

	m_status = new QStatusBar(this);
Tobias WEBER's avatar
Tobias WEBER committed
93
	m_statusCurAtom = new QLabel(m_status);
Tobias WEBER's avatar
Tobias WEBER committed
94
	m_statusAtoms = new QLabel(m_status);
Tobias WEBER's avatar
Tobias WEBER committed
95
	m_status->addWidget(m_statusCurAtom);
Tobias WEBER's avatar
Tobias WEBER committed
96
	m_status->addPermanentWidget(m_statusAtoms);
Tobias WEBER's avatar
Tobias WEBER committed
97 98 99
	this->setStatusBar(m_status);


Tobias WEBER's avatar
Tobias WEBER committed
100 101 102 103 104 105 106
	QWidget *pMainPanel = new QWidget();
	auto pMainGrid = new QGridLayout(pMainPanel);
	pMainGrid->setSpacing(2);
	pMainGrid->setContentsMargins(4,4,4,4);
	this->setCentralWidget(pMainPanel);


Tobias WEBER's avatar
Tobias WEBER committed
107 108 109 110 111
	// menu bar
	{
		m_menu = new QMenuBar(this);
		m_menu->setNativeMenuBar(m_sett ? m_sett->value("native_gui", false).toBool() : false);

Tobias WEBER's avatar
Tobias WEBER committed
112

Tobias WEBER's avatar
Tobias WEBER committed
113
		// File
Tobias WEBER's avatar
Tobias WEBER committed
114 115 116 117
		auto menuFile = new QMenu("File", m_menu);

		auto acNew = new QAction("New", menuFile);
		auto acLoad = new QAction("Load...", menuFile);
Tobias WEBER's avatar
Tobias WEBER committed
118
		auto acSaveAs = new QAction("Save As...", menuFile);
Tobias WEBER's avatar
Tobias WEBER committed
119 120 121 122 123
		auto acExit = new QAction("Exit", menuFile);

		menuFile->addAction(acNew);
		menuFile->addSeparator();
		menuFile->addAction(acLoad);
Tobias WEBER's avatar
Tobias WEBER committed
124
		menuFile->addAction(acSaveAs);
Tobias WEBER's avatar
Tobias WEBER committed
125 126 127 128 129
		menuFile->addSeparator();
		menuFile->addAction(acExit);

		connect(acNew, &QAction::triggered, this, &MolDynDlg::New);
		connect(acLoad, &QAction::triggered, this, &MolDynDlg::Load);
Tobias WEBER's avatar
Tobias WEBER committed
130
		connect(acSaveAs, &QAction::triggered, this, &MolDynDlg::SaveAs);
Tobias WEBER's avatar
Tobias WEBER committed
131 132
		connect(acExit, &QAction::triggered, this, &QDialog::close);

Tobias WEBER's avatar
Tobias WEBER committed
133 134

		// Edit
Tobias WEBER's avatar
Tobias WEBER committed
135
		auto menuEdit = new QMenu("Edit", m_menu);
Tobias WEBER's avatar
Tobias WEBER committed
136
		auto acSelectAll = new QAction("Select All", menuEdit);
Tobias WEBER's avatar
Tobias WEBER committed
137 138
		auto acSelectNone = new QAction("Select None", menuEdit);

Tobias WEBER's avatar
Tobias WEBER committed
139
		menuEdit->addAction(acSelectAll);
Tobias WEBER's avatar
Tobias WEBER committed
140 141
		menuEdit->addAction(acSelectNone);

Tobias WEBER's avatar
Tobias WEBER committed
142
		connect(acSelectAll, &QAction::triggered, this, &MolDynDlg::SelectAll);
Tobias WEBER's avatar
Tobias WEBER committed
143 144 145 146 147
		connect(acSelectNone, &QAction::triggered, this, &MolDynDlg::SelectNone);


		// Calculate
		auto menuCalc = new QMenu("Calculate", m_menu);
Tobias WEBER's avatar
Tobias WEBER committed
148 149 150
		auto acCalcDist = new QAction("Distance Between Selected Atoms...", menuEdit);
		auto acCalcPos = new QAction("Positions Of Selected Atoms...", menuEdit);
		auto acCalcDeltaDist = new QAction("Distances to Initial Position of Selected Atoms...", menuEdit);
Tobias WEBER's avatar
Tobias WEBER committed
151 152

		menuCalc->addAction(acCalcDist);
Tobias WEBER's avatar
Tobias WEBER committed
153 154
		menuCalc->addAction(acCalcPos);
		menuCalc->addAction(acCalcDeltaDist);
Tobias WEBER's avatar
Tobias WEBER committed
155 156

		connect(acCalcDist, &QAction::triggered, this, &MolDynDlg::CalculateDistanceBetweenAtoms);
Tobias WEBER's avatar
Tobias WEBER committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170
		connect(acCalcPos, &QAction::triggered, this, &MolDynDlg::CalculatePositionsOfAtoms);
		connect(acCalcDeltaDist, &QAction::triggered, this, &MolDynDlg::CalculateDeltaDistancesOfAtoms);


		// Help
		auto menuHelp = new QMenu("Help", m_menu);
		auto acHelpInfo = new QAction("Infos...", menuHelp);

		menuHelp->addAction(acHelpInfo);

		connect(acHelpInfo, &QAction::triggered, this, [this]()
		{
			QString strHelp;

171
			strHelp = QString{PROG_NAME} + " v" + QString{PROG_VER} + ", part of the Takin 2 package.\n";
Tobias WEBER's avatar
Tobias WEBER committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185
			strHelp += "Written by Tobias Weber <tweber@ill.fr>\nin December 2019.\n\n";

			strHelp += "This program 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, version 3 of the License.\n\n"
				"This program 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.\n\n"
				"You should have received a copy of the GNU General Public License "
				"along with this program.  If not, see <http://www.gnu.org/licenses/>.";

			QMessageBox::information(this, PROG_NAME, strHelp);
		});
Tobias WEBER's avatar
Tobias WEBER committed
186 187


Tobias WEBER's avatar
Tobias WEBER committed
188
		m_menu->addMenu(menuFile);
Tobias WEBER's avatar
Tobias WEBER committed
189 190
		m_menu->addMenu(menuEdit);
		m_menu->addMenu(menuCalc);
Tobias WEBER's avatar
Tobias WEBER committed
191
		m_menu->addMenu(menuHelp);
Tobias WEBER's avatar
Tobias WEBER committed
192 193 194 195
		this->setMenuBar(m_menu);
	}


Tobias WEBER's avatar
Tobias WEBER committed
196 197 198 199 200
	// context menus
	{
		m_atomContextMenu = new QMenu(this);
		m_atomContextMenu->setTitle("Atoms");
		m_atomContextMenu->addAction("Delete Atom", this, &MolDynDlg::DeleteAtomUnderCursor);
201 202 203 204
        m_atomContextMenu->addSeparator();
        m_atomContextMenu->addAction("Delete Selected Atoms", this, &MolDynDlg::DeleteSelectedAtoms);
        m_atomContextMenu->addAction("Delete All But Selected Atoms", this, &MolDynDlg::OnlyKeepSelectedAtoms);
        m_atomContextMenu->addSeparator();
Tobias WEBER's avatar
Tobias WEBER committed
205 206
		m_atomContextMenu->addAction("Delete All Atoms Of Selected Type", this, &MolDynDlg::DeleteAllAtomsOfSameType);
		m_atomContextMenu->addAction("Only Keep Atoms Of Selected Type", this, &MolDynDlg::KeepAtomsOfSameType);
Tobias WEBER's avatar
Tobias WEBER committed
207 208
		m_atomContextMenu->addSeparator();
		m_atomContextMenu->addAction("Select All Atoms of Same Type", this, &MolDynDlg::SelectAtomsOfSameType);
Tobias WEBER's avatar
Tobias WEBER committed
209 210 211
	}


Tobias WEBER's avatar
Tobias WEBER committed
212 213 214 215 216
	// plot widget
	{
		m_plot = new GlPlot(this);
		m_plot->setSizePolicy(QSizePolicy{QSizePolicy::Expanding, QSizePolicy::Expanding});

Tobias WEBER's avatar
Tobias WEBER committed
217
		m_plot->GetImpl()->EnablePicker(1);
Tobias WEBER's avatar
Tobias WEBER committed
218 219 220 221 222 223 224
		m_plot->GetImpl()->SetLight(0, m::create<t_vec3_gl>({ 5, 5, 5 }));
		m_plot->GetImpl()->SetLight(1, m::create<t_vec3_gl>({ -5, -5, -5 }));
		m_plot->GetImpl()->SetCoordMax(1.);
		m_plot->GetImpl()->SetCamBase(m::create<t_mat_gl>({1,0,0,0,  0,0,1,0,  0,-1,0,-1.5,  0,0,0,1}),
			m::create<t_vec_gl>({1,0,0,0}), m::create<t_vec_gl>({0,0,1,0}));

		connect(m_plot, &GlPlot::AfterGLInitialisation, this, &MolDynDlg::AfterGLInitialisation);
Tobias WEBER's avatar
Tobias WEBER committed
225
		connect(m_plot, &GlPlot::GLInitialisationFailed, this, &MolDynDlg::GLInitialisationFailed);
Tobias WEBER's avatar
Tobias WEBER committed
226 227 228
		connect(m_plot->GetImpl(), &GlPlot_impl::PickerIntersection, this, &MolDynDlg::PickerIntersection);
		connect(m_plot, &GlPlot::MouseDown, this, &MolDynDlg::PlotMouseDown);
		connect(m_plot, &GlPlot::MouseUp, this, &MolDynDlg::PlotMouseUp);
Tobias WEBER's avatar
Tobias WEBER committed
229
		connect(m_plot, &GlPlot::MouseClick, this, &MolDynDlg::PlotMouseClick);
Tobias WEBER's avatar
Tobias WEBER committed
230

Tobias WEBER's avatar
Tobias WEBER committed
231
		//this->setCentralWidget(m_plot);
Tobias WEBER's avatar
Tobias WEBER committed
232
		pMainGrid->addWidget(m_plot, 0,0,1,9);
Tobias WEBER's avatar
Tobias WEBER committed
233 234 235 236 237
	}


	// controls
	{
Tobias WEBER's avatar
Tobias WEBER committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
		auto labCoordSys = new QLabel("Coordinates:", this);
		auto labFrames = new QLabel("Frames:", this);
		auto labScale = new QLabel("Scale:", this);
		labCoordSys->setSizePolicy(QSizePolicy{QSizePolicy::Fixed, QSizePolicy::Fixed});
		labFrames->setSizePolicy(QSizePolicy{QSizePolicy::Fixed, QSizePolicy::Fixed});
		labScale->setSizePolicy(QSizePolicy{QSizePolicy::Fixed, QSizePolicy::Fixed});

		auto comboCoordSys = new QComboBox(this);
		comboCoordSys->addItem("Fractional Units (rlu)");
		comboCoordSys->addItem("Lab Units (A)");
		comboCoordSys->setFocusPolicy(Qt::StrongFocus);

		m_spinScale = new QDoubleSpinBox(this);
		m_spinScale->setDecimals(4);
		m_spinScale->setRange(1e-4, 1e4);
		m_spinScale->setSingleStep(0.1);
		m_spinScale->setValue(0.4);
		m_spinScale->setFocusPolicy(Qt::StrongFocus);

Tobias WEBER's avatar
Tobias WEBER committed
257 258 259
		m_slider = new QSlider(Qt::Horizontal, this);
		m_slider->setSizePolicy(QSizePolicy{QSizePolicy::Expanding, QSizePolicy::Minimum});
		m_slider->setMinimum(0);
Tobias WEBER's avatar
Tobias WEBER committed
260 261
		m_slider->setSingleStep(1);
		m_slider->setPageStep(10);
Tobias WEBER's avatar
Tobias WEBER committed
262
		m_slider->setTracking(1);
Tobias WEBER's avatar
Tobias WEBER committed
263
		m_slider->setFocusPolicy(Qt::StrongFocus);
Tobias WEBER's avatar
Tobias WEBER committed
264 265

		connect(m_slider, &QSlider::valueChanged, this, &MolDynDlg::SliderValueChanged);
Tobias WEBER's avatar
Tobias WEBER committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
		connect(comboCoordSys, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int val)
		{
			if(this->m_plot)
				this->m_plot->GetImpl()->SetCoordSys(val);
		});
		connect(m_spinScale, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, [this](double val)
		{
			if(!this->m_plot) return;

			// hack to trigger update
			SliderValueChanged(m_slider->value());
		});

		pMainGrid->addWidget(labCoordSys, 1,0,1,1);
		pMainGrid->addWidget(comboCoordSys, 1,1,1,1);
		pMainGrid->addWidget(labScale, 1,2,1,1);
		pMainGrid->addWidget(m_spinScale, 1,3,1,1);
		pMainGrid->addWidget(labFrames, 1,4,1,1);
		pMainGrid->addWidget(m_slider, 1,5,1,4);
Tobias WEBER's avatar
Tobias WEBER committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
	}


	// restore window size and position
	if(m_sett && m_sett->contains("geo"))
		restoreGeometry(m_sett->value("geo").toByteArray());
	else
		resize(600, 500);

	m_ignoreChanges = 0;
}



// ----------------------------------------------------------------------------
/**
Tobias WEBER's avatar
Tobias WEBER committed
301
 * add an atom
Tobias WEBER's avatar
Tobias WEBER committed
302
 */
303
std::size_t MolDynDlg::Add3DItem(const t_vec& vec, const t_vec& col, t_real scale, const std::string& label)
Tobias WEBER's avatar
Tobias WEBER committed
304
{
Tobias WEBER's avatar
Tobias WEBER committed
305
	auto obj = m_plot->GetImpl()->AddLinkedObject(m_sphere, 0,0,0, col[0],col[1],col[2],1);
Tobias WEBER's avatar
Tobias WEBER committed
306
	Change3DItem(obj, &vec, &col, &scale, &label);
307
	return obj;
Tobias WEBER's avatar
Tobias WEBER committed
308
}
Tobias WEBER's avatar
Tobias WEBER committed
309 310 311 312 313 314 315


/**
 * change an atom
 */
void MolDynDlg::Change3DItem(std::size_t obj, const t_vec *vec, const t_vec *col, const t_real *scale, const std::string *label)
{
Tobias WEBER's avatar
Tobias WEBER committed
316 317 318 319 320 321
	if(vec)
	{
		t_mat_gl mat = m::hom_translation<t_mat_gl>((*vec)[0], (*vec)[1], (*vec)[2]);
		if(scale) mat *= m::hom_scaling<t_mat_gl>(*scale, *scale, *scale);
		m_plot->GetImpl()->SetObjectMatrix(obj, mat);
	}
Tobias WEBER's avatar
Tobias WEBER committed
322 323 324 325 326

	if(col) m_plot->GetImpl()->SetObjectCol(obj, (*col)[0], (*col)[1], (*col)[2], 1);
	if(label) m_plot->GetImpl()->SetObjectLabel(obj, *label);
	if(label) m_plot->GetImpl()->SetObjectDataString(obj, *label);
}
Tobias WEBER's avatar
Tobias WEBER committed
327 328 329 330
// ----------------------------------------------------------------------------



Tobias WEBER's avatar
Tobias WEBER committed
331 332 333 334 335 336
// ----------------------------------------------------------------------------
/**
 * calculate the distance between selected atoms
 */
void MolDynDlg::CalculateDistanceBetweenAtoms()
{
Tobias WEBER's avatar
Tobias WEBER committed
337
	try
Tobias WEBER's avatar
Tobias WEBER committed
338
	{
Tobias WEBER's avatar
Tobias WEBER committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
		// get selected atoms
		std::vector<std::tuple<std::size_t, std::size_t>> objs;

		for(const auto& obj : m_sphereHandles)
		{
			// continue if object isn't selected
			if(!m_plot->GetImpl()->GetObjectHighlight(obj))
				continue;

			// get indices for selected atoms
			const auto [bOk, atomTypeIdx, atomSubTypeIdx, sphereIdx] = GetAtomIndexFromHandle(obj);
			if(!bOk)
			{
				QMessageBox::critical(this, PROG_NAME, "Atom handle not found, data is corrupted.");
				return;
			}

			objs.push_back(std::make_tuple(atomTypeIdx, atomSubTypeIdx));
		}
Tobias WEBER's avatar
Tobias WEBER committed
358

Tobias WEBER's avatar
Tobias WEBER committed
359
		if(objs.size() <= 1)
Tobias WEBER's avatar
Tobias WEBER committed
360
		{
Tobias WEBER's avatar
Tobias WEBER committed
361
			QMessageBox::critical(this, PROG_NAME, "At least two atoms have to be selected.");
Tobias WEBER's avatar
Tobias WEBER committed
362 363 364 365
			return;
		}


Tobias WEBER's avatar
Tobias WEBER committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
		// create file
		QString dirLast = m_sett->value("dir", "").toString();
		QString filename = QFileDialog::getSaveFileName(this, "Save File", dirLast, "Data File (*.dat)");
		if(filename == "")
			return;

		std::ofstream ofstr(filename.toStdString());
		if(!ofstr)
		{
			QMessageBox::critical(this, PROG_NAME, "Cannot open file.");
			return;
		}

		ofstr.precision(g_prec);
		m_sett->setValue("dir", QFileInfo(filename).path());


		// get coordinates of first atom
		auto [firstObjTypeIdx, firstObjSubTypeIdx] = objs[0];
		auto firstObjCoords = m_mol.GetAtomCoords(firstObjTypeIdx, firstObjSubTypeIdx);


		ofstr << "# Column 1: Frame\n";
		ofstr << "# Columns 2, 3, ...: Distances to first atom (A)\n";

		// progress dialog
		std::shared_ptr<QProgressDialog> dlgProgress = std::make_shared<QProgressDialog>(
			"Calculating...", "Cancel", 1, objs.size(), this);
		dlgProgress->setWindowModality(Qt::WindowModal);

		// get distances to other selected atoms
		for(std::size_t objIdx=1; objIdx<objs.size(); ++objIdx)
		{
			auto [objTypeIdx, objSubTypeIdx] = objs[objIdx];
			const auto objCoords = m_mol.GetAtomCoords(objTypeIdx, objSubTypeIdx);
Tobias WEBER's avatar
Tobias WEBER committed
401

Tobias WEBER's avatar
Tobias WEBER committed
402 403 404 405
			for(std::size_t frameidx=0; frameidx<m_mol.GetFrameCount(); ++frameidx)
			{
				t_real dist = m::get_dist_uc(m_crystA, firstObjCoords[frameidx], objCoords[frameidx]);

Tobias WEBER's avatar
Tobias WEBER committed
406
				ofstr
Tobias WEBER's avatar
Tobias WEBER committed
407 408 409 410 411 412 413 414 415 416 417 418 419
					<< std::left << std::setw(g_prec*1.5) << frameidx << " "
					<< std::left << std::setw(g_prec*1.5) << dist << "\n";
			}

			dlgProgress->setValue(objIdx+1);
			if(dlgProgress->wasCanceled())
			{
				ofstr << "\n# WARNING: Calculation aborted by user.\n";
				break;
			}
		}
	}
	catch(const std::exception& ex)
Tobias WEBER's avatar
Tobias WEBER committed
420
	{
Tobias WEBER's avatar
Tobias WEBER committed
421
		QMessageBox::critical(this, PROG_NAME, ex.what());
Tobias WEBER's avatar
Tobias WEBER committed
422
	}
Tobias WEBER's avatar
Tobias WEBER committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
}



/**
 * calculate positions of selected atoms
 */
void MolDynDlg::CalculatePositionsOfAtoms()
{
	try
	{
		// get selected atoms
		std::vector<std::tuple<std::size_t, std::size_t>> objs;

		for(const auto& obj : m_sphereHandles)
		{
			// continue if object isn't selected
			if(!m_plot->GetImpl()->GetObjectHighlight(obj))
				continue;

			// get indices for selected atoms
			const auto [bOk, atomTypeIdx, atomSubTypeIdx, sphereIdx] = GetAtomIndexFromHandle(obj);
			if(!bOk)
			{
				QMessageBox::critical(this, PROG_NAME, "Atom handle not found, data is corrupted.");
				return;
			}

			objs.push_back(std::make_tuple(atomTypeIdx, atomSubTypeIdx));
		}

		if(objs.size() <= 0)
		{
			QMessageBox::critical(this, PROG_NAME, "At least one atom has to be selected.");
			return;
		}


		// create file
		QString dirLast = m_sett->value("dir", "").toString();
		QString filename = QFileDialog::getSaveFileName(this, "Save File", dirLast, "Data File (*.dat)");
		if(filename == "")
			return;

		std::ofstream ofstr(filename.toStdString());
		if(!ofstr)
		{
			QMessageBox::critical(this, PROG_NAME, "Cannot open file.");
			return;
		}

		ofstr.precision(g_prec);
		m_sett->setValue("dir", QFileInfo(filename).path());
Tobias WEBER's avatar
Tobias WEBER committed
476 477


Tobias WEBER's avatar
Tobias WEBER committed
478 479 480 481 482 483 484
		ofstr << "# Column 1: Frame\n";
		ofstr << "# Columns 2, 3, 4: x, y, z position of atom  (A)\n";

		// progress dialog
		std::shared_ptr<QProgressDialog> dlgProgress = std::make_shared<QProgressDialog>(
			"Calculating...", "Cancel", 0, m_mol.GetFrameCount(), this);
		dlgProgress->setWindowModality(Qt::WindowModal);
Tobias WEBER's avatar
Tobias WEBER committed
485

Tobias WEBER's avatar
Tobias WEBER committed
486 487 488 489
		// iterate all selected atoms
		for(std::size_t frameidx=0; frameidx<m_mol.GetFrameCount(); ++frameidx)
		{
			ofstr << std::left << std::setw(g_prec*1.5) << frameidx << " ";
Tobias WEBER's avatar
Tobias WEBER committed
490

Tobias WEBER's avatar
Tobias WEBER committed
491 492 493 494
			for(std::size_t objIdx=0; objIdx<objs.size(); ++objIdx)
			{
				auto [objTypeIdx, objSubTypeIdx] = objs[objIdx];
				const t_vec& coords = m_mol.GetAtomCoords(objTypeIdx, objSubTypeIdx, frameidx);
Tobias WEBER's avatar
Tobias WEBER committed
495

Tobias WEBER's avatar
Tobias WEBER committed
496 497 498 499 500
				ofstr 
					<< std::left << std::setw(g_prec*1.5) << coords[0] << " "
					<< std::left << std::setw(g_prec*1.5) << coords[1] << " "
					<< std::left << std::setw(g_prec*1.5) << coords[2] << "  ";
			}
Tobias WEBER's avatar
Tobias WEBER committed
501

Tobias WEBER's avatar
Tobias WEBER committed
502
			ofstr << "\n";
Tobias WEBER's avatar
Tobias WEBER committed
503

Tobias WEBER's avatar
Tobias WEBER committed
504 505 506 507 508 509 510 511 512
			dlgProgress->setValue(frameidx+1);
			if(dlgProgress->wasCanceled())
			{
				ofstr << "\n# WARNING: Calculation aborted by user.\n";
				break;
			}
		}
	}
	catch(const std::exception& ex)
Tobias WEBER's avatar
Tobias WEBER committed
513
	{
Tobias WEBER's avatar
Tobias WEBER committed
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
		QMessageBox::critical(this, PROG_NAME, ex.what());
	}
}



/**
 * calculate distance to initial positions of selected atoms
 */
void MolDynDlg::CalculateDeltaDistancesOfAtoms()
{
	try
	{
		// get selected atoms
		std::vector<std::tuple<std::size_t, std::size_t>> objs;

		for(const auto& obj : m_sphereHandles)
		{
			// continue if object isn't selected
			if(!m_plot->GetImpl()->GetObjectHighlight(obj))
				continue;

			// get indices for selected atoms
			const auto [bOk, atomTypeIdx, atomSubTypeIdx, sphereIdx] = GetAtomIndexFromHandle(obj);
			if(!bOk)
			{
				QMessageBox::critical(this, PROG_NAME, "Atom handle not found, data is corrupted.");
				return;
			}

			objs.push_back(std::make_tuple(atomTypeIdx, atomSubTypeIdx));
		}

		if(objs.size() <= 0)
		{
			QMessageBox::critical(this, PROG_NAME, "At least one atom has to be selected.");
			return;
		}


		// create file
		QString dirLast = m_sett->value("dir", "").toString();
		QString filename = QFileDialog::getSaveFileName(this, "Save File", dirLast, "Data File (*.dat)");
		if(filename == "")
			return;

		std::ofstream ofstr(filename.toStdString());
		if(!ofstr)
		{
			QMessageBox::critical(this, PROG_NAME, "Cannot open file.");
			return;
		}

		ofstr.precision(g_prec);
		m_sett->setValue("dir", QFileInfo(filename).path());


		ofstr << "# Column 1: Frame\n";
		ofstr << "# Column 2, 3, ...: Distance delta (A)\n";

		// progress dialog
		std::shared_ptr<QProgressDialog> dlgProgress = std::make_shared<QProgressDialog>(
			"Calculating...", "Cancel", 0, m_mol.GetFrameCount(), this);
		dlgProgress->setWindowModality(Qt::WindowModal);

		// iterate all selected atoms
Tobias WEBER's avatar
Tobias WEBER committed
580 581
		for(std::size_t frameidx=0; frameidx<m_mol.GetFrameCount(); ++frameidx)
		{
Tobias WEBER's avatar
Tobias WEBER committed
582 583 584 585 586 587 588 589 590
			ofstr << std::left << std::setw(g_prec*1.5) << frameidx << " ";

			for(std::size_t objIdx=0; objIdx<objs.size(); ++objIdx)
			{
				auto [objTypeIdx, objSubTypeIdx] = objs[objIdx];
			 	const t_vec& coords = m_mol.GetAtomCoords(objTypeIdx, objSubTypeIdx, frameidx);
				const t_vec& coordsInitial = m_mol.GetAtomCoords(objTypeIdx, objSubTypeIdx, 0);

				t_real dist = m::get_dist_uc(m_crystA, coords, coordsInitial);
Tobias WEBER's avatar
Tobias WEBER committed
591

Tobias WEBER's avatar
Tobias WEBER committed
592 593 594 595 596 597 598 599 600 601 602
				ofstr << std::left << std::setw(g_prec*1.5) << dist << " ";
			}

			ofstr << "\n";

			dlgProgress->setValue(frameidx+1);
			if(dlgProgress->wasCanceled())
			{
				ofstr << "\n# WARNING: Calculation aborted by user.\n";
				break;
			}
Tobias WEBER's avatar
Tobias WEBER committed
603 604
		}
	}
Tobias WEBER's avatar
Tobias WEBER committed
605 606 607 608
	catch(const std::exception& ex)
	{
		QMessageBox::critical(this, PROG_NAME, ex.what());
	}
Tobias WEBER's avatar
Tobias WEBER committed
609 610 611 612
}
// ----------------------------------------------------------------------------


Tobias WEBER's avatar
Tobias WEBER committed
613 614 615 616

// ----------------------------------------------------------------------------
void MolDynDlg::New()
{
Tobias WEBER's avatar
Tobias WEBER committed
617
	m_mol.Clear();
Tobias WEBER's avatar
Tobias WEBER committed
618 619 620 621

	for(const auto& obj : m_sphereHandles)
		m_plot->GetImpl()->RemoveObject(obj);

622
	m_sphereHandles.clear();
Tobias WEBER's avatar
Tobias WEBER committed
623 624 625
	m_slider->setValue(0);

	m_plot->update();
Tobias WEBER's avatar
Tobias WEBER committed
626 627 628 629 630
}


void MolDynDlg::Load()
{
631 632
	if(!m_plot) return;

Tobias WEBER's avatar
Tobias WEBER committed
633 634 635
	try
	{
		QString dirLast = m_sett->value("dir", "").toString();
Tobias WEBER's avatar
Tobias WEBER committed
636 637 638 639 640 641
		auto filedlg = std::make_shared<MolDynFileDlg>(this, "Load File", dirLast, "Molecular Dynamics File (*)");
		if(!filedlg->exec())
			return;
		auto files = filedlg->selectedFiles();
		if(!files.size())
			return;
Tobias WEBER's avatar
Tobias WEBER committed
642

Tobias WEBER's avatar
Tobias WEBER committed
643
		QString filename = files[0];
Tobias WEBER's avatar
Tobias WEBER committed
644
		if(filename == "" || !QFile::exists(filename))
Tobias WEBER's avatar
Tobias WEBER committed
645 646 647
			return;
		m_sett->setValue("dir", QFileInfo(filename).path());

Tobias WEBER's avatar
Tobias WEBER committed
648
		New();
649

Tobias WEBER's avatar
Tobias WEBER committed
650

651 652 653
		std::shared_ptr<QProgressDialog> dlgProgress = std::make_shared<QProgressDialog>(
			"Loading \"" + QFileInfo(filename).fileName() + "\"...", "Cancel", 0, 1000, this);
		bool bCancelled = 0;
Tobias WEBER's avatar
Tobias WEBER committed
654
		auto progressHandler = [dlgProgress, &bCancelled](t_real percentage) -> bool
655 656 657 658
		{
			dlgProgress->setValue(int(percentage*10));
			bCancelled = dlgProgress->wasCanceled();
			return !bCancelled;
Tobias WEBER's avatar
Tobias WEBER committed
659 660
		};
		m_mol.SubscribeToLoadProgress(progressHandler);
661 662
		dlgProgress->setWindowModality(Qt::WindowModal);

Tobias WEBER's avatar
Tobias WEBER committed
663

Tobias WEBER's avatar
Tobias WEBER committed
664
		if(!m_mol.LoadFile(filename.toStdString(), filedlg->GetFrameSkip()))
Tobias WEBER's avatar
Tobias WEBER committed
665
		{
666 667
			// only show error if not explicitely cancelled
			if(!bCancelled)
Tobias WEBER's avatar
Tobias WEBER committed
668
				QMessageBox::critical(this, PROG_NAME, "Error loading file.");
Tobias WEBER's avatar
Tobias WEBER committed
669
			return;
Tobias WEBER's avatar
Tobias WEBER committed
670 671
		}

Tobias WEBER's avatar
Tobias WEBER committed
672 673

		m_mol.UnsubscribeFromLoadProgress(&progressHandler);
Tobias WEBER's avatar
Tobias WEBER committed
674
		m_slider->setMaximum(m_mol.GetFrameCount() - 1);
Tobias WEBER's avatar
Tobias WEBER committed
675

Tobias WEBER's avatar
Tobias WEBER committed
676

Tobias WEBER's avatar
Tobias WEBER committed
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
		// crystal A and B matrices
		const t_vec& _a = m_mol.GetBaseA();
		const t_vec& _b = m_mol.GetBaseB();
		const t_vec& _c = m_mol.GetBaseC();

		m_crystA = m::create<t_mat>({
			_a[0],	_b[0],	_c[0],
			_a[1],	_b[1],	_c[1],
			_a[2], 	_b[2],	_c[2] });

		bool ok = true;
		std::tie(m_crystB, ok) = m::inv(m_crystA);
		if(!ok)
		{
			m_crystB = m::unit<t_mat>();
Tobias WEBER's avatar
Tobias WEBER committed
692
			QMessageBox::critical(this, PROG_NAME, "Error: Cannot invert A matrix.");
Tobias WEBER's avatar
Tobias WEBER committed
693 694 695 696 697 698 699 700 701 702
		}

		m_crystB /= t_real_gl(2)*m::pi<t_real_gl>;
		t_mat_gl matA{m_crystA};
		m_plot->GetImpl()->SetBTrafo(m_crystB, &matA);

		std::cout << "A matrix: " << m_crystA << ", \n"
			<< "B matrix: " << m_crystB << "." << std::endl;


Tobias WEBER's avatar
Tobias WEBER committed
703
		// atom colors
Tobias WEBER's avatar
Tobias WEBER committed
704 705 706 707 708 709 710 711 712 713
		std::vector<t_vec> cols =
		{
			m::create<t_vec>({1, 0, 0}),
			m::create<t_vec>({0, 0, 1}),
			m::create<t_vec>({0, 0.5, 0}),
			m::create<t_vec>({0, 0.5, 0.5}),
			m::create<t_vec>({0.5, 0.5, 0}),
			m::create<t_vec>({0, 0, 0}),
		};

Tobias WEBER's avatar
Tobias WEBER committed
714
		// add atoms to 3d view
Tobias WEBER's avatar
Tobias WEBER committed
715 716 717
		if(m_mol.GetFrameCount())
		{
			const auto& frame = m_mol.GetFrame(0);
Tobias WEBER's avatar
Tobias WEBER committed
718
			m_sphereHandles.reserve(frame.GetNumAtomTypes());
Tobias WEBER's avatar
Tobias WEBER committed
719

Tobias WEBER's avatar
Tobias WEBER committed
720
			for(std::size_t atomidx=0; atomidx<frame.GetNumAtomTypes(); ++atomidx)
Tobias WEBER's avatar
Tobias WEBER committed
721 722 723
			{
				const auto& coords = frame.GetCoords(atomidx);
				for(const t_vec& vec : coords)
724
				{
Tobias WEBER's avatar
Tobias WEBER committed
725 726
					t_real atomscale = m_spinScale->value();
					std::size_t handle = Add3DItem(vec, cols[atomidx % cols.size()], atomscale, m_mol.GetAtomName(atomidx));
727 728
					m_sphereHandles.push_back(handle);
				}
Tobias WEBER's avatar
Tobias WEBER committed
729 730 731 732 733
			}
		}
	}
	catch(const std::exception& ex)
	{
Tobias WEBER's avatar
Tobias WEBER committed
734
		QMessageBox::critical(this, PROG_NAME, ex.what());
Tobias WEBER's avatar
Tobias WEBER committed
735 736
	}

Tobias WEBER's avatar
Tobias WEBER committed
737

Tobias WEBER's avatar
Tobias WEBER committed
738
	UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
739
	m_plot->update();
Tobias WEBER's avatar
Tobias WEBER committed
740 741 742
}


Tobias WEBER's avatar
Tobias WEBER committed
743
void MolDynDlg::SaveAs()
Tobias WEBER's avatar
Tobias WEBER committed
744
{
Tobias WEBER's avatar
Tobias WEBER committed
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
	try
	{
		QString dirLast = m_sett->value("dir", "").toString();
		QString filename = QFileDialog::getSaveFileName(this, "Save File", dirLast, "Molecular Dynamics File (*)");
		if(filename == "")
			return;
		m_sett->setValue("dir", QFileInfo(filename).path());


		std::shared_ptr<QProgressDialog> dlgProgress = std::make_shared<QProgressDialog>(
			"Saving \"" + QFileInfo(filename).fileName() + "\"...", "Cancel", 0, 1000, this);
		bool bCancelled = 0;
		auto progressHandler = [dlgProgress, &bCancelled](t_real percentage) -> bool
		{
			dlgProgress->setValue(int(percentage*10));
			bCancelled = dlgProgress->wasCanceled();
			return !bCancelled;
		};
		m_mol.SubscribeToSaveProgress(progressHandler);
		dlgProgress->setWindowModality(Qt::WindowModal);


		if(!m_mol.SaveFile(filename.toStdString()))
		{
Tobias WEBER's avatar
Tobias WEBER committed
769
			QMessageBox::critical(this, PROG_NAME, "Error saving file.");
Tobias WEBER's avatar
Tobias WEBER committed
770 771 772 773 774 775 776
		}


		m_mol.UnsubscribeFromSaveProgress(&progressHandler);
	}
	catch(const std::exception& ex)
	{
Tobias WEBER's avatar
Tobias WEBER committed
777
		QMessageBox::critical(this, PROG_NAME, ex.what());
Tobias WEBER's avatar
Tobias WEBER committed
778
	}
Tobias WEBER's avatar
Tobias WEBER committed
779 780 781 782 783 784 785 786 787 788 789
}
// ----------------------------------------------------------------------------



// ----------------------------------------------------------------------------
/**
 * mouse hovers over 3d object
 */
void MolDynDlg::PickerIntersection(const t_vec3_gl* pos, std::size_t objIdx, const t_vec3_gl* posSphere)
{
790 791
	if(!m_plot) return;

Tobias WEBER's avatar
Tobias WEBER committed
792 793 794 795 796 797 798 799
	if(pos)
		m_curPickedObj = long(objIdx);
	else
		m_curPickedObj = -1;


	if(m_curPickedObj > 0)
	{
800
		const std::string& label = m_plot->GetImpl()->GetObjectDataString(m_curPickedObj);
Tobias WEBER's avatar
Tobias WEBER committed
801 802
		m_statusCurAtom->setText(label.c_str());
		//SetStatusMsg(label);
Tobias WEBER's avatar
Tobias WEBER committed
803 804 805
	}
	else
	{
Tobias WEBER's avatar
Tobias WEBER committed
806 807
		m_statusCurAtom->setText("");
		//SetStatusMsg("");
Tobias WEBER's avatar
Tobias WEBER committed
808 809 810 811 812 813 814 815
	}
}



/**
 * set status label text in 3d dialog
 */
Tobias WEBER's avatar
Tobias WEBER committed
816
void MolDynDlg::SetStatusMsg(const std::string& msg)
Tobias WEBER's avatar
Tobias WEBER committed
817 818
{
	if(!m_status) return;
819
	m_status->showMessage(msg.c_str(), 2000);
Tobias WEBER's avatar
Tobias WEBER committed
820 821 822 823
}



Tobias WEBER's avatar
Tobias WEBER committed
824 825
void  MolDynDlg::UpdateAtomsStatusMsg()
{
Tobias WEBER's avatar
Tobias WEBER committed
826 827 828 829 830 831 832 833 834 835 836
	if(!m_statusAtoms || !m_slider) return;

	// Atoms
	std::string numAtoms = std::to_string(m_mol.GetNumAtomsTotal()) + " atoms.";

	// Selected
	if(m_plot)
	{
		std::size_t numSelected = 0;

		for(auto handle : m_sphereHandles)
837
        {
Tobias WEBER's avatar
Tobias WEBER committed
838 839
			if(m_plot->GetImpl()->GetObjectHighlight(handle))
				++numSelected;
840
        }
Tobias WEBER's avatar
Tobias WEBER committed
841 842 843 844 845 846

		numAtoms += " " + std::to_string(numSelected) + " selected.";
	}

	// Frames
	numAtoms += " Frame " + std::to_string(m_slider->value()+1) + " of " + std::to_string(m_mol.GetFrameCount()) + ".";
Tobias WEBER's avatar
Tobias WEBER committed
847 848 849 850 851 852

	m_statusAtoms->setText(numAtoms.c_str());
}



Tobias WEBER's avatar
Tobias WEBER committed
853 854 855 856 857
/**
 * mouse button pressed
 */
void MolDynDlg::PlotMouseDown(bool left, bool mid, bool right)
{
Tobias WEBER's avatar
Tobias WEBER committed
858 859
	if(!m_plot) return;

Tobias WEBER's avatar
Tobias WEBER committed
860 861
	if(left && m_curPickedObj > 0)
	{
Tobias WEBER's avatar
Tobias WEBER committed
862
		m_plot->GetImpl()->SetObjectHighlight(m_curPickedObj, !m_plot->GetImpl()->GetObjectHighlight(m_curPickedObj));
Tobias WEBER's avatar
Tobias WEBER committed
863
		UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
864
		m_plot->update();
Tobias WEBER's avatar
Tobias WEBER committed
865 866 867 868 869 870 871 872 873 874
	}
}


/**
 * mouse button released
 */
void MolDynDlg::PlotMouseUp(bool left, bool mid, bool right)
{
}
Tobias WEBER's avatar
Tobias WEBER committed
875 876 877 878 879 880 881 882 883 884 885 886


/**
 * mouse button clicked
 */
void MolDynDlg::PlotMouseClick(bool left, bool mid, bool right)
{
	// show context menu
	if(right && m_curPickedObj > 0)
	{
		QString atomLabel = m_plot->GetImpl()->GetObjectDataString(m_curPickedObj).c_str();
		m_atomContextMenu->actions()[0]->setText("Delete This \"" + atomLabel + "\" Atom");
887 888 889
		m_atomContextMenu->actions()[5]->setText("Delete All \"" + atomLabel + "\" Atoms");
		m_atomContextMenu->actions()[6]->setText("Delete All But \"" + atomLabel + "\" Atoms");
		m_atomContextMenu->actions()[8]->setText("Select All \"" + atomLabel + "\" Atoms");
Tobias WEBER's avatar
Tobias WEBER committed
890 891 892 893 894 895

		auto ptGlob = QCursor::pos();
		ptGlob.setY(ptGlob.y() + 8);
		m_atomContextMenu->popup(ptGlob);
	}
}
Tobias WEBER's avatar
Tobias WEBER committed
896 897


Tobias WEBER's avatar
Tobias WEBER committed
898 899 900
// ----------------------------------------------------------------------------


Tobias WEBER's avatar
Tobias WEBER committed
901 902 903 904 905 906 907 908 909 910
/**
 * select all atoms
 */
void MolDynDlg::SelectAll()
{
	if(!m_plot) return;

	for(auto handle : m_sphereHandles)
		m_plot->GetImpl()->SetObjectHighlight(handle, 1);

Tobias WEBER's avatar
Tobias WEBER committed
911
	UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
912 913 914 915
	m_plot->update();
}


Tobias WEBER's avatar
Tobias WEBER committed
916 917 918 919 920 921 922 923 924 925
/**
 * unselect all atoms
 */
void MolDynDlg::SelectNone()
{
	if(!m_plot) return;

	for(auto handle : m_sphereHandles)
		m_plot->GetImpl()->SetObjectHighlight(handle, 0);

Tobias WEBER's avatar
Tobias WEBER committed
926
	UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
927 928 929
	m_plot->update();
}

Tobias WEBER's avatar
Tobias WEBER committed
930

Tobias WEBER's avatar
Tobias WEBER committed
931 932
void MolDynDlg::SliderValueChanged(int val)
{
933 934 935 936 937 938 939 940
	if(!m_plot) return;

	if(val < 0 || val >= m_mol.GetFrameCount())
		return;


	// update atom position with selected frame
	const auto& frame = m_mol.GetFrame(val);
Tobias WEBER's avatar
Tobias WEBER committed
941
	t_real atomscale = m_spinScale->value();
942 943

	std::size_t counter = 0;
Tobias WEBER's avatar
Tobias WEBER committed
944
	for(std::size_t atomidx=0; atomidx<frame.GetNumAtomTypes(); ++atomidx)
945 946 947 948 949
	{
		const auto& coords = frame.GetCoords(atomidx);
		for(const t_vec& vec : coords)
		{
			std::size_t obj = m_sphereHandles[counter];
Tobias WEBER's avatar
Tobias WEBER committed
950
			Change3DItem(obj, &vec, nullptr, &atomscale);
951 952 953 954 955

			++counter;
		}
	}

Tobias WEBER's avatar
Tobias WEBER committed
956
	UpdateAtomsStatusMsg();
957
	m_plot->update();
Tobias WEBER's avatar
Tobias WEBER committed
958 959 960
}


Tobias WEBER's avatar
Tobias WEBER committed
961 962 963
// ----------------------------------------------------------------------------


Tobias WEBER's avatar
Tobias WEBER committed
964
/**
Tobias WEBER's avatar
Tobias WEBER committed
965 966
 * get the index of the atom in the m_mol data structure
 * from the handle of the displayed 3d object
Tobias WEBER's avatar
Tobias WEBER committed
967
 */
Tobias WEBER's avatar
Tobias WEBER committed
968 969
std::tuple<bool, std::size_t, std::size_t, std::size_t> 
MolDynDlg::GetAtomIndexFromHandle(std::size_t handle) const
Tobias WEBER's avatar
Tobias WEBER committed
970
{
Tobias WEBER's avatar
Tobias WEBER committed
971
	// find handle in sphere handle vector
Tobias WEBER's avatar
Tobias WEBER committed
972
	auto iter = std::find(m_sphereHandles.begin(), m_sphereHandles.end(), handle);
Tobias WEBER's avatar
Tobias WEBER committed
973
	if(iter == m_sphereHandles.end())
Tobias WEBER's avatar
Tobias WEBER committed
974
		return std::make_tuple(0, 0, 0, 0);
Tobias WEBER's avatar
Tobias WEBER committed
975 976

	std::size_t sphereIdx = iter - m_sphereHandles.begin();
Tobias WEBER's avatar
Tobias WEBER committed
977

Tobias WEBER's avatar
Tobias WEBER committed
978 979
	std::size_t atomCountsSoFar = 0;
	std::size_t atomTypeIdx = 0;
Tobias WEBER's avatar
Tobias WEBER committed
980
	for(atomTypeIdx=0; atomTypeIdx<m_mol.GetNumAtomTypes(); ++atomTypeIdx)
Tobias WEBER's avatar
Tobias WEBER committed
981 982 983 984 985 986 987 988
	{
		std::size_t numAtoms = m_mol.GetAtomNum(atomTypeIdx);
		if(atomCountsSoFar + numAtoms > sphereIdx)
			break;

		atomCountsSoFar += numAtoms;
	}

Tobias WEBER's avatar
Tobias WEBER committed
989 990 991 992 993 994
	std::size_t atomSubTypeIdx = sphereIdx-atomCountsSoFar;

	return std::make_tuple(1, atomTypeIdx, atomSubTypeIdx, sphereIdx);
}


Tobias WEBER's avatar
Tobias WEBER committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
/**
 * select all atoms of the same type as the one under the cursor
 */
void MolDynDlg::SelectAtomsOfSameType()
{
	// nothing under cursor
	if(m_curPickedObj <= 0)
		return;

	// atom type to be selected
	const std::string& atomLabel = m_plot->GetImpl()->GetObjectDataString(m_curPickedObj);

	for(auto handle : m_sphereHandles)
1008
    {
Tobias WEBER's avatar
Tobias WEBER committed
1009 1010
		if(m_plot->GetImpl()->GetObjectDataString(handle) == atomLabel)
			m_plot->GetImpl()->SetObjectHighlight(handle, 1);
1011
    }
Tobias WEBER's avatar
Tobias WEBER committed
1012

Tobias WEBER's avatar
Tobias WEBER committed
1013
	UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
1014 1015 1016 1017
	m_plot->update();
}


1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
/**
 * delete the selected atoms
 */
void MolDynDlg::DeleteSelectedAtoms()
{
    std::size_t totalRemoved = 0;

    for(auto iter=m_sphereHandles.begin(); iter!=m_sphereHandles.end();)
    {
        auto handle = *iter;
        if(m_plot->GetImpl()->GetObjectHighlight(handle))
        {
            const auto [bOk, atomTypeIdx, atomSubTypeIdx, sphereIdx] = GetAtomIndexFromHandle(handle);
            if(!bOk)
            {
                QMessageBox::critical(this, PROG_NAME, "Atom handle not found, data is corrupted.");
                return;
            }

            // remove 3d objects
            m_plot->GetImpl()->RemoveObject(handle);
            iter = m_sphereHandles.erase(iter);

            // remove atom
            m_mol.RemoveAtom(atomTypeIdx, atomSubTypeIdx);
            
            ++totalRemoved;
            continue;
        }

        ++iter;
    }

    SetStatusMsg(std::to_string(totalRemoved) + " atoms removed.");
	UpdateAtomsStatusMsg();
	m_plot->update();
}


/**
 * delete all but the selected atoms
 */
void MolDynDlg::OnlyKeepSelectedAtoms()
{
    std::size_t totalRemoved = 0;

    for(auto iter=m_sphereHandles.begin(); iter!=m_sphereHandles.end();)
    {
        auto handle = *iter;
        if(!m_plot->GetImpl()->GetObjectHighlight(handle))
        {
            const auto [bOk, atomTypeIdx, atomSubTypeIdx, sphereIdx] = GetAtomIndexFromHandle(handle);
            if(!bOk)
            {
                QMessageBox::critical(this, PROG_NAME, "Atom handle not found, data is corrupted.");
                return;
            }

            // remove 3d objects
            m_plot->GetImpl()->RemoveObject(handle);
            iter = m_sphereHandles.erase(iter);

            // remove atom
            m_mol.RemoveAtom(atomTypeIdx, atomSubTypeIdx);
            
            ++totalRemoved;
            continue;
        }

        ++iter;
    }

    SetStatusMsg(std::to_string(totalRemoved) + " atoms removed.");
	UpdateAtomsStatusMsg();
	m_plot->update();
}


Tobias WEBER's avatar
Tobias WEBER committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
/**
 * delete one atom
 */
void MolDynDlg::DeleteAtomUnderCursor()
{
	// nothing under cursor
	if(m_curPickedObj <= 0)
		return;

	// atom type to be deleted
	const std::string& atomLabel = m_plot->GetImpl()->GetObjectDataString(m_curPickedObj);

	const auto [bOk, atomTypeIdx, atomSubTypeIdx, sphereIdx] = GetAtomIndexFromHandle(m_curPickedObj);
	if(!bOk)
	{
Tobias WEBER's avatar
Tobias WEBER committed
1111
		QMessageBox::critical(this, PROG_NAME, "Atom handle not found, data is corrupted.");
Tobias WEBER's avatar
Tobias WEBER committed
1112 1113 1114
		return;
	}

Tobias WEBER's avatar
Tobias WEBER committed
1115 1116
	if(m_mol.GetAtomName(atomTypeIdx) != atomLabel)
	{
Tobias WEBER's avatar
Tobias WEBER committed
1117
		QMessageBox::critical(this, PROG_NAME, "Mismatch in atom type, data is corrupted.");
Tobias WEBER's avatar
Tobias WEBER committed
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
		return;
	}

	// remove 3d objects
	m_plot->GetImpl()->RemoveObject(m_sphereHandles[sphereIdx]);
	m_sphereHandles.erase(m_sphereHandles.begin()+sphereIdx);

	// remove atom
	m_mol.RemoveAtom(atomTypeIdx, atomSubTypeIdx);

	SetStatusMsg("1 atom removed.");
Tobias WEBER's avatar
Tobias WEBER committed
1129
	UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
1130
	m_plot->update();
Tobias WEBER's avatar
Tobias WEBER committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
}


/**
 * delete all atoms of the type under the cursor
 */
void MolDynDlg::DeleteAllAtomsOfSameType()
{
	// nothing under cursor
	if(m_curPickedObj <= 0)
		return;

	// atom type to be deleted
	const std::string& atomLabel = m_plot->GetImpl()->GetObjectDataString(m_curPickedObj);

	std::size_t startIdx = 0;
	std::size_t totalRemoved = 0;
Tobias WEBER's avatar
Tobias WEBER committed
1148
	for(std::size_t atomIdx=0; atomIdx<m_mol.GetNumAtomTypes();)
Tobias WEBER's avatar
Tobias WEBER committed
1149 1150 1151 1152 1153 1154 1155
	{
		std::size_t numAtoms = m_mol.GetAtomNum(atomIdx);

		if(m_mol.GetAtomName(atomIdx) == atomLabel)
		{
			// remove 3d objects
			for(std::size_t sphereIdx=startIdx; sphereIdx<startIdx+numAtoms; ++sphereIdx)
Tobias WEBER's avatar
Tobias WEBER committed
1156
				m_plot->GetImpl()->RemoveObject(m_sphereHandles[sphereIdx]);
Tobias WEBER's avatar
Tobias WEBER committed
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
			m_sphereHandles.erase(m_sphereHandles.begin()+startIdx, m_sphereHandles.begin()+startIdx+numAtoms);

			// remove atoms
			m_mol.RemoveAtoms(atomIdx);

			totalRemoved += numAtoms;
		}
		else
		{
			startIdx += numAtoms;
			++atomIdx;
		}
	}

	SetStatusMsg(std::to_string(totalRemoved) + " atoms removed.");
Tobias WEBER's avatar
Tobias WEBER committed
1172
	UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
	m_plot->update();
}


/**
 * delete all atoms NOT of the type under the cursor
 */
void MolDynDlg::KeepAtomsOfSameType()
{
	// nothing under cursor
	if(m_curPickedObj <= 0)
		return;

	// atom type to be deleted
	const std::string& atomLabel = m_plot->GetImpl()->GetObjectDataString(m_curPickedObj);

	std::size_t startIdx = 0;
	std::size_t totalRemoved = 0;
Tobias WEBER's avatar
Tobias WEBER committed
1191
	for(std::size_t atomIdx=0; atomIdx<m_mol.GetNumAtomTypes();)
Tobias WEBER's avatar
Tobias WEBER committed
1192 1193 1194 1195 1196 1197 1198
	{
		std::size_t numAtoms = m_mol.GetAtomNum(atomIdx);

		if(m_mol.GetAtomName(atomIdx) != atomLabel)
		{
			// remove 3d objects
			for(std::size_t sphereIdx=startIdx; sphereIdx<startIdx+numAtoms; ++sphereIdx)
Tobias WEBER's avatar
Tobias WEBER committed
1199
				m_plot->GetImpl()->RemoveObject(m_sphereHandles[sphereIdx]);
Tobias WEBER's avatar
Tobias WEBER committed
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
			m_sphereHandles.erase(m_sphereHandles.begin()+startIdx, m_sphereHandles.begin()+startIdx+numAtoms);

			// remove atoms
			m_mol.RemoveAtoms(atomIdx);

			totalRemoved += numAtoms;
		}
		else
		{
			startIdx += numAtoms;
			++atomIdx;
		}
	}

	SetStatusMsg(std::to_string(totalRemoved) + " atoms removed.");
Tobias WEBER's avatar
Tobias WEBER committed
1215
	UpdateAtomsStatusMsg();
Tobias WEBER's avatar
Tobias WEBER committed
1216 1217 1218 1219 1220
	m_plot->update();
}



Tobias WEBER's avatar
Tobias WEBER committed
1221 1222 1223 1224 1225 1226 1227 1228 1229
// ----------------------------------------------------------------------------
void MolDynDlg::AfterGLInitialisation()
{
	if(!m_plot) return;

	// reference sphere for linked objects
	m_sphere = m_plot->GetImpl()->AddSphere(0.05, 0.,0.,0., 1.,1.,1.,1.);
	m_plot->GetImpl()->SetObjectVisible(m_sphere, false);

Tobias WEBER's avatar
Tobias WEBER committed
1230 1231 1232
	// B matrix
	m_plot->GetImpl()->SetBTrafo(m_crystB);

Tobias WEBER's avatar
Tobias WEBER committed
1233 1234 1235 1236 1237 1238 1239 1240
	// GL device info
	auto [strGlVer, strGlShaderVer, strGlVendor, strGlRenderer]
		= m_plot->GetImpl()->GetGlDescr();
	std::cout << "GL Version: " << strGlVer << ", Shader Version: " << strGlShaderVer << "." << std::endl;
	std::cout << "GL Device: " << strGlRenderer << ", " << strGlVendor << "." << std::endl;
}


Tobias WEBER's avatar
Tobias WEBER committed
1241 1242 1243 1244 1245 1246 1247 1248 1249
void MolDynDlg::GLInitialisationFailed()
{
	std::string err = "GL initialisation failed.";
	err += " Need GL version " + std::to_string(_GL_MAJ_VER) + "." + std::to_string(_GL_MIN_VER);
	err += " and shader version " + std::to_string(_GLSL_MAJ_VER) + std::to_string(_GLSL_MIN_VER) + "0.";
	QMessageBox::critical(this, PROG_NAME, err.c_str());
}


Tobias WEBER's avatar
Tobias WEBER committed
1250 1251 1252 1253 1254 1255 1256
void MolDynDlg::closeEvent(QCloseEvent *evt)
{
	if(m_sett)
	{
		m_sett->setValue("geo", saveGeometry());
	}
}
Tobias WEBER's avatar
Tobias WEBER committed
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275


void MolDynDlg::keyPressEvent(QKeyEvent *evt)
{
	if(evt->key()==Qt::Key_Left || evt->key()==Qt::Key_Down)
		m_slider->setValue(m_slider->value() - m_slider->singleStep());
	else if(evt->key()==Qt::Key_Right || evt->key()==Qt::Key_Up)
		m_slider->setValue(m_slider->value() + m_slider->singleStep());
	else if(evt->key()==Qt::Key_PageUp)
		m_slider->setValue(m_slider->value() + m_slider->pageStep());
	else if(evt->key()==Qt::Key_PageDown)
		m_slider->setValue(m_slider->value() - m_slider->pageStep());
	else if(evt->key()==Qt::Key_Home)
		m_slider->setValue(m_slider->minimum());
	else if(evt->key()==Qt::Key_End)
		m_slider->setValue(m_slider->maximum());

	QMainWindow::keyPressEvent(evt);
}
Tobias WEBER's avatar
Tobias WEBER committed
1276 1277 1278 1279 1280 1281 1282
// ----------------------------------------------------------------------------





// ----------------------------------------------------------------------------
1283 1284 1285

int main(int argc, char** argv)
{
Tobias WEBER's avatar
Tobias WEBER committed
1286
	set_gl_format(1, _GL_MAJ_VER, _GL_MIN_VER, 0);
Tobias WEBER's avatar
Tobias WEBER committed
1287
	tl2::set_locales();
1288

Tobias WEBER's avatar
Tobias WEBER committed
1289
	QApplication::addLibraryPath(QString(".") + QDir::separator() + "qtplugins");
Tobias WEBER's avatar
Tobias WEBER committed
1290
	auto app = std::make_unique<QApplication>(argc, argv);
Tobias WEBER's avatar
Tobias WEBER committed
1291
	QApplication::addLibraryPath(QApplication::applicationDirPath() + QDir::separator() + "qtplugins");
Tobias WEBER's avatar
Tobias WEBER committed
1292

Tobias WEBER's avatar
Tobias WEBER committed
1293 1294
	auto dlg = std::make_unique<MolDynDlg>(nullptr);
	dlg->show();
1295