diff --git a/Base/CheckboxDelegate.cpp b/Base/CheckboxDelegate.cpp index ae3c7c84dfdab17dff87b9a9bcf4b16957e75215..c0224f1006fc00905bd9623ab37cb76cd70706a5 100644 --- a/Base/CheckboxDelegate.cpp +++ b/Base/CheckboxDelegate.cpp @@ -1,28 +1,28 @@ /** * \file CheckboxDelegate.cpp * 19/08/2010 LB Initial implementation - * + * * Implementation of CheckboxDelegate class */ // ** INCLUDES ** #include "CheckboxDelegate.h" +#include <QApplication> #include <QCheckBox> -#include <QPainter> #include <QEvent> -#include <QApplication> -#include <QStyleOptionButton> #include <QMouseEvent> +#include <QPainter> +#include <QStyleOptionButton> #include <iostream> CheckboxDelegate::CheckboxDelegate(QObject* parent) -: QItemDelegate(parent) + : QItemDelegate(parent) { } void CheckboxDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, - const QModelIndex& index) const + const QModelIndex& index) const { if(index.isValid()) { @@ -38,32 +38,32 @@ void CheckboxDelegate::paint(QPainter* painter, const QStyleOptionViewItem& opti styleOptionButton.rect = this->checkboxRect(option); QApplication::style()->drawControl(QStyle::CE_CheckBox, - &styleOptionButton, painter); + &styleOptionButton, painter); } else QItemDelegate::paint(painter, option, index); } -bool CheckboxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, - const QStyleOptionViewItem &option, const QModelIndex &index) +bool CheckboxDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, + const QStyleOptionViewItem &option, const QModelIndex &index) { Q_UNUSED(option); if ((event->type() == QEvent::MouseButtonRelease) || - (event->type() == QEvent::MouseButtonDblClick)) + (event->type() == QEvent::MouseButtonDblClick)) { - QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event); + QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event); if (mouse_event->button() != Qt::LeftButton || - !checkboxRect(option).contains(mouse_event->pos())) - return false; + !checkboxRect(option).contains(mouse_event->pos())) + return false; if (event->type() == QEvent::MouseButtonDblClick) - return true; + return true; } else if (event->type() == QEvent::KeyPress) { if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space && - static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select) - return false; + static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select) + return false; } else return false; @@ -72,7 +72,8 @@ bool CheckboxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, return model->setData(index, !checked, Qt::EditRole); } -QSize CheckboxDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const +QSize CheckboxDelegate::sizeHint(const QStyleOptionViewItem & option, + const QModelIndex & index) const { Q_UNUSED(index); @@ -84,10 +85,10 @@ QRect CheckboxDelegate::checkboxRect(const QStyleOptionViewItem& viewItemStyleOp { QStyleOptionButton styleOptionButton; QRect rect = QApplication::style()->subElementRect( - QStyle::SE_CheckBoxIndicator, &styleOptionButton); + QStyle::SE_CheckBoxIndicator, &styleOptionButton); QPoint point(viewItemStyleOptions.rect.x() + - viewItemStyleOptions.rect.width() / 2 - rect.width() / 2, - viewItemStyleOptions.rect.y() + viewItemStyleOptions.rect.height() / 2 - - rect.height() / 2); + viewItemStyleOptions.rect.width() / 2 - rect.width() / 2, + viewItemStyleOptions.rect.y() + viewItemStyleOptions.rect.height() / 2 - + rect.height() / 2); return QRect(point, rect.size()); } diff --git a/Base/CheckboxDelegate.h b/Base/CheckboxDelegate.h index 200c7a721eede907b6c67191aba1e875e91d17ad..67a4fbef36495060b16741a516d9627a86d4d7ba 100644 --- a/Base/CheckboxDelegate.h +++ b/Base/CheckboxDelegate.h @@ -3,8 +3,8 @@ * 19/08/2010 LB Initial implementation */ -#ifndef CHECKBOXDELEGATE_H -#define CHECKBOXDELEGATE_H +#ifndef CHECKBOXDELEGATE_H +#define CHECKBOXDELEGATE_H #include <QItemDelegate> @@ -14,24 +14,24 @@ class QRect; /** * \brief CheckboxDelegate modifies a model view to display boolean values as checkboxes. * - * Important: the column on which this delegate is set (QAbstractItemView::setItemDelegateForColumn()) + * Important: the column on which this delegate is set (QAbstractItemView::setItemDelegateForColumn()) * must not have the flags Qt::ItemIsEditable or Qt::ItemIsUserCheckable set in the model. **/ class CheckboxDelegate : public QItemDelegate { Q_OBJECT - + public: /// \brief Constructor CheckboxDelegate (QObject* parent = 0); /// \brief Paints a checkbox. This overrides the default painting of a combo box. void paint(QPainter* painter, const QStyleOptionViewItem& option, - const QModelIndex& index) const; + const QModelIndex& index) const; /// \brief Handles the click events and sets the model data. - bool editorEvent(QEvent *event, QAbstractItemModel *model, - const QStyleOptionViewItem &option, const QModelIndex &index); + bool editorEvent(QEvent* event, QAbstractItemModel* model, + const QStyleOptionViewItem &option, const QModelIndex &index); QSize sizeHint (const QStyleOptionViewItem & option, const QModelIndex & index) const; diff --git a/Base/ColorPickerPushButton.cpp b/Base/ColorPickerPushButton.cpp index 6d1d986e94a1d60a816a054f0bf0e16be999b0b3..802d4beea81bacf4b40587c7b9d2c17e078f21f2 100644 --- a/Base/ColorPickerPushButton.cpp +++ b/Base/ColorPickerPushButton.cpp @@ -1,17 +1,17 @@ /** * \file ColorPickerPushButton.cpp * 17/5/2010 LB Initial implementation - * + * * Implementation of ColorPickerPushButton */ // ** INCLUDES ** #include "ColorPickerPushButton.h" - #include <QColorDialog> +#include <QColorDialog> ColorPickerPushButton::ColorPickerPushButton( QWidget* parent /*= 0*/ ) -: QPushButton(parent) + : QPushButton(parent) { setAutoFillBackground(true); _color = QColor("white"); @@ -23,7 +23,7 @@ void ColorPickerPushButton::mouseReleaseEvent(QMouseEvent* e) QColor newColor = QColorDialog::getColor(_color, NULL, "Choose a color"); if (!newColor.isValid()) return; - + setColor(newColor); emit colorPicked(_color); diff --git a/Base/ColorPickerPushButton.h b/Base/ColorPickerPushButton.h index bbbb43fa0c8651bb6f31b6b1ae5a75d74794b8f1..5703d44e023bd82e66682923d49af1449b9c501f 100644 --- a/Base/ColorPickerPushButton.h +++ b/Base/ColorPickerPushButton.h @@ -4,7 +4,6 @@ * */ - #ifndef COLORPICKERPUSHBUTTON_H #define COLORPICKERPUSHBUTTON_H diff --git a/Base/OGSError.h b/Base/OGSError.h index 5b5b4edb8efeb832ce05ac60eb691e11cafbc597..fd6ce0839cc904784298fc27c49ea3825e055e32 100644 --- a/Base/OGSError.h +++ b/Base/OGSError.h @@ -13,7 +13,6 @@ class QString; */ class OGSError { - public: static void box(QString e); static void box(QString e, QString t); @@ -21,7 +20,6 @@ public: protected: OGSError(); ~OGSError(); - }; #endif //OGSERROR_H diff --git a/Base/QNonScalableGraphicsTextItem.cpp b/Base/QNonScalableGraphicsTextItem.cpp index 546d2423ecf52d14f6d153269d24863826153405..0901e7cdcd75d499f1894a8dbb4878f8744f35f1 100644 --- a/Base/QNonScalableGraphicsTextItem.cpp +++ b/Base/QNonScalableGraphicsTextItem.cpp @@ -3,25 +3,27 @@ * KR Initial implementation */ -#include <QPainter> #include "QNonScalableGraphicsTextItem.h" +#include <QPainter> /// Constructor using a QGraphicsTextItem. -QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem(QGraphicsItem* parent) : QGraphicsTextItem(parent) +QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem(QGraphicsItem* parent) : + QGraphicsTextItem(parent) { setAcceptDrops(true); - setAcceptHoverEvents(true); + setAcceptHoverEvents(true); setFlag(QGraphicsItem::ItemIgnoresTransformations, true); } /// Constructor using a QString. -QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem(const QString & text, QGraphicsItem * parent) : +QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem(const QString & text, + QGraphicsItem* parent) : QGraphicsTextItem(parent) { if (!text.isEmpty()) - setPlainText(text); - setAcceptDrops(true); - setAcceptHoverEvents(true); + setPlainText(text); + setAcceptDrops(true); + setAcceptHoverEvents(true); setFlag(QGraphicsItem::ItemIgnoresTransformations, true); } @@ -30,11 +32,13 @@ QNonScalableGraphicsTextItem::~QNonScalableGraphicsTextItem() } /// Paints the text item. -void QNonScalableGraphicsTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void QNonScalableGraphicsTextItem::paint(QPainter* painter, + const QStyleOptionGraphicsItem* option, + QWidget* widget) { //painter->drawRect(boundingRect()); QRectF rect = boundingRect(); - painter->translate(-rect.width()/2, -rect.height()/2); + painter->translate(-rect.width() / 2, -rect.height() / 2); QGraphicsTextItem::paint(painter, option, widget); } @@ -42,5 +46,5 @@ void QNonScalableGraphicsTextItem::paint(QPainter *painter, const QStyleOptionGr QRectF QNonScalableGraphicsTextItem::boundingRect() const { QRectF rect = QGraphicsTextItem::boundingRect(); - return rect;//QRectF(rect.x()-rect.width()/2, rect.y()-rect.height()/2,rect.width(), rect.height()); + return rect; //QRectF(rect.x()-rect.width()/2, rect.y()-rect.height()/2,rect.width(), rect.height()); } diff --git a/Base/QNonScalableGraphicsTextItem.h b/Base/QNonScalableGraphicsTextItem.h index 607681952c3efe2224273ffb2d95253a70a31d08..1b3dc2679519ce6beb8b7f99a29f4187dbd758b5 100644 --- a/Base/QNonScalableGraphicsTextItem.h +++ b/Base/QNonScalableGraphicsTextItem.h @@ -9,7 +9,7 @@ #include <QGraphicsTextItem> /** - * \brief A QGraphicsTextItem that will ignore all geometric transformations. + * \brief A QGraphicsTextItem that will ignore all geometric transformations. * * A QGraphicsTextItem that will ignore all geometric transformations to the underlying QGraphicsView/QGraphicsScene (in particular, it will not be scaled). */ @@ -17,10 +17,10 @@ class QNonScalableGraphicsTextItem : public QGraphicsTextItem { public: QNonScalableGraphicsTextItem(QGraphicsItem* parent = 0); - QNonScalableGraphicsTextItem(const QString &text, QGraphicsItem * parent = 0); + QNonScalableGraphicsTextItem(const QString &text, QGraphicsItem* parent = 0); ~QNonScalableGraphicsTextItem(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); virtual QRectF boundingRect() const; }; diff --git a/Base/QValueTooltipSlider.cpp b/Base/QValueTooltipSlider.cpp index 2e6294a8bcdd4a5983aeadd256525cd27f9c7bf0..f66584a0573f7ffcf935b86eb3876e0f249781ec 100644 --- a/Base/QValueTooltipSlider.cpp +++ b/Base/QValueTooltipSlider.cpp @@ -1,20 +1,20 @@ /** * \file QValueTooltipSlider.cpp * 23/03/2011 LB Initial implementation - * + * * Implementation of QValueSlider class */ // ** INCLUDES ** #include "QValueTooltipSlider.h" +#include <QCursor> #include <QString> #include <QToolTip> -#include <QCursor> #include <iostream> -QValueTooltipSlider::QValueTooltipSlider(QWidget *parent) +QValueTooltipSlider::QValueTooltipSlider(QWidget* parent) : QSlider(parent) { connect(this, SIGNAL(sliderMoved(int)), this, SLOT(setTooltipValue(int))); diff --git a/Base/QValueTooltipSlider.h b/Base/QValueTooltipSlider.h index 20c8bed456b4f393ff6dd83218739f53995b8829..3facee9475cba66a54efd7339e35fd8b88b052e0 100644 --- a/Base/QValueTooltipSlider.h +++ b/Base/QValueTooltipSlider.h @@ -11,7 +11,7 @@ class QValueTooltipSlider : public QSlider { Q_OBJECT - + public: QValueTooltipSlider(QWidget* parent = 0); @@ -19,7 +19,6 @@ public slots: void setTooltipValue(int value); protected: - }; #endif // QVALUETOOLTIPSLIDER_H diff --git a/Base/RecentFiles.cpp b/Base/RecentFiles.cpp index 9c2613fa29b6d8fd1fbd9499ee38946d2f4ab8d1..520b8ad230d49bca3ea92c2d56aff9b777aac70a 100644 --- a/Base/RecentFiles.cpp +++ b/Base/RecentFiles.cpp @@ -1,19 +1,19 @@ /** * \file RecentFiles.cpp * 5/11/2009 LB Initial implementation - * + * * Implementation of RecentFiles */ // ** INCLUDES ** #include "RecentFiles.h" -#include <QSettings> #include <QFileInfo> +#include <QSettings> RecentFiles::RecentFiles( QObject* parent, const char* slot, - QString settingsName, QString programName ) -: QObject(parent), _settingsName(settingsName), _programName(programName) + QString settingsName, QString programName ) + : QObject(parent), _settingsName(settingsName), _programName(programName) { _filesMenu = new QMenu(tr("Recent files")); for (int i = 0; i < _maxFiles; i++) @@ -38,7 +38,7 @@ QMenu* RecentFiles::menu() void RecentFiles::setCurrentFile( const QString& filename ) { _currentFile = filename; - + QSettings settings("UFZ", _programName); QStringList files = settings.value(_settingsName).toStringList(); files.removeAll(filename); @@ -64,7 +64,7 @@ void RecentFiles::updateRecentFileActions() _fileActions[i]->setData(files[i]); _fileActions[i]->setVisible(true); } - + for (int i = numFiles; i < _maxFiles; ++i) _fileActions[i]->setVisible(false); } diff --git a/Base/RecentFiles.h b/Base/RecentFiles.h index 837e0f8691fca86149c84b3986ee028fabd1cfb2..01281edbaa9d344baaa0d7fdfa66fa63f0771326 100644 --- a/Base/RecentFiles.h +++ b/Base/RecentFiles.h @@ -4,14 +4,13 @@ * */ - #ifndef RECENTFILES_H #define RECENTFILES_H // ** INCLUDES ** -#include <QObject> -#include <QMenu> #include <QAction> +#include <QMenu> +#include <QObject> class QString; @@ -68,7 +67,6 @@ private: QString _programName; enum { _maxFiles = 5 }; QAction* _fileActions[_maxFiles]; - }; #endif // RECENTFILES_H diff --git a/Base/StrictDoubleValidator.h b/Base/StrictDoubleValidator.h index 049d33c81b813371a83e0b13bdebb9d0c9e5e237..1b845ff813c34fd44499df759b59657be5c4b24d 100644 --- a/Base/StrictDoubleValidator.h +++ b/Base/StrictDoubleValidator.h @@ -13,7 +13,8 @@ #include <QDoubleValidator> -class StrictDoubleValidator : public QDoubleValidator { +class StrictDoubleValidator : public QDoubleValidator +{ public: StrictDoubleValidator ( double min, double max, size_t decimals, QObject* parent = 0) : QDoubleValidator( min, max, decimals, parent) @@ -23,9 +24,8 @@ public: { if (input.isEmpty() || input == ".") return Intermediate; - if (QDoubleValidator::validate(input, pos) != Acceptable) { + if (QDoubleValidator::validate(input, pos) != Acceptable) return Invalid; - } return Acceptable; } }; diff --git a/Base/StrictIntValidator.h b/Base/StrictIntValidator.h index 81b922f7959527066db520fc3256283b3b1c8a35..ad7533b1aded04ffe7b19bbf656c358d2dbe75cf 100644 --- a/Base/StrictIntValidator.h +++ b/Base/StrictIntValidator.h @@ -13,7 +13,8 @@ #include <QIntValidator> -class StrictIntValidator : public QIntValidator { +class StrictIntValidator : public QIntValidator +{ public: StrictIntValidator ( int min, int max, QObject* parent = 0) : QIntValidator( min, max, parent) @@ -23,9 +24,8 @@ public: { if (input.isEmpty()) return Intermediate; - if (QIntValidator::validate(input, pos) != Acceptable) { + if (QIntValidator::validate(input, pos) != Acceptable) return Invalid; - } return Acceptable; } }; diff --git a/Base/TreeItem.cpp b/Base/TreeItem.cpp index 732b10e5a43a7213249b803b4e055d82e278c5ce..bbb4147690f34c82b6356d3797ee75222d91e3fb 100644 --- a/Base/TreeItem.cpp +++ b/Base/TreeItem.cpp @@ -6,19 +6,19 @@ #include "TreeItem.h" /** - * The constructor is only used to record the item's parent + * The constructor is only used to record the item's parent * and the data associated with each column. */ -TreeItem::TreeItem(const QList<QVariant> &data, TreeItem *parent) +TreeItem::TreeItem(const QList<QVariant> &data, TreeItem* parent) { _parentItem = parent; _itemData = data; } /** - * A pointer to each of the child items belonging to this item - * will be stored in the _childItems private member variable. When - * the class's destructor is called, it must delete each of these + * A pointer to each of the child items belonging to this item + * will be stored in the _childItems private member variable. When + * the class's destructor is called, it must delete each of these * to ensure that their memory is reused. */ TreeItem::~TreeItem() @@ -26,21 +26,20 @@ TreeItem::~TreeItem() qDeleteAll(_childItems); } - /** * Add a child to the tree item - */ -void TreeItem::appendChild(TreeItem *item) + */ +void TreeItem::appendChild(TreeItem* item) { _childItems.append(item); } /** - * Returns the child that corresponds to the specified row number + * Returns the child that corresponds to the specified row number * in the item's list of child items * Returns NULL if that child does not exist. */ -TreeItem *TreeItem::child(int row) const +TreeItem* TreeItem::child(int row) const { if (_childItems.count() > row) return _childItems.value(row); @@ -75,7 +74,6 @@ int TreeItem::columnCount() const return _itemData.count(); } - /** * Returns the data from all the columns. */ @@ -98,7 +96,7 @@ bool TreeItem::setData( int column, const QVariant &value ) /** * Returns the parent object of the tree item. */ -TreeItem *TreeItem::parentItem() const +TreeItem* TreeItem::parentItem() const { return _parentItem; } @@ -108,11 +106,11 @@ TreeItem *TreeItem::parentItem() const */ bool TreeItem::removeChildren(int position, int count) { - if (position < 0 || position + count > _childItems.size()) - return false; + if (position < 0 || position + count > _childItems.size()) + return false; for (int row = 0; row < count; ++row) - delete _childItems.takeAt(position); + delete _childItems.takeAt(position); - return true; + return true; } diff --git a/Base/TreeItem.h b/Base/TreeItem.h index ffaaf65a2d0ee86afe61468e72e9aab22737294d..4fd9d18e72bc4273d3bd588769fc1e8fbceac775 100644 --- a/Base/TreeItem.h +++ b/Base/TreeItem.h @@ -12,17 +12,17 @@ /** * \brief Objects nodes for the TreeModel. * - * The TreeItem class provides simple items that contain several pieces of data, + * The TreeItem class provides simple items that contain several pieces of data, * and which can provide information about their parent and child items * \sa TreeModel */ class TreeItem { public: - TreeItem(const QList<QVariant> &data, TreeItem *parent); + TreeItem(const QList<QVariant> &data, TreeItem* parent); virtual ~TreeItem(); - void appendChild(TreeItem *child); + void appendChild(TreeItem* child); TreeItem* child(int row) const; virtual int childCount() const; virtual int columnCount() const; @@ -35,8 +35,7 @@ public: private: QList<TreeItem*> _childItems; QList<QVariant> _itemData; - TreeItem* _parentItem; - + TreeItem* _parentItem; }; #endif //QTREEITEM_H diff --git a/Base/TreeModel.cpp b/Base/TreeModel.cpp index 42fe56abedbc0f0bfc67b44dc98135818e01cc0d..3f25f944c3e70051df5161241e083483d3b078cc 100644 --- a/Base/TreeModel.cpp +++ b/Base/TreeModel.cpp @@ -7,17 +7,15 @@ #include "TreeItem.h" +#include <QModelIndex> #include <QStringList> #include <QVariant> -#include <QModelIndex> - - /** * A model for the QTreeView implementing the tree as a double-linked list. */ -TreeModel::TreeModel( QObject *parent ) -: QAbstractItemModel(parent) +TreeModel::TreeModel( QObject* parent ) + : QAbstractItemModel(parent) { //_modelType = TREE_MODEL; QList<QVariant> rootData; @@ -46,19 +44,19 @@ QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) con if (!hasIndex(row, column, parent)) return QModelIndex(); - TreeItem *parentItem; + TreeItem* parentItem; if (!parent.isValid()) parentItem = _rootItem; else parentItem = static_cast<TreeItem*>(parent.internalPointer()); - TreeItem *childItem = parentItem->child(row); + TreeItem* childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); - } +} /** * Returns the model index of a TreeItem based on its index. @@ -68,8 +66,8 @@ QModelIndex TreeModel::parent(const QModelIndex &index) const if (!index.isValid()) return QModelIndex(); - TreeItem *childItem = static_cast<TreeItem*>(index.internalPointer()); - TreeItem *parentItem = childItem->parentItem(); + TreeItem* childItem = static_cast<TreeItem*>(index.internalPointer()); + TreeItem* parentItem = childItem->parentItem(); if (parentItem == _rootItem) return QModelIndex(); @@ -83,7 +81,7 @@ QModelIndex TreeModel::parent(const QModelIndex &index) const */ int TreeModel::rowCount(const QModelIndex &parent) const { - TreeItem *parentItem; + TreeItem* parentItem; if (parent.column() > 0) return 0; @@ -108,7 +106,6 @@ int TreeModel::columnCount(const QModelIndex &parent) const void TreeModel::updateData() { - } /** * Since each item manages its own columns, the column number is used to retrieve @@ -121,7 +118,7 @@ QVariant TreeModel::data(const QModelIndex &index, int role) const if (role == Qt::EditRole || role == Qt::DisplayRole) { - TreeItem *item = static_cast<TreeItem*>(index.internalPointer()); + TreeItem* item = static_cast<TreeItem*>(index.internalPointer()); return item->data(index.column()); } @@ -154,20 +151,22 @@ Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const * Returns the Item characterized by the given index. */ TreeItem* TreeModel::getItem(const QModelIndex &index) const - { - if (index.isValid()) { - TreeItem *item = static_cast<TreeItem*>(index.internalPointer()); - if (item) return item; - } - return _rootItem; - } +{ + if (index.isValid()) + { + TreeItem* item = static_cast<TreeItem*>(index.internalPointer()); + if (item) + return item; + } + return _rootItem; +} QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return _rootItem->data(section); - return QVariant(); + return QVariant(); } /** @@ -175,67 +174,74 @@ QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int rol */ bool TreeModel::removeRows(int position, int count, const QModelIndex & parent) { - TreeItem *parentItem = getItem(parent); + TreeItem* parentItem = getItem(parent); bool success = true; - beginRemoveRows(parent, position, position + count - 1); - success = parentItem->removeChildren(position, count); - endRemoveRows(); + beginRemoveRows(parent, position, position + count - 1); + success = parentItem->removeChildren(position, count); + endRemoveRows(); - return success; + return success; } /** * Test method for creating a tree model */ -void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) - { - QList<TreeItem*> parents; - QList<int> indentations; - parents << parent; - indentations << 0; - - int number = 0; - - while (number < lines.count()) { - int position = 0; - while (position < lines[number].length()) { - if (lines[number].mid(position, 1) != " ") - break; - position++; - } - - QString lineData = lines[number].mid(position).trimmed(); - - if (!lineData.isEmpty()) { - // Read the column data from the rest of the line. - QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); - QList<QVariant> columnData; - for (int column = 0; column < columnStrings.count(); ++column) - columnData << columnStrings[column]; - - if (position > indentations.last()) { - // The last child of the current parent is now the new parent - // unless the current parent has no children. - - if (parents.last()->childCount() > 0) { - parents << parents.last()->child(parents.last()->childCount()-1); - indentations << position; - } - } else { - while (position < indentations.last() && parents.count() > 0) { - parents.pop_back(); - indentations.pop_back(); - } - } - - // Append a new item to the current parent's list of children. - parents.last()->appendChild(new TreeItem(columnData, parents.last())); - } - - number++; - } - } +void TreeModel::setupModelData(const QStringList &lines, TreeItem* parent) +{ + QList<TreeItem*> parents; + QList<int> indentations; + parents << parent; + indentations << 0; + + int number = 0; + + while (number < lines.count()) + { + int position = 0; + while (position < lines[number].length()) + { + if (lines[number].mid(position, 1) != " ") + break; + position++; + } + + QString lineData = lines[number].mid(position).trimmed(); + + if (!lineData.isEmpty()) + { + // Read the column data from the rest of the line. + QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); + QList<QVariant> columnData; + for (int column = 0; column < columnStrings.count(); ++column) + columnData << columnStrings[column]; + + if (position > indentations.last()) + { + // The last child of the current parent is now the new parent + // unless the current parent has no children. + + if (parents.last()->childCount() > 0) + { + parents << parents.last()->child(parents.last()->childCount( + ) - 1); + indentations << position; + } + } + else + while (position < indentations.last() && parents.count() > 0) + { + parents.pop_back(); + indentations.pop_back(); + } + + // Append a new item to the current parent's list of children. + parents.last()->appendChild(new TreeItem(columnData, parents.last())); + } + + number++; + } +} TreeItem* TreeModel::rootItem() const { diff --git a/Base/TreeModel.h b/Base/TreeModel.h index d4726557c4f98c60daeaa8171cdf49a0148680c6..32d36ee8d233f6730d9c5e97b9b5cc4af1ac75c5 100644 --- a/Base/TreeModel.h +++ b/Base/TreeModel.h @@ -30,7 +30,8 @@ public: bool setData(const QModelIndex &index, const QVariant &value, int role /* = Qt::EditRole */); Qt::ItemFlags flags(const QModelIndex &index) const; TreeItem* getItem(const QModelIndex &index) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = + Qt::DisplayRole) const; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; QModelIndex parent(const QModelIndex &index) const; bool removeRows(int row, int count, const QModelIndex & parent); @@ -43,10 +44,10 @@ public slots: void updateData(); protected: - TreeItem* _rootItem; + TreeItem* _rootItem; private: - void setupModelData(const QStringList &lines, TreeItem *parent); + void setupModelData(const QStringList &lines, TreeItem* parent); }; #endif //QTREEMODEL_H diff --git a/Base/TreeModelIterator.cpp b/Base/TreeModelIterator.cpp index 03028c7605d5982b892f62b3b5a6a2f5ce95273c..9e36bb3616e8ca48afa748661fd33d67ed669c26 100644 --- a/Base/TreeModelIterator.cpp +++ b/Base/TreeModelIterator.cpp @@ -1,7 +1,7 @@ /** * \file TreeModelIterator.cpp * 23/6/2010 LB Initial implementation - * + * * Implementation of TreeModelIterator */ @@ -12,7 +12,7 @@ #include "TreeModel.h" TreeModelIterator::TreeModelIterator( TreeModel* model ) -: _current(NULL), _model(model) + : _current(NULL), _model(model) { if (_model->rootItem()->childCount() > 0) { @@ -31,9 +31,7 @@ TreeItem* TreeModelIterator::operator*() const TreeModelIterator& TreeModelIterator::operator++() { if (_current) - { _current = next(_current); - } return *this; } @@ -56,7 +54,7 @@ TreeItem* TreeModelIterator::next( const TreeItem* current ) // walk the sibling TreeItem* parent = current->parentItem(); next = parent ? parent->child(_currentIndex + 1) - : _model->rootItem()->child(_currentIndex + 1); + : _model->rootItem()->child(_currentIndex + 1); while (!next && parent) { // if we had no sibling walk up the parent @@ -64,7 +62,7 @@ TreeItem* TreeModelIterator::next( const TreeItem* current ) parent = parent->parentItem(); _currentIndex = _parentIndex.pop(); next = parent ? parent->child(_currentIndex + 1) - : _model->rootItem()->child(_currentIndex + 1); + : _model->rootItem()->child(_currentIndex + 1); } if (next) ++(_currentIndex); diff --git a/Base/TreeModelIterator.h b/Base/TreeModelIterator.h index b137052cf7231a72b18659a654e0202477da0671..b8d8a9cc80d48a2d19382c0c0d14435fb21cedbc 100644 --- a/Base/TreeModelIterator.h +++ b/Base/TreeModelIterator.h @@ -1,10 +1,9 @@ /** * \file TreeModelIterator.h * 23/6/2010 LB Initial implementation - * + * */ - #ifndef TREEMODELITERATOR_H #define TREEMODELITERATOR_H @@ -27,7 +26,6 @@ class TreeItem; */ class TreeModelIterator { - public: /// \brief Constructor. Provide a tree model to iterate over. TreeModelIterator(TreeModel* model); @@ -54,7 +52,6 @@ private: /// \brief The traversal implementation. TreeItem* next(const TreeItem* current); - }; #endif // TREEMODELITERATOR_H diff --git a/Base/modeltest.cpp b/Base/modeltest.cpp index 40d7d282a8aef0d1c6932ccff5f5ae105ee9ff01..a43db8aa557dd72412a5fe8be1cbcef2165c56d0 100644 --- a/Base/modeltest.cpp +++ b/Base/modeltest.cpp @@ -29,101 +29,102 @@ Q_DECLARE_METATYPE(QModelIndex) /*! Connect to all of the models signals. Whenever anything happens recheck everything. -*/ -ModelTest::ModelTest(QAbstractItemModel *_model, QObject *parent) : QObject(parent), model(_model), fetchingMore(false) + */ +ModelTest::ModelTest(QAbstractItemModel* _model, + QObject* parent) : QObject(parent), model(_model), fetchingMore(false) { - Q_ASSERT(model); - - connect(model, SIGNAL(columnsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(headerDataChanged(Qt::Orientation, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(layoutAboutToBeChanged ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(layoutChanged ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(modelReset ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - - // Special checks for inserting/removing - connect(model, SIGNAL(layoutAboutToBeChanged()), - this, SLOT(layoutAboutToBeChanged())); - connect(model, SIGNAL(layoutChanged()), - this, SLOT(layoutChanged())); - - connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(rowsAboutToBeInserted(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), - this, SLOT(rowsInserted(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), - this, SLOT(rowsRemoved(const QModelIndex &, int, int))); - - runAllTests(); + Q_ASSERT(model); + + connect(model, SIGNAL(columnsAboutToBeInserted(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(columnsAboutToBeRemoved(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(columnsInserted(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(columnsRemoved(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(headerDataChanged(Qt::Orientation, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(layoutAboutToBeChanged ()), this, SLOT(runAllTests())); + connect(model, SIGNAL(layoutChanged ()), this, SLOT(runAllTests())); + connect(model, SIGNAL(modelReset ()), this, SLOT(runAllTests())); + connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), + this, SLOT(runAllTests())); + + // Special checks for inserting/removing + connect(model, SIGNAL(layoutAboutToBeChanged()), + this, SLOT(layoutAboutToBeChanged())); + connect(model, SIGNAL(layoutChanged()), + this, SLOT(layoutChanged())); + + connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), + this, SLOT(rowsAboutToBeInserted(const QModelIndex &, int, int))); + connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), + this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int))); + connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), + this, SLOT(rowsInserted(const QModelIndex &, int, int))); + connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), + this, SLOT(rowsRemoved(const QModelIndex &, int, int))); + + runAllTests(); } void ModelTest::runAllTests() { - if (fetchingMore) - return; - nonDestructiveBasicTest(); - rowCount(); - columnCount(); - hasIndex(); - index(); - parent(); - data(); + if (fetchingMore) + return; + nonDestructiveBasicTest(); + rowCount(); + columnCount(); + hasIndex(); + index(); + parent(); + data(); } /*! nonDestructiveBasicTest tries to call a number of the basic functions (not all) to make sure the model doesn't outright segfault, testing the functions that makes sense. -*/ + */ void ModelTest::nonDestructiveBasicTest() { - Q_ASSERT(model->buddy(QModelIndex()) == QModelIndex()); - model->canFetchMore(QModelIndex()); - Q_ASSERT(model->columnCount(QModelIndex()) >= 0); - Q_ASSERT(model->data(QModelIndex()) == QVariant()); - fetchingMore = true; - model->fetchMore(QModelIndex()); - fetchingMore = false; - Qt::ItemFlags flags = model->flags(QModelIndex()); - Q_ASSERT(flags == Qt::ItemIsDropEnabled || flags == 0); - model->hasChildren(QModelIndex()); - model->hasIndex(0, 0); - model->headerData(0, Qt::Horizontal); - model->index(0, 0); - Q_ASSERT(model->index(-1, -1) == QModelIndex()); - model->itemData(QModelIndex()); - QVariant cache; - model->match(QModelIndex(), -1, cache); - model->mimeTypes(); - Q_ASSERT(model->parent(QModelIndex()) == QModelIndex()); - Q_ASSERT(model->rowCount() >= 0); - QVariant variant; - model->setData(QModelIndex(), variant, -1); - model->setHeaderData(-1, Qt::Horizontal, QVariant()); - model->setHeaderData(0, Qt::Horizontal, QVariant()); - model->setHeaderData(999999, Qt::Horizontal, QVariant()); - QMap<int, QVariant> roles; - model->sibling(0, 0, QModelIndex()); - model->span(QModelIndex()); - model->supportedDropActions(); + Q_ASSERT(model->buddy(QModelIndex()) == QModelIndex()); + model->canFetchMore(QModelIndex()); + Q_ASSERT(model->columnCount(QModelIndex()) >= 0); + Q_ASSERT(model->data(QModelIndex()) == QVariant()); + fetchingMore = true; + model->fetchMore(QModelIndex()); + fetchingMore = false; + Qt::ItemFlags flags = model->flags(QModelIndex()); + Q_ASSERT(flags == Qt::ItemIsDropEnabled || flags == 0); + model->hasChildren(QModelIndex()); + model->hasIndex(0, 0); + model->headerData(0, Qt::Horizontal); + model->index(0, 0); + Q_ASSERT(model->index(-1, -1) == QModelIndex()); + model->itemData(QModelIndex()); + QVariant cache; + model->match(QModelIndex(), -1, cache); + model->mimeTypes(); + Q_ASSERT(model->parent(QModelIndex()) == QModelIndex()); + Q_ASSERT(model->rowCount() >= 0); + QVariant variant; + model->setData(QModelIndex(), variant, -1); + model->setHeaderData(-1, Qt::Horizontal, QVariant()); + model->setHeaderData(0, Qt::Horizontal, QVariant()); + model->setHeaderData(999999, Qt::Horizontal, QVariant()); + QMap<int, QVariant> roles; + model->sibling(0, 0, QModelIndex()); + model->span(QModelIndex()); + model->supportedDropActions(); } /*! @@ -133,24 +134,24 @@ void ModelTest::nonDestructiveBasicTest() */ void ModelTest::rowCount() { - // check top row - QModelIndex topIndex = model->index(0, 0, QModelIndex()); - int rows = model->rowCount(topIndex); - Q_ASSERT(rows >= 0); - if (rows > 0) - Q_ASSERT(model->hasChildren(topIndex) == true); - - QModelIndex secondLevelIndex = model->index(0, 0, topIndex); - if (secondLevelIndex.isValid()) { // not the top level - // check a row count where parent is valid - rows = model->rowCount(secondLevelIndex); - Q_ASSERT(rows >= 0); - if (rows > 0) - Q_ASSERT(model->hasChildren(secondLevelIndex) == true); - } - - // The models rowCount() is tested more extensively in checkChildren(), - // but this catches the big mistakes + // check top row + QModelIndex topIndex = model->index(0, 0, QModelIndex()); + int rows = model->rowCount(topIndex); + Q_ASSERT(rows >= 0); + if (rows > 0) + Q_ASSERT(model->hasChildren(topIndex) == true); + + QModelIndex secondLevelIndex = model->index(0, 0, topIndex); + if (secondLevelIndex.isValid()) // not the top level + { // check a row count where parent is valid + rows = model->rowCount(secondLevelIndex); + Q_ASSERT(rows >= 0); + if (rows > 0) + Q_ASSERT(model->hasChildren(secondLevelIndex) == true); + } + + // The models rowCount() is tested more extensively in checkChildren(), + // but this catches the big mistakes } /*! @@ -158,17 +159,17 @@ void ModelTest::rowCount() */ void ModelTest::columnCount() { - // check top row - QModelIndex topIndex = model->index(0, 0, QModelIndex()); - Q_ASSERT(model->columnCount(topIndex) >= 0); + // check top row + QModelIndex topIndex = model->index(0, 0, QModelIndex()); + Q_ASSERT(model->columnCount(topIndex) >= 0); - // check a column count where parent is valid - QModelIndex childIndex = model->index(0, 0, topIndex); - if (childIndex.isValid()) - Q_ASSERT(model->columnCount(childIndex) >= 0); + // check a column count where parent is valid + QModelIndex childIndex = model->index(0, 0, topIndex); + if (childIndex.isValid()) + Q_ASSERT(model->columnCount(childIndex) >= 0); - // columnCount() is tested more extensively in checkChildren(), - // but this catches the big mistakes + // columnCount() is tested more extensively in checkChildren(), + // but this catches the big mistakes } /*! @@ -176,23 +177,23 @@ void ModelTest::columnCount() */ void ModelTest::hasIndex() { - // Make sure that invalid values returns an invalid index - Q_ASSERT(model->hasIndex(-2, -2) == false); - Q_ASSERT(model->hasIndex(-2, 0) == false); - Q_ASSERT(model->hasIndex(0, -2) == false); + // Make sure that invalid values returns an invalid index + Q_ASSERT(model->hasIndex(-2, -2) == false); + Q_ASSERT(model->hasIndex(-2, 0) == false); + Q_ASSERT(model->hasIndex(0, -2) == false); - int rows = model->rowCount(); - int columns = model->columnCount(); + int rows = model->rowCount(); + int columns = model->columnCount(); - // check out of bounds - Q_ASSERT(model->hasIndex(rows, columns) == false); - Q_ASSERT(model->hasIndex(rows + 1, columns + 1) == false); + // check out of bounds + Q_ASSERT(model->hasIndex(rows, columns) == false); + Q_ASSERT(model->hasIndex(rows + 1, columns + 1) == false); - if (rows > 0) - Q_ASSERT(model->hasIndex(0, 0) == true); + if (rows > 0) + Q_ASSERT(model->hasIndex(0, 0) == true); - // hasIndex() is tested more extensively in checkChildren(), - // but this catches the big mistakes + // hasIndex() is tested more extensively in checkChildren(), + // but this catches the big mistakes } /*! @@ -200,28 +201,28 @@ void ModelTest::hasIndex() */ void ModelTest::index() { - // Make sure that invalid values returns an invalid index - Q_ASSERT(model->index(-2, -2) == QModelIndex()); - Q_ASSERT(model->index(-2, 0) == QModelIndex()); - Q_ASSERT(model->index(0, -2) == QModelIndex()); + // Make sure that invalid values returns an invalid index + Q_ASSERT(model->index(-2, -2) == QModelIndex()); + Q_ASSERT(model->index(-2, 0) == QModelIndex()); + Q_ASSERT(model->index(0, -2) == QModelIndex()); - int rows = model->rowCount(); - int columns = model->columnCount(); + int rows = model->rowCount(); + int columns = model->columnCount(); - if (rows == 0) - return; + if (rows == 0) + return; - // Catch off by one errors - Q_ASSERT(model->index(rows, columns) == QModelIndex()); - Q_ASSERT(model->index(0, 0).isValid() == true); + // Catch off by one errors + Q_ASSERT(model->index(rows, columns) == QModelIndex()); + Q_ASSERT(model->index(0, 0).isValid() == true); - // Make sure that the same index is *always* returned - QModelIndex a = model->index(0, 0); - QModelIndex b = model->index(0, 0); - Q_ASSERT(a == b); + // Make sure that the same index is *always* returned + QModelIndex a = model->index(0, 0); + QModelIndex b = model->index(0, 0); + Q_ASSERT(a == b); - // index() is tested more extensively in checkChildren(), - // but this catches the big mistakes + // index() is tested more extensively in checkChildren(), + // but this catches the big mistakes } /*! @@ -229,43 +230,45 @@ void ModelTest::index() */ void ModelTest::parent() { - // Make sure the model wont crash and will return an invalid QModelIndex - // when asked for the parent of an invalid index. - Q_ASSERT(model->parent(QModelIndex()) == QModelIndex()); - - if (model->rowCount() == 0) - return; - - // Column 0 | Column 1 | - // QModelIndex() | | - // \- topIndex | topIndex1 | - // \- childIndex | childIndex1 | - - // Common error test #1, make sure that a top level index has a parent - // that is a invalid QModelIndex. - QModelIndex topIndex = model->index(0, 0, QModelIndex()); - Q_ASSERT(model->parent(topIndex) == QModelIndex()); - - // Common error test #2, make sure that a second level index has a parent - // that is the first level index. - if (model->rowCount(topIndex) > 0) { - QModelIndex childIndex = model->index(0, 0, topIndex); - Q_ASSERT(model->parent(childIndex) == topIndex); - } - - // Common error test #3, the second column should NOT have the same children - // as the first column in a row. - // Usually the second column shouldn't have children. - QModelIndex topIndex1 = model->index(0, 1, QModelIndex()); - if (model->rowCount(topIndex1) > 0) { - QModelIndex childIndex = model->index(0, 0, topIndex); - QModelIndex childIndex1 = model->index(0, 0, topIndex1); - Q_ASSERT(childIndex != childIndex1); - } - - // Full test, walk n levels deep through the model making sure that all - // parent's children correctly specify their parent. - checkChildren(QModelIndex()); + // Make sure the model wont crash and will return an invalid QModelIndex + // when asked for the parent of an invalid index. + Q_ASSERT(model->parent(QModelIndex()) == QModelIndex()); + + if (model->rowCount() == 0) + return; + + // Column 0 | Column 1 | + // QModelIndex() | | + // \- topIndex | topIndex1 | + // \- childIndex | childIndex1 | + + // Common error test #1, make sure that a top level index has a parent + // that is a invalid QModelIndex. + QModelIndex topIndex = model->index(0, 0, QModelIndex()); + Q_ASSERT(model->parent(topIndex) == QModelIndex()); + + // Common error test #2, make sure that a second level index has a parent + // that is the first level index. + if (model->rowCount(topIndex) > 0) + { + QModelIndex childIndex = model->index(0, 0, topIndex); + Q_ASSERT(model->parent(childIndex) == topIndex); + } + + // Common error test #3, the second column should NOT have the same children + // as the first column in a row. + // Usually the second column shouldn't have children. + QModelIndex topIndex1 = model->index(0, 1, QModelIndex()); + if (model->rowCount(topIndex1) > 0) + { + QModelIndex childIndex = model->index(0, 0, topIndex); + QModelIndex childIndex1 = model->index(0, 0, topIndex1); + Q_ASSERT(childIndex != childIndex1); + } + + // Full test, walk n levels deep through the model making sure that all + // parent's children correctly specify their parent. + checkChildren(QModelIndex()); } /*! @@ -284,94 +287,98 @@ void ModelTest::parent() */ void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth) { - // First just try walking back up the tree. - QModelIndex p = parent; - while (p.isValid()) - p = p.parent(); - - // For models that are dynamically populated - if (model->canFetchMore(parent)) { - fetchingMore = true; - model->fetchMore(parent); - fetchingMore = false; - } - - int rows = model->rowCount(parent); - int columns = model->columnCount(parent); - - if (rows > 0) - Q_ASSERT(model->hasChildren(parent)); - - // Some further testing against rows(), columns(), and hasChildren() - Q_ASSERT(rows >= 0); - Q_ASSERT(columns >= 0); - if (rows > 0) - Q_ASSERT(model->hasChildren(parent) == true); - - //qDebug() << "parent:" << model->data(parent).toString() << "rows:" << rows - // << "columns:" << columns << "parent column:" << parent.column(); - - Q_ASSERT(model->hasIndex(rows + 1, 0, parent) == false); - for (int r = 0; r < rows; ++r) { - if (model->canFetchMore(parent)) { - fetchingMore = true; - model->fetchMore(parent); - fetchingMore = false; - } - Q_ASSERT(model->hasIndex(r, columns + 1, parent) == false); - for (int c = 0; c < columns; ++c) { - Q_ASSERT(model->hasIndex(r, c, parent) == true); - QModelIndex index = model->index(r, c, parent); - // rowCount() and columnCount() said that it existed... - Q_ASSERT(index.isValid() == true); - - // index() should always return the same index when called twice in a row - QModelIndex modifiedIndex = model->index(r, c, parent); - Q_ASSERT(index == modifiedIndex); - - // Make sure we get the same index if we request it twice in a row - QModelIndex a = model->index(r, c, parent); - QModelIndex b = model->index(r, c, parent); - Q_ASSERT(a == b); - - // Some basic checking on the index that is returned - Q_ASSERT(index.model() == model); - Q_ASSERT(index.row() == r); - Q_ASSERT(index.column() == c); - // While you can technically return a QVariant usually this is a sign - // of an bug in data() Disable if this really is ok in your model. - //Q_ASSERT(model->data(index, Qt::DisplayRole).isValid() == true); - - // If the next test fails here is some somewhat useful debug you play with. - /* - if (model->parent(index) != parent) { - qDebug() << r << c << currentDepth << model->data(index).toString() - << model->data(parent).toString(); - qDebug() << index << parent << model->parent(index); - // And a view that you can even use to show the model. - //QTreeView view; - //view.setModel(model); - //view.show(); - }*/ - - // Check that we can get back our real parent. - QModelIndex p = model->parent(index); - //qDebug() << "child:" << index; - //qDebug() << p; - //qDebug() << parent; - Q_ASSERT(model->parent(index) == parent); - - // recursively go down the children - if (model->hasChildren(index) && currentDepth < 10 ) { - //qDebug() << r << c << "has children" << model->rowCount(index); - checkChildren(index, ++currentDepth); - }/* else { if (currentDepth >= 10) qDebug() << "checked 10 deep"; };*/ - - // make sure that after testing the children that the index doesn't change. - QModelIndex newerIndex = model->index(r, c, parent); - Q_ASSERT(index == newerIndex); - } - } + // First just try walking back up the tree. + QModelIndex p = parent; + while (p.isValid()) + p = p.parent(); + + // For models that are dynamically populated + if (model->canFetchMore(parent)) + { + fetchingMore = true; + model->fetchMore(parent); + fetchingMore = false; + } + + int rows = model->rowCount(parent); + int columns = model->columnCount(parent); + + if (rows > 0) + Q_ASSERT(model->hasChildren(parent)); + + // Some further testing against rows(), columns(), and hasChildren() + Q_ASSERT(rows >= 0); + Q_ASSERT(columns >= 0); + if (rows > 0) + Q_ASSERT(model->hasChildren(parent) == true); + + //qDebug() << "parent:" << model->data(parent).toString() << "rows:" << rows + // << "columns:" << columns << "parent column:" << parent.column(); + + Q_ASSERT(model->hasIndex(rows + 1, 0, parent) == false); + for (int r = 0; r < rows; ++r) + { + if (model->canFetchMore(parent)) + { + fetchingMore = true; + model->fetchMore(parent); + fetchingMore = false; + } + Q_ASSERT(model->hasIndex(r, columns + 1, parent) == false); + for (int c = 0; c < columns; ++c) + { + Q_ASSERT(model->hasIndex(r, c, parent) == true); + QModelIndex index = model->index(r, c, parent); + // rowCount() and columnCount() said that it existed... + Q_ASSERT(index.isValid() == true); + + // index() should always return the same index when called twice in a row + QModelIndex modifiedIndex = model->index(r, c, parent); + Q_ASSERT(index == modifiedIndex); + + // Make sure we get the same index if we request it twice in a row + QModelIndex a = model->index(r, c, parent); + QModelIndex b = model->index(r, c, parent); + Q_ASSERT(a == b); + + // Some basic checking on the index that is returned + Q_ASSERT(index.model() == model); + Q_ASSERT(index.row() == r); + Q_ASSERT(index.column() == c); + // While you can technically return a QVariant usually this is a sign + // of an bug in data() Disable if this really is ok in your model. + //Q_ASSERT(model->data(index, Qt::DisplayRole).isValid() == true); + + // If the next test fails here is some somewhat useful debug you play with. + /* + if (model->parent(index) != parent) { + qDebug() << r << c << currentDepth << model->data(index).toString() + << model->data(parent).toString(); + qDebug() << index << parent << model->parent(index); + // And a view that you can even use to show the model. + //QTreeView view; + //view.setModel(model); + //view.show(); + }*/ + + // Check that we can get back our real parent. + QModelIndex p = model->parent(index); + //qDebug() << "child:" << index; + //qDebug() << p; + //qDebug() << parent; + Q_ASSERT(model->parent(index) == parent); + + // recursively go down the children + if (model->hasChildren(index) && currentDepth < 10 ) + //qDebug() << r << c << "has children" << model->rowCount(index); + checkChildren(index, ++currentDepth); + /* else { if (currentDepth >= 10) qDebug() << "checked 10 deep"; };*/ + + // make sure that after testing the children that the index doesn't change. + QModelIndex newerIndex = model->index(r, c, parent); + Q_ASSERT(index == newerIndex); + } + } } /*! @@ -379,80 +386,75 @@ void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth) */ void ModelTest::data() { - // Invalid index should return an invalid qvariant - Q_ASSERT(!model->data(QModelIndex()).isValid()); - - if (model->rowCount() == 0) - return; - - // A valid index should have a valid QVariant data - Q_ASSERT(model->index(0, 0).isValid()); - - // shouldn't be able to set data on an invalid index - Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), Qt::DisplayRole) == false); - - // General Purpose roles that should return a QString - QVariant variant = model->data(model->index(0, 0), Qt::ToolTipRole); - if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert<QString>(variant)); - } - variant = model->data(model->index(0, 0), Qt::StatusTipRole); - if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert<QString>(variant)); - } - variant = model->data(model->index(0, 0), Qt::WhatsThisRole); - if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert<QString>(variant)); - } - - // General Purpose roles that should return a QSize - variant = model->data(model->index(0, 0), Qt::SizeHintRole); - if (variant.isValid()) { - Q_ASSERT(qVariantCanConvert<QSize>(variant)); - } - - // General Purpose roles that should return a QFont - QVariant fontVariant = model->data(model->index(0, 0), Qt::FontRole); - if (fontVariant.isValid()) { - Q_ASSERT(qVariantCanConvert<QFont>(fontVariant)); - } - - // Check that the alignment is one we know about - QVariant textAlignmentVariant = model->data(model->index(0, 0), Qt::TextAlignmentRole); - if (textAlignmentVariant.isValid()) { - int alignment = textAlignmentVariant.toInt(); - Q_ASSERT(alignment == Qt::AlignLeft || - alignment == Qt::AlignRight || - alignment == Qt::AlignHCenter || - alignment == Qt::AlignJustify || - alignment == Qt::AlignTop || - alignment == Qt::AlignBottom || - alignment == Qt::AlignVCenter || - alignment == Qt::AlignCenter || - alignment == Qt::AlignAbsolute || - alignment == Qt::AlignLeading || - alignment == Qt::AlignTrailing); - } - - // General Purpose roles that should return a QColor - QVariant colorVariant = model->data(model->index(0, 0), Qt::BackgroundColorRole); - if (colorVariant.isValid()) { - Q_ASSERT(qVariantCanConvert<QColor>(colorVariant)); - } - - colorVariant = model->data(model->index(0, 0), Qt::TextColorRole); - if (colorVariant.isValid()) { - Q_ASSERT(qVariantCanConvert<QColor>(colorVariant)); - } - - // Check that the "check state" is one we know about. - QVariant checkStateVariant = model->data(model->index(0, 0), Qt::CheckStateRole); - if (checkStateVariant.isValid()) { - int state = checkStateVariant.toInt(); - Q_ASSERT(state == Qt::Unchecked || - state == Qt::PartiallyChecked || - state == Qt::Checked); - } + // Invalid index should return an invalid qvariant + Q_ASSERT(!model->data(QModelIndex()).isValid()); + + if (model->rowCount() == 0) + return; + + // A valid index should have a valid QVariant data + Q_ASSERT(model->index(0, 0).isValid()); + + // shouldn't be able to set data on an invalid index + Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), Qt::DisplayRole) == false); + + // General Purpose roles that should return a QString + QVariant variant = model->data(model->index(0, 0), Qt::ToolTipRole); + if (variant.isValid()) + Q_ASSERT(qVariantCanConvert<QString>(variant)); + variant = model->data(model->index(0, 0), Qt::StatusTipRole); + if (variant.isValid()) + Q_ASSERT(qVariantCanConvert<QString>(variant)); + variant = model->data(model->index(0, 0), Qt::WhatsThisRole); + if (variant.isValid()) + Q_ASSERT(qVariantCanConvert<QString>(variant)); + + // General Purpose roles that should return a QSize + variant = model->data(model->index(0, 0), Qt::SizeHintRole); + if (variant.isValid()) + Q_ASSERT(qVariantCanConvert<QSize>(variant)); + + // General Purpose roles that should return a QFont + QVariant fontVariant = model->data(model->index(0, 0), Qt::FontRole); + if (fontVariant.isValid()) + Q_ASSERT(qVariantCanConvert<QFont>(fontVariant)); + + // Check that the alignment is one we know about + QVariant textAlignmentVariant = model->data(model->index(0, 0), Qt::TextAlignmentRole); + if (textAlignmentVariant.isValid()) + { + int alignment = textAlignmentVariant.toInt(); + Q_ASSERT(alignment == Qt::AlignLeft || + alignment == Qt::AlignRight || + alignment == Qt::AlignHCenter || + alignment == Qt::AlignJustify || + alignment == Qt::AlignTop || + alignment == Qt::AlignBottom || + alignment == Qt::AlignVCenter || + alignment == Qt::AlignCenter || + alignment == Qt::AlignAbsolute || + alignment == Qt::AlignLeading || + alignment == Qt::AlignTrailing); + } + + // General Purpose roles that should return a QColor + QVariant colorVariant = model->data(model->index(0, 0), Qt::BackgroundColorRole); + if (colorVariant.isValid()) + Q_ASSERT(qVariantCanConvert<QColor>(colorVariant)); + + colorVariant = model->data(model->index(0, 0), Qt::TextColorRole); + if (colorVariant.isValid()) + Q_ASSERT(qVariantCanConvert<QColor>(colorVariant)); + + // Check that the "check state" is one we know about. + QVariant checkStateVariant = model->data(model->index(0, 0), Qt::CheckStateRole); + if (checkStateVariant.isValid()) + { + int state = checkStateVariant.toInt(); + Q_ASSERT(state == Qt::Unchecked || + state == Qt::PartiallyChecked || + state == Qt::Checked); + } } /*! @@ -462,13 +464,13 @@ void ModelTest::data() */ void ModelTest::rowsAboutToBeInserted(const QModelIndex &parent, int start, int end) { - Q_UNUSED(end); - Changing c; - c.parent = parent; - c.oldSize = model->rowCount(parent); - c.last = model->data(model->index(start - 1, 0, parent)); - c.next = model->data(model->index(start, 0, parent)); - insert.push(c); + Q_UNUSED(end); + Changing c; + c.parent = parent; + c.oldSize = model->rowCount(parent); + c.last = model->data(model->index(start - 1, 0, parent)); + c.next = model->data(model->index(start, 0, parent)); + insert.push(c); } /*! @@ -478,34 +480,35 @@ void ModelTest::rowsAboutToBeInserted(const QModelIndex &parent, int start, int */ void ModelTest::rowsInserted(const QModelIndex & parent, int start, int end) { - Changing c = insert.pop(); - Q_ASSERT(c.parent == parent); - Q_ASSERT(c.oldSize + (end - start + 1) == model->rowCount(parent)); - Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent))); - /* - if (c.next != model->data(model->index(end + 1, 0, c.parent))) { - qDebug() << start << end; - for (int i=0; i < model->rowCount(); ++i) - qDebug() << model->index(i, 0).data().toString(); - qDebug() << c.next << model->data(model->index(end + 1, 0, c.parent)); - } - */ - Q_ASSERT(c.next == model->data(model->index(end + 1, 0, c.parent))); + Changing c = insert.pop(); + Q_ASSERT(c.parent == parent); + Q_ASSERT(c.oldSize + (end - start + 1) == model->rowCount(parent)); + Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent))); + /* + if (c.next != model->data(model->index(end + 1, 0, c.parent))) { + qDebug() << start << end; + for (int i=0; i < model->rowCount(); ++i) + qDebug() << model->index(i, 0).data().toString(); + qDebug() << c.next << model->data(model->index(end + 1, 0, c.parent)); + } + */ + Q_ASSERT(c.next == model->data(model->index(end + 1, 0, c.parent))); } void ModelTest::layoutAboutToBeChanged() { - for (int i = 0; i < qBound(0, model->rowCount(), 100); ++i) - changing.append(QPersistentModelIndex(model->index(i, 0))); + for (int i = 0; i < qBound(0, model->rowCount(), 100); ++i) + changing.append(QPersistentModelIndex(model->index(i, 0))); } void ModelTest::layoutChanged() { - for (int i = 0; i < changing.count(); ++i) { - QPersistentModelIndex p = changing[i]; - Q_ASSERT(p == model->index(p.row(), p.column(), p.parent())); - } - changing.clear(); + for (int i = 0; i < changing.count(); ++i) + { + QPersistentModelIndex p = changing[i]; + Q_ASSERT(p == model->index(p.row(), p.column(), p.parent())); + } + changing.clear(); } /*! @@ -515,12 +518,12 @@ void ModelTest::layoutChanged() */ void ModelTest::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) { - Changing c; - c.parent = parent; - c.oldSize = model->rowCount(parent); - c.last = model->data(model->index(start - 1, 0, parent)); - c.next = model->data(model->index(end + 1, 0, parent)); - remove.push(c); + Changing c; + c.parent = parent; + c.oldSize = model->rowCount(parent); + c.last = model->data(model->index(start - 1, 0, parent)); + c.next = model->data(model->index(end + 1, 0, parent)); + remove.push(c); } /*! @@ -530,10 +533,10 @@ void ModelTest::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int e */ void ModelTest::rowsRemoved(const QModelIndex & parent, int start, int end) { - Changing c = remove.pop(); - Q_ASSERT(c.parent == parent); - Q_ASSERT(c.oldSize - (end - start + 1) == model->rowCount(parent)); - Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent))); - Q_ASSERT(c.next == model->data(model->index(start, 0, c.parent))); + Changing c = remove.pop(); + Q_ASSERT(c.parent == parent); + Q_ASSERT(c.oldSize - (end - start + 1) == model->rowCount(parent)); + Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent))); + Q_ASSERT(c.next == model->data(model->index(start, 0, c.parent))); } diff --git a/Base/modeltest.h b/Base/modeltest.h index 38b6b2bed3a7e188a69933a83738204acbcd6c26..ca72795ff9a9917253e466bfd58fe60429979a04 100644 --- a/Base/modeltest.h +++ b/Base/modeltest.h @@ -24,53 +24,53 @@ #ifndef MODELTEST_H #define MODELTEST_H -#include <QtCore/QObject> #include <QtCore/QAbstractItemModel> +#include <QtCore/QObject> #include <QtCore/QStack> class ModelTest : public QObject { - Q_OBJECT + Q_OBJECT public: - ModelTest(QAbstractItemModel *model, QObject *parent = 0); + ModelTest(QAbstractItemModel* model, QObject* parent = 0); private Q_SLOTS: - void nonDestructiveBasicTest(); - void rowCount(); - void columnCount(); - void hasIndex(); - void index(); - void parent(); - void data(); + void nonDestructiveBasicTest(); + void rowCount(); + void columnCount(); + void hasIndex(); + void index(); + void parent(); + void data(); protected Q_SLOTS: - void runAllTests(); - void layoutAboutToBeChanged(); - void layoutChanged(); - void rowsAboutToBeInserted(const QModelIndex &parent, int start, int end); - void rowsInserted(const QModelIndex & parent, int start, int end); - void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end); - void rowsRemoved(const QModelIndex & parent, int start, int end); + void runAllTests(); + void layoutAboutToBeChanged(); + void layoutChanged(); + void rowsAboutToBeInserted(const QModelIndex &parent, int start, int end); + void rowsInserted(const QModelIndex & parent, int start, int end); + void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end); + void rowsRemoved(const QModelIndex & parent, int start, int end); private: - void checkChildren(const QModelIndex &parent, int currentDepth = 0); + void checkChildren(const QModelIndex &parent, int currentDepth = 0); - QAbstractItemModel *model; + QAbstractItemModel* model; - struct Changing - { - QModelIndex parent; - int oldSize; - QVariant last; - QVariant next; - }; - QStack<Changing> insert; - QStack<Changing> remove; + struct Changing + { + QModelIndex parent; + int oldSize; + QVariant last; + QVariant next; + }; + QStack<Changing> insert; + QStack<Changing> remove; - bool fetchingMore; + bool fetchingMore; - QList<QPersistentModelIndex> changing; + QList<QPersistentModelIndex> changing; }; #endif diff --git a/DataView/BaseItem.h b/DataView/BaseItem.h index 4a614f2122ada16fb61f1fae5551ab86ac9aa7d7..08c4722eb82975f9be44c611691426138644ddff 100644 --- a/DataView/BaseItem.h +++ b/DataView/BaseItem.h @@ -6,12 +6,11 @@ #ifndef BASEITEM_H #define BASEITEM_H - #include "Point.h" -#include <vtkPolyDataAlgorithm.h> #include "VtkStationSource.h" #include <QModelIndex> +#include <vtkPolyDataAlgorithm.h> /** * \brief A BaseItem contains additional Information about a subtree in the StationTreeModel. @@ -19,11 +18,10 @@ * It is used for list names in the StationTreeModel and it contains the * vtkObject for visualisation of the whole list in 3D. */ -class BaseItem +class BaseItem { - public: - BaseItem(const QString &listName, const std::vector<GEOLIB::Point*> *stations = NULL ) + BaseItem(const QString &listName, const std::vector<GEOLIB::Point*>* stations = NULL ) : _stations(stations), _vtkSource(VtkStationSource::New()) { // create the vtk-object for 3d-visualisation of this list @@ -37,24 +35,23 @@ public: } /// Returns the associated QModelIndex which belongs to a Qt model - QModelIndex modelIndex() const { return _modelIndex; }; + QModelIndex modelIndex() const { return _modelIndex; } /// Sets the model index - void setModelIndex( QModelIndex index ) { _modelIndex = index; }; + void setModelIndex( QModelIndex index ) { _modelIndex = index; } - const std::vector<GEOLIB::Point*> *getStations() { return _stations; } + const std::vector<GEOLIB::Point*>* getStations() { return _stations; } /// Returns the Vtk polydata source object vtkPolyDataAlgorithm* vtkSource() const { return _vtkSource; } private: QModelIndex _modelIndex; - const std::vector<GEOLIB::Point*> *_stations; + const std::vector<GEOLIB::Point*>* _stations; /// The Vtk data source object. This is the starting point for a Vtk data /// visualization pipeline. vtkPolyDataAlgorithm* _vtkSource; - }; #endif //BASEITEM_H diff --git a/DataView/ColorTableModel.cpp b/DataView/ColorTableModel.cpp index 165012dd844ec37dca6d1a257c533833ab1ed622..98d5a2c9f82be701a6e9fd19511895f09e4b5fce 100644 --- a/DataView/ColorTableModel.cpp +++ b/DataView/ColorTableModel.cpp @@ -8,8 +8,8 @@ #include "ColorTableModel.h" - -ColorTableModel::ColorTableModel( const std::map<std::string, GEOLIB::Color*> &colorLookupTable, QObject* parent /*= 0*/ ) +ColorTableModel::ColorTableModel( const std::map<std::string, GEOLIB::Color*> &colorLookupTable, + QObject* parent /*= 0*/ ) { Q_UNUSED(parent) @@ -27,19 +27,20 @@ int ColorTableModel::columnCount( const QModelIndex& parent /*= QModelIndex()*/ return 2; } -QVariant ColorTableModel::headerData( int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/ ) const +QVariant ColorTableModel::headerData( int section, Qt::Orientation orientation, + int role /*= Qt::DisplayRole*/ ) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { - switch (section) - { - case 0: return "Name"; - case 1: return "Colour"; - default: return QVariant(); - } + switch (section) + { + case 0: return "Name"; + case 1: return "Colour"; + default: return QVariant(); + } } else return QString("Row %1").arg(section); @@ -47,55 +48,55 @@ QVariant ColorTableModel::headerData( int section, Qt::Orientation orientation, QVariant ColorTableModel::data( const QModelIndex& index, int role ) const { - if (!index.isValid()) - return QVariant(); + if (!index.isValid()) + return QVariant(); - if (index.row() >= _listOfPairs.size() || index.row()<0) - return QVariant(); + if (index.row() >= _listOfPairs.size() || index.row() < 0) + return QVariant(); if (role == Qt::DisplayRole) { QPair<QString, QColor> pair = _listOfPairs.at(index.row()); switch (index.column()) - { - case 0: - return pair.first; - case 1: - return pair.second; - default: - return QVariant(); + { + case 0: + return pair.first; + case 1: + return pair.second; + default: + return QVariant(); } - } + } return QVariant(); } bool ColorTableModel::buildTable(const std::map<std::string, GEOLIB::Color*> &colorLookupTable) { - int count = 0; - beginInsertRows(QModelIndex(), 0, colorLookupTable.size()-1); + int count = 0; + beginInsertRows(QModelIndex(), 0, colorLookupTable.size() - 1); - for (std::map<std::string, GEOLIB::Color*>::const_iterator it=colorLookupTable.begin(); it !=colorLookupTable.end(); ++it) - { - QColor color((*(it->second))[0], (*(it->second))[1], (*(it->second))[2]); - QString name(QString::fromStdString(it->first)); + for (std::map<std::string, GEOLIB::Color*>::const_iterator it = colorLookupTable.begin(); + it != colorLookupTable.end(); ++it) + { + QColor color((*(it->second))[0], (*(it->second))[1], (*(it->second))[2]); + QString name(QString::fromStdString(it->first)); /* Saudi Arabia strat names * - if (it->first.compare("1")==0) name="Buweib"; - if (it->first.compare("2")==0) name="Wasia"; - if (it->first.compare("3")==0) name="Aruma"; - if (it->first.compare("4")==0) name="Umm Er Radhuma"; - if (it->first.compare("5")==0) name="Rus"; - if (it->first.compare("6")==0) name="Dammam"; - if (it->first.compare("7")==0) name="Neogene"; - */ - - QPair<QString, QColor> pair(name, color); - _listOfPairs.insert(count++, pair); - } - - endInsertRows(); - return true; -} + if (it->first.compare("1")==0) name="Buweib"; + if (it->first.compare("2")==0) name="Wasia"; + if (it->first.compare("3")==0) name="Aruma"; + if (it->first.compare("4")==0) name="Umm Er Radhuma"; + if (it->first.compare("5")==0) name="Rus"; + if (it->first.compare("6")==0) name="Dammam"; + if (it->first.compare("7")==0) name="Neogene"; + */ + + QPair<QString, QColor> pair(name, color); + _listOfPairs.insert(count++, pair); + } + endInsertRows(); + return true; +} diff --git a/DataView/ColorTableModel.h b/DataView/ColorTableModel.h index db7a4e8c86192c81b5bdd6d5367272db13e6b91e..37debb210436ea4320cb3e4a736d320d70462d28 100644 --- a/DataView/ColorTableModel.h +++ b/DataView/ColorTableModel.h @@ -6,9 +6,9 @@ #ifndef COLORTABLEMODEL_H #define COLORTABLEMODEL_H +#include "Color.h" #include <QAbstractTableModel> #include <QColor> -#include "Color.h" /** * The PolylinesModel is a Qt model which represents Polylines. @@ -18,7 +18,8 @@ class ColorTableModel : public QAbstractTableModel Q_OBJECT public: - ColorTableModel( const std::map<std::string, GEOLIB::Color*> &colorLookupTable, QObject* parent = 0 ); + ColorTableModel( const std::map<std::string, GEOLIB::Color*> &colorLookupTable, + QObject* parent = 0 ); ~ColorTableModel(); int columnCount(const QModelIndex& parent = QModelIndex()) const; @@ -31,12 +32,12 @@ public: return _listOfPairs.size(); } - QVariant headerData( int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/ ) const; + QVariant headerData( int section, Qt::Orientation orientation, + int role /*= Qt::DisplayRole*/ ) const; private: bool buildTable( const std::map<std::string, GEOLIB::Color*> &colorLookupTable ); QList< QPair<QString, QColor> > _listOfPairs; - }; #endif // COLORTABLEMODEL_H diff --git a/DataView/ColorTableView.cpp b/DataView/ColorTableView.cpp index 65120e9ce5475fbc46bd6793cfc9a6deadf06796..aadf9ecabcd9a5143f929d150c19fa3df8aa100e 100644 --- a/DataView/ColorTableView.cpp +++ b/DataView/ColorTableView.cpp @@ -1,12 +1,12 @@ /** * \file ColorTableView.cpp * 17/06/2010 KR Initial implementation - * + * */ +#include "ColorTableView.h" #include <QHeaderView> #include <QPainter> -#include "ColorTableView.h" ColorTableView::ColorTableView( QWidget* parent /*= 0*/ ) : QTableView(parent) { @@ -16,7 +16,9 @@ ColorTableView::ColorTableView( QWidget* parent /*= 0*/ ) : QTableView(parent) this->resizeRowsToContents(); } -void ColorTableViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +void ColorTableViewDelegate::paint(QPainter* painter, + const QStyleOptionViewItem &option, + const QModelIndex &index) const { QColor val; if (index.column() == 1) @@ -32,10 +34,12 @@ void ColorTableViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem QItemDelegate::paint(painter, option, index); } -QSize ColorTableViewDelegate::sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const +QSize ColorTableViewDelegate::sizeHint( const QStyleOptionViewItem &option, + const QModelIndex &index ) const { QSize s = QItemDelegate::sizeHint(option, index); - if( s.isValid() ) s.setHeight((int)(0.5*s.height())); + if( s.isValid() ) + s.setHeight((int)(0.5 * s.height())); return s; } diff --git a/DataView/ColorTableView.h b/DataView/ColorTableView.h index 7df960691d88bb6742ad8d695339ea554899dcf9..4ff1c48ddd4c1fece1631d57f239147c9d810ce1 100644 --- a/DataView/ColorTableView.h +++ b/DataView/ColorTableView.h @@ -5,8 +5,8 @@ #ifndef COLORTABLEVIEW_H #define COLORTABLEVIEW_H -#include <QTableView> #include <QItemDelegate> +#include <QTableView> /** * A QTableView to display colour lookup tables. @@ -18,7 +18,6 @@ class ColorTableView : public QTableView public: /// Constructor ColorTableView(QWidget* parent = 0); - }; /** @@ -30,10 +29,11 @@ class ColorTableViewDelegate : public QItemDelegate public: /// Constructor - ColorTableViewDelegate(QWidget *parent = 0) : QItemDelegate(parent) {}; + ColorTableViewDelegate(QWidget* parent = 0) : QItemDelegate(parent) {} /// Overwrites the paint-method to set user-defined properties instead of the default properties. - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + void paint(QPainter* painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const; QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const; }; diff --git a/DataView/CondItem.h b/DataView/CondItem.h index 01e26ef6e073a2511d9f32522c00cc982119895d..d03d4a27dbd57d1d531666752116f3f31da8b992 100644 --- a/DataView/CondItem.h +++ b/DataView/CondItem.h @@ -6,32 +6,30 @@ #ifndef CONDITEM_H #define CONDITEM_H -#include "TreeItem.h" #include "FEMCondition.h" +#include "TreeItem.h" #include "VtkPointsSource.h" - /** * \brief A TreeItem containing a condition of a FEM (BC, IC or ST). * \sa TreeItem */ class CondItem : public TreeItem { - public: /// Constructor - CondItem(const QList<QVariant> &data, TreeItem *parent, const FEMCondition* cond) + CondItem(const QList<QVariant> &data, TreeItem* parent, const FEMCondition* cond) : TreeItem(data, parent), _item(cond) { - }; + } - ~CondItem() {}; + ~CondItem() {} /// Returns the FEM Condition associated with the item. - const FEMCondition* getItem() { return _item; }; + const FEMCondition* getItem() { return _item; } /// Returns the geo-object on which the condition is placed. - const GEOLIB::GeoObject* getGeoObject() { return this->getGeoObject(); }; + const GEOLIB::GeoObject* getGeoObject() { return this->getGeoObject(); } private: const FEMCondition* _item; diff --git a/DataView/CondObjectListItem.h b/DataView/CondObjectListItem.h index 88f84a22ee174189bf3163ba64e3efb1ac2a7a54..873398fb323e7b5237b87e6aba7331a61a7a9c80 100644 --- a/DataView/CondObjectListItem.h +++ b/DataView/CondObjectListItem.h @@ -6,16 +6,15 @@ #ifndef CONDOBJECTLISTITEM_H #define CONDOBJECTLISTITEM_H - #include "FEMCondition.h" #include "TreeItem.h" -#include <vtkPolyDataAlgorithm.h> -#include <vtkThresholdPoints.h> #include "VtkConditionSource.h" #include <QModelIndex> +#include <vtkPolyDataAlgorithm.h> +#include <vtkThresholdPoints.h> /** - * \brief The CondObjectListItem is the TreeItem that contains the subtree for either initial conditions, + * \brief The CondObjectListItem is the TreeItem that contains the subtree for either initial conditions, * boundary conditions source terms. This item also contains the vtk source-item for visualisation of this * information and the indices of the associated geometry-objects. * Upon creation the type of condition needs to be defined and the vector of points of the associated geometry @@ -25,13 +24,18 @@ */ class CondObjectListItem : public TreeItem { - public: /// Constructor for the TreeItem specifying FEM Conditions. - CondObjectListItem(const QList<QVariant> &data, TreeItem *parent, FEMCondition::CondType type, const std::vector<GEOLIB::Point*> *points) - : TreeItem(data, parent), _vtkSource(VtkConditionSource::New()), _type(type), _cond_vec(new std::vector<FEMCondition*>) + CondObjectListItem(const QList<QVariant> &data, + TreeItem* parent, + FEMCondition::CondType type, + const std::vector<GEOLIB::Point*>* points) + : TreeItem(data, + parent), _vtkSource(VtkConditionSource::New()), _type(type), + _cond_vec(new std::vector<FEMCondition*>) { - QString display_name = parent->data(0).toString().append(" - ").append(QString::fromStdString(FEMCondition::condTypeToString(type))); + QString display_name = parent->data(0).toString().append(" - ").append( + QString::fromStdString(FEMCondition::condTypeToString(type))); static_cast<VtkConditionSource*>(_vtkSource)->setData( points, _cond_vec); static_cast<VtkConditionSource*>(_vtkSource)->SetName( display_name ); } @@ -43,32 +47,33 @@ public: } /// Adds FEMCondtion for construction of VTK object. - void addCondition(FEMCondition* cond) { - _cond_vec->push_back(cond); + void addCondition(FEMCondition* cond) + { + _cond_vec->push_back(cond); _vtkSource->Modified(); - }; - + } /// Returns the type of geo-objects contained in the subtree of this item. - FEMCondition::CondType getType() { return _type; }; + FEMCondition::CondType getType() { return _type; } /// Returns the Vtk polydata source object - vtkPolyDataAlgorithm* vtkSource() const { - return _vtkSource; + vtkPolyDataAlgorithm* vtkSource() const + { + return _vtkSource; /* - vtkThresholdPoints* threshold = vtkThresholdPoints::New(); - threshold->SetInputConnection(_vtkSource->GetOutputPort()); - threshold->ThresholdByUpper(-9998); - threshold->Update(); - return threshold; - */ - }; + vtkThresholdPoints* threshold = vtkThresholdPoints::New(); + threshold->SetInputConnection(_vtkSource->GetOutputPort()); + threshold->ThresholdByUpper(-9998); + threshold->Update(); + return threshold; + */ + } private: /// The Vtk data source object. This is the starting point for a Vtk data visualization pipeline. vtkPolyDataAlgorithm* _vtkSource; FEMCondition::CondType _type; - std::vector<FEMCondition*> *_cond_vec; + std::vector<FEMCondition*>* _cond_vec; }; #endif //CONDOBJECTLISTITEM_H diff --git a/DataView/ConditionModel.cpp b/DataView/ConditionModel.cpp index 8141ab108887ae9810144015e52bcff7de655fe5..3192f3b2be44c5ed6a374ca6924c4f9b47f86d68 100644 --- a/DataView/ConditionModel.cpp +++ b/DataView/ConditionModel.cpp @@ -4,20 +4,19 @@ */ // ** INCLUDES ** -#include "ConditionModel.h" -#include "CondObjectListItem.h" #include "CondItem.h" -#include "GeoObject.h" +#include "CondObjectListItem.h" +#include "ConditionModel.h" +#include "FEMCondition.h" #include "GEOObjects.h" +#include "GeoObject.h" #include "GeoType.h" -#include "FEMCondition.h" -#include <vtkPolyDataAlgorithm.h> #include <QFileInfo> - +#include <vtkPolyDataAlgorithm.h> ConditionModel::ConditionModel( ProjectData &project, QObject* parent /*= 0*/ ) -: TreeModel(parent), _project(project) + : TreeModel(parent), _project(project) { QList<QVariant> rootData; delete _rootItem; @@ -38,14 +37,17 @@ int ConditionModel::columnCount( const QModelIndex &parent /*= QModelIndex()*/ ) void ConditionModel::addConditionItem(FEMCondition* c) { - TreeItem* geoParent = this->getGEOParent(QString::fromStdString(c->getAssociatedGeometryName()), true); + TreeItem* geoParent = + this->getGEOParent(QString::fromStdString(c->getAssociatedGeometryName()), true); CondObjectListItem* condParent = this->getCondParent(geoParent, c->getCondType()); - if (condParent==NULL) condParent = this->createCondParent(geoParent, c->getCondType()); + if (condParent == NULL) + condParent = this->createCondParent(geoParent, c->getCondType()); if (condParent) { QList<QVariant> condData; - condData << QString::fromStdString(c->getGeoName()) << QString::fromStdString(c->getGeoTypeAsString()); + condData << QString::fromStdString(c->getGeoName()) << QString::fromStdString( + c->getGeoTypeAsString()); CondItem* condItem = new CondItem(condData, condParent, c); condParent->appendChild(condItem); // add process information @@ -54,27 +56,31 @@ void ConditionModel::addConditionItem(FEMCondition* c) TreeItem* pcsInfo = new TreeItem(pcsData, condItem); // add information on primary variable QList<QVariant> pvData; - pvData << QString::fromStdString(convertPrimaryVariableToString(c->getProcessPrimaryVariable())); + pvData << + QString::fromStdString(convertPrimaryVariableToString(c->getProcessPrimaryVariable())); TreeItem* pvInfo = new TreeItem(pvData, condItem); // add distribution information QList<QVariant> disData; - disData << QString::fromStdString(convertDisTypeToString(c->getProcessDistributionType())); + disData << + QString::fromStdString(convertDisTypeToString(c->getProcessDistributionType())); std::vector<double> dis_value = c->getDisValue(); TreeItem* disInfo; - if (!(c->getProcessDistributionType() == FiniteElement::LINEAR || c->getProcessDistributionType() == FiniteElement::LINEAR_NEUMANN)) + if (!(c->getProcessDistributionType() == FiniteElement::LINEAR || + c->getProcessDistributionType() == FiniteElement::LINEAR_NEUMANN)) { - for (size_t i=0; i<dis_value.size(); i++) disData << dis_value[i]; + for (size_t i = 0; i < dis_value.size(); i++) + disData << dis_value[i]; disInfo = new TreeItem(disData, condItem); } else { - size_t nVals = dis_value.size()/2; + size_t nVals = dis_value.size() / 2; disData << static_cast<int>(nVals); disInfo = new TreeItem(disData, condItem); - for (size_t i=0; i<nVals; i++) + for (size_t i = 0; i < nVals; i++) { QList<QVariant> linData; - linData << dis_value[2*i] << dis_value[2*i+1]; + linData << dis_value[2 * i] << dis_value[2 * i + 1]; TreeItem* linInfo = new TreeItem(linData, disInfo); disInfo->appendChild(linInfo); } @@ -83,21 +89,25 @@ void ConditionModel::addConditionItem(FEMCondition* c) condItem->appendChild(pcsInfo); condItem->appendChild(pvInfo); condItem->appendChild(disInfo); - + condParent->addCondition(c); reset(); - } else - std::cout << "Error in ConditionModel::addConditionItem() - Parent object not found..." << std::endl; + std::cout << + "Error in ConditionModel::addConditionItem() - Parent object not found..." << + std::endl; } void ConditionModel::addConditions(std::vector<FEMCondition*> &conditions) { - for (size_t i=0; i<conditions.size(); i++) + for (size_t i = 0; i < conditions.size(); i++) { bool is_domain = (conditions[i]->getGeoType() == GEOLIB::GEODOMAIN) ? true : false; - const GEOLIB::GeoObject* object = this->getGEOObject(conditions[i]->getAssociatedGeometryName(), conditions[i]->getGeoType(), conditions[i]->getGeoName()); + const GEOLIB::GeoObject* object = this->getGEOObject( + conditions[i]->getAssociatedGeometryName(), + conditions[i]->getGeoType(), + conditions[i]->getGeoName()); if (object || is_domain) { conditions[i]->setGeoObj(object); @@ -105,32 +115,36 @@ void ConditionModel::addConditions(std::vector<FEMCondition*> &conditions) this->addConditionItem(conditions[i]); } else - std::cout << "Error in ConditionModel::addConditions() - Specified geometrical object " << conditions[i]->getGeoName() << " not found in associated geometry..." << std::endl; + std::cout << + "Error in ConditionModel::addConditions() - Specified geometrical object " + << conditions[i]->getGeoName() << + " not found in associated geometry..." << + std::endl; } } /* -bool ConditionModel::removeConditionItem(const QModelIndex &idx) -{ - if (idx.isValid()) - { - CondItem* item = dynamic_cast<CondItem*>(this->getItem(idx)); - if (item) - { - emit conditionRemoved(this, idx); - TreeItem* parent = item->parentItem(); - if (parent->childCount() <=1) - this->removeFEMConditions(QString::fromStdString(item->getItem()->getAssociatedGeometryName()), item->getItem()->getCondType()); - else - parent->removeChildren(item->row(),1); - reset(); - return true; - } - } + bool ConditionModel::removeConditionItem(const QModelIndex &idx) + { + if (idx.isValid()) + { + CondItem* item = dynamic_cast<CondItem*>(this->getItem(idx)); + if (item) + { + emit conditionRemoved(this, idx); + TreeItem* parent = item->parentItem(); + if (parent->childCount() <=1) + this->removeFEMConditions(QString::fromStdString(item->getItem()->getAssociatedGeometryName()), item->getItem()->getCondType()); + else + parent->removeChildren(item->row(),1); + reset(); + return true; + } + } - std::cout << "ConditionModel::removeCondition() - Specified index does not exist." << std::endl; - return false; -} -*/ + std::cout << "ConditionModel::removeCondition() - Specified index does not exist." << std::endl; + return false; + } + */ void ConditionModel::removeFEMConditions(const QString &geometry_name, FEMCondition::CondType type) { @@ -147,34 +161,58 @@ void ConditionModel::removeFEMConditions(const QString &geometry_name, FEMCondit _project.removeConditions(geometry_name.toStdString(), type); } -const GEOLIB::GeoObject* ConditionModel::getGEOObject(const std::string &geo_name, GEOLIB::GEOTYPE type, const std::string &obj_name) const +const GEOLIB::GeoObject* ConditionModel::getGEOObject(const std::string &geo_name, + GEOLIB::GEOTYPE type, + const std::string &obj_name) const { - if (type==GEOLIB::POINT) return this->_project.getGEOObjects()->getPointVecObj(geo_name)->getElementByName(obj_name); - else if (type==GEOLIB::POLYLINE) return this->_project.getGEOObjects()->getPolylineVecObj(geo_name)->getElementByName(obj_name); - else if (type==GEOLIB::SURFACE) return this->_project.getGEOObjects()->getSurfaceVecObj(geo_name)->getElementByName(obj_name); + if (type == GEOLIB::POINT) + return this->_project.getGEOObjects()->getPointVecObj(geo_name)->getElementByName( + obj_name); + else if (type == GEOLIB::POLYLINE) + return this->_project.getGEOObjects()->getPolylineVecObj(geo_name)-> + getElementByName(obj_name); + else if (type == GEOLIB::SURFACE) + return this->_project.getGEOObjects()->getSurfaceVecObj(geo_name)->getElementByName( + obj_name); return NULL; } -int ConditionModel::getGEOIndex(const std::string &geo_name, GEOLIB::GEOTYPE type, const std::string &obj_name) const +int ConditionModel::getGEOIndex(const std::string &geo_name, + GEOLIB::GEOTYPE type, + const std::string &obj_name) const { bool exists(false); size_t idx(0); - if (type==GEOLIB::POINT) exists = this->_project.getGEOObjects()->getPointVecObj(geo_name)->getElementIDByName(obj_name, idx); - else if (type==GEOLIB::POLYLINE) exists = this->_project.getGEOObjects()->getPolylineVecObj(geo_name)->getElementIDByName(obj_name, idx); - else if (type==GEOLIB::SURFACE) exists = this->_project.getGEOObjects()->getSurfaceVecObj(geo_name)->getElementIDByName(obj_name, idx); + if (type == GEOLIB::POINT) + exists = + this->_project.getGEOObjects()->getPointVecObj(geo_name)-> + getElementIDByName( + obj_name, + idx); + else if (type == GEOLIB::POLYLINE) + exists = + this->_project.getGEOObjects()->getPolylineVecObj(geo_name)-> + getElementIDByName( + obj_name, + idx); + else if (type == GEOLIB::SURFACE) + exists = + this->_project.getGEOObjects()->getSurfaceVecObj(geo_name)-> + getElementIDByName( + obj_name, + idx); - if (exists) return idx; + if (exists) + return idx; return -1; } TreeItem* ConditionModel::getGEOParent(const QString &geoName, bool create_item) { int nLists = _rootItem->childCount(); - for (int i=0; i<nLists; i++) - { + for (int i = 0; i < nLists; i++) if (_rootItem->child(i)->data(0).toString().compare(geoName) == 0) return _rootItem->child(i); - } if (create_item) { @@ -190,11 +228,9 @@ TreeItem* ConditionModel::getGEOParent(const QString &geoName, bool create_item) CondObjectListItem* ConditionModel::getCondParent(TreeItem* parent, FEMCondition::CondType type) { int nLists = parent->childCount(); - for (int i=0; i<nLists; i++) - { + for (int i = 0; i < nLists; i++) if (dynamic_cast<CondObjectListItem*>(parent->child(i))->getType() == type) return dynamic_cast<CondObjectListItem*>(parent->child(i)); - } return NULL; } @@ -205,7 +241,7 @@ CondObjectListItem* ConditionModel::createCondParent(TreeItem* parent, FEMCondit condData << condType << ""; std::string geo_name = parent->data(0).toString().toStdString(); - const std::vector<GEOLIB::Point*> *pnts = _project.getGEOObjects()->getPointVec(geo_name); + const std::vector<GEOLIB::Point*>* pnts = _project.getGEOObjects()->getPointVec(geo_name); if (pnts) { CondObjectListItem* cond = new CondObjectListItem(condData, parent, type, pnts); @@ -216,13 +252,15 @@ CondObjectListItem* ConditionModel::createCondParent(TreeItem* parent, FEMCondit return NULL; } -vtkPolyDataAlgorithm* ConditionModel::vtkSource(const std::string &name, FEMCondition::CondType type) +vtkPolyDataAlgorithm* ConditionModel::vtkSource(const std::string &name, + FEMCondition::CondType type) { TreeItem* geoParent = this->getGEOParent(QString::fromStdString(name)); if (geoParent) { CondObjectListItem* condParent = this->getCondParent(geoParent, type); - if (condParent) return condParent->vtkSource(); + if (condParent) + return condParent->vtkSource(); } return NULL; } diff --git a/DataView/ConditionModel.h b/DataView/ConditionModel.h index b24f06a5e42a10673654801376145d442bed90bd..c77ebdba0c333ed5438359e49077f5fdec73ac7e 100644 --- a/DataView/ConditionModel.h +++ b/DataView/ConditionModel.h @@ -7,16 +7,17 @@ #define CONDITIONMODEL_H // ** INCLUDES ** -#include "TreeModel.h" #include "ProjectData.h" +#include "TreeModel.h" class FEMCondition; class CondObjectListItem; class vtkPolyDataAlgorithm; -namespace GEOLIB { - class GeoObject; - class GeoType; +namespace GEOLIB +{ +class GeoObject; +class GeoType; } /** @@ -31,7 +32,7 @@ public: ConditionModel(ProjectData &project, QObject* parent = 0); ~ConditionModel(); - int columnCount(const QModelIndex& parent = QModelIndex()) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const; /// Returns the vtk source object for the specified subtree of a geometry with the given name. vtkPolyDataAlgorithm* vtkSource(const std::string &name, FEMCondition::CondType type); @@ -40,7 +41,8 @@ public slots: void addConditions(std::vector<FEMCondition*> &conditions); /// Removes a subtree (BCs, ICs, STs) from the the model. If all conditions for a given geometry are removed, this tree is completely removed. - void removeFEMConditions(const QString &geometry_name, FEMCondition::CondType type = FEMCondition::UNSPECIFIED); + void removeFEMConditions(const QString &geometry_name, + FEMCondition::CondType type = FEMCondition::UNSPECIFIED); private: /// Adds a new FEM condition to the condition tree model. @@ -58,10 +60,13 @@ private: /// Returns the subtree item for a geometry with the given name. If create_item is true, this item will be created if it doesn't exist yet. TreeItem* getGEOParent(const QString &geoName, bool create_item = false); /// Returns the geo object for a geometric item of the given name and type for the associated geometry. - const GEOLIB::GeoObject* getGEOObject(const std::string &geo_name, GEOLIB::GEOTYPE type, const std::string &obj_name) const; + const GEOLIB::GeoObject* getGEOObject(const std::string &geo_name, + GEOLIB::GEOTYPE type, + const std::string &obj_name) const; /// Returns the index of a geometric item of the given name and type for the associated geometry. - int getGEOIndex(const std::string &geo_name, GEOLIB::GEOTYPE type, const std::string &obj_name) const; - + int getGEOIndex(const std::string &geo_name, + GEOLIB::GEOTYPE type, + const std::string &obj_name) const; ProjectData& _project; diff --git a/DataView/ConditionTabWidget.cpp b/DataView/ConditionTabWidget.cpp index d669b3cddc77ef97d3234bd79bb3b6cf8b8ecb66..10323c838e336a25a3a3f7c8597ba69e3fc19763 100644 --- a/DataView/ConditionTabWidget.cpp +++ b/DataView/ConditionTabWidget.cpp @@ -6,12 +6,12 @@ */ // ** INCLUDES ** +#include "ConditionModel.h" #include "ConditionTabWidget.h" #include "TreeItem.h" -#include "ConditionModel.h" ConditionTabWidget::ConditionTabWidget( QWidget* parent /*= 0*/ ) -: QWidget(parent) + : QWidget(parent) { setupUi(this); } diff --git a/DataView/ConditionTabWidget.h b/DataView/ConditionTabWidget.h index 16e58ccd564e58d2e07c8f614351c72f99aeab9b..076d6360d04ff17e574e8f0281d917a0d76c669c 100644 --- a/DataView/ConditionTabWidget.h +++ b/DataView/ConditionTabWidget.h @@ -4,7 +4,6 @@ * */ - #ifndef CONDITIONTABWIDGET_H #define CONDITIONTABWIDGET_H @@ -20,7 +19,6 @@ class ConditionTabWidget : public QWidget, public Ui_ConditionTabWidgetBase public: ConditionTabWidget(QWidget* parent = 0); - }; #endif // CONDITIONTABWIDGET_H diff --git a/DataView/ConditionView.cpp b/DataView/ConditionView.cpp index 9fd5849583587a5dd33a2a6a56d40a9823897a41..b865854f26d9afd691c17de17ec1140094b714b9 100644 --- a/DataView/ConditionView.cpp +++ b/DataView/ConditionView.cpp @@ -5,11 +5,10 @@ #include <QMenu> -#include "ConditionView.h" -#include "ConditionModel.h" -#include "CondObjectListItem.h" #include "CondItem.h" - +#include "CondObjectListItem.h" +#include "ConditionModel.h" +#include "ConditionView.h" ConditionView::ConditionView(QWidget* parent) : QTreeView(parent) { @@ -28,7 +27,8 @@ void ConditionView::on_Clicked(QModelIndex idx) qDebug("%d, %d",idx.parent().row(), idx.row()); } -void ConditionView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) +void ConditionView::selectionChanged( const QItemSelection &selected, + const QItemSelection &deselected ) { emit itemSelectionChanged(selected, deselected); return QTreeView::selectionChanged(selected, deselected); @@ -37,8 +37,12 @@ void ConditionView::selectionChanged( const QItemSelection &selected, const QIte void ConditionView::contextMenuEvent( QContextMenuEvent* event ) { Q_UNUSED(event); - - CondObjectListItem* item = dynamic_cast<CondObjectListItem*>(static_cast<ConditionModel*>(this->model())->getItem(this->selectionModel()->currentIndex())); + + CondObjectListItem* item = + dynamic_cast<CondObjectListItem*>(static_cast<ConditionModel*>(this->model())-> + getItem(this + -> + selectionModel()->currentIndex())); if (item) { QMenu menu; @@ -46,27 +50,30 @@ void ConditionView::contextMenuEvent( QContextMenuEvent* event ) connect(removeAction, SIGNAL(triggered()), this, SLOT(removeCondition())); menu.exec(event->globalPos()); } - } void ConditionView::removeCondition() { - CondObjectListItem* item = dynamic_cast<CondObjectListItem*>(static_cast<ConditionModel*>(this->model())->getItem(this->selectionModel()->currentIndex())); + CondObjectListItem* item = + dynamic_cast<CondObjectListItem*>(static_cast<ConditionModel*>(this->model())-> + getItem(this + -> + selectionModel()->currentIndex())); QString geo_name = item->parentItem()->data(0).toString(); FEMCondition::CondType type = item->getType(); emit conditionsRemoved(geo_name, type); } /* -void ConditionView::removeAllConditions() -{ - ConditionModel* model = static_cast<ConditionModel*>(this->model()); + void ConditionView::removeAllConditions() + { + ConditionModel* model = static_cast<ConditionModel*>(this->model()); - for (size_t j=0; j<3; j++) - { - QModelIndex parentIndex = model->index(j, 0, QModelIndex()); - int nChildren = model->getItem(parentIndex)->childCount(); - for (int i=nChildren; i>=0; i--) - emit requestConditionRemoval(model->index(i, 0, parentIndex)); - } -} -*/ + for (size_t j=0; j<3; j++) + { + QModelIndex parentIndex = model->index(j, 0, QModelIndex()); + int nChildren = model->getItem(parentIndex)->childCount(); + for (int i=nChildren; i>=0; i--) + emit requestConditionRemoval(model->index(i, 0, parentIndex)); + } + } + */ diff --git a/DataView/ConditionView.h b/DataView/ConditionView.h index 2ed40808e31ec621af666224a4b7f5a1c9a4c7bc..619da4366aa65c969e1ddab9b2521f281c11e5aa 100644 --- a/DataView/ConditionView.h +++ b/DataView/ConditionView.h @@ -6,14 +6,13 @@ #ifndef CONDITIONVIEW_H #define CONDITIONVIEW_H -#include <QTreeView> #include <QContextMenuEvent> +#include <QTreeView> #include "FEMCondition.h" class ConditionModel; - /** * \brief A view for FEM-Conditions (Initial- & Boundary Conditions / Source Terms) with a number of additional * information such as Process Type, Distribution, etc. @@ -44,10 +43,9 @@ private slots: //void removeAllConditions(); signals: - void itemSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected); + void itemSelectionChanged(const QItemSelection & selected, + const QItemSelection & deselected); void conditionsRemoved(QString, FEMCondition::CondType); - }; - #endif //CONDITIONVIEW_H diff --git a/DataView/DBConnectionDialog.cpp b/DataView/DBConnectionDialog.cpp index 5f12a44c79059e2b938894b5acfd2d45af198fb3..b3b6349ef5333cf45db0e7c78950526e64ac6304 100644 --- a/DataView/DBConnectionDialog.cpp +++ b/DataView/DBConnectionDialog.cpp @@ -3,26 +3,22 @@ * KR Initial implementation */ -#include <QSettings> #include "DBConnectionDialog.h" - +#include <QSettings> /// Constructor DBConnectionDialog::DBConnectionDialog(QDialog* parent) : QDialog(parent) { setupUi(this); - int idx=0; + int idx = 0; QSettings settings("UFZ", "OpenGeoSys-5"); if (!settings.value("DBProtocol", "").toString().isEmpty()) - { - for (int i=0; i<driverBox->count(); i++) - { - if (driverBox->itemText(i).startsWith(settings.value("DBProtocol", "").toString())) + for (int i = 0; i < driverBox->count(); i++) + if (driverBox->itemText(i).startsWith(settings.value("DBProtocol", + "").toString())) idx = i; - } - } driverBox->setCurrentIndex(idx); hostnameLine->setText(settings.value("DBHost", "").toString()); diff --git a/DataView/DBConnectionDialog.h b/DataView/DBConnectionDialog.h index 8870e2c8412a83c1b107fca881cc9d09a3ac132d..7385933faaefbd1514a14098e36d9a6a0a293587 100644 --- a/DataView/DBConnectionDialog.h +++ b/DataView/DBConnectionDialog.h @@ -6,10 +6,9 @@ #ifndef DBCONNECTIONDIALOG_H #define DBCONNECTIONDIALOG_H -#include <QtGui/QMainWindow> -#include <QSqlQueryModel> #include "ui_DBConnection.h" - +#include <QSqlQueryModel> +#include <QtGui/QMainWindow> /** * \brief A dialog window for settung up a database connection @@ -22,16 +21,12 @@ public: DBConnectionDialog(QDialog* parent = 0); ~DBConnectionDialog(void); - - - private slots: void accept(); void reject(); signals: void connectionRequested(QString, QString, QString, QString, QString); - }; #endif //DBCONNECTIONDIALOG_H diff --git a/DataView/DataView.cpp b/DataView/DataView.cpp index 116a5c52154322a7f963bf2f57d2008daa56d91f..9d500cdee8c8e8945483b5c9fb2452cc42c62e39 100644 --- a/DataView/DataView.cpp +++ b/DataView/DataView.cpp @@ -6,25 +6,25 @@ */ #include "DataView.h" -#include <QHeaderView> #include "GridAdapter.h" #include "MshEditDialog.h" -#include "MshModel.h" #include "MshItem.h" +#include "MshModel.h" #include "OGSError.h" +#include <QHeaderView> #include "VtkMeshSource.h" -#include <QObject> -#include <QMenu> #include <QContextMenuEvent> #include <QFileDialog> +#include <QMenu> +#include <QObject> #include <QSettings> #include "MeshIO/OGSMeshIO.h" DataView::DataView( QWidget* parent /*= 0*/ ) -: QTreeView(parent) + : QTreeView(parent) { //resizeColumnsToContents(); //resizeRowsToContents(); @@ -35,20 +35,23 @@ void DataView::updateView() setAlternatingRowColors(true); setColumnWidth(0,125); size_t nColumns = (this->model() != NULL) ? this->model()->columnCount() : 0; - for (size_t i=1; i<nColumns; i++) + for (size_t i = 1; i < nColumns; i++) resizeColumnToContents(i); } - void DataView::addMeshAction() { QSettings settings("UFZ", "OpenGeoSys-5"); - QString fileName = QFileDialog::getOpenFileName(this, "Select mesh file", settings.value("lastOpenedFileDirectory").toString(), "OpenGeosys mesh files (*.msh);;All files (* *.*)"); + QString fileName = + QFileDialog::getOpenFileName(this, "Select mesh file", settings.value( + "lastOpenedFileDirectory").toString(), + "OpenGeosys mesh files (*.msh);;All files (* *.*)"); if (!fileName.isEmpty()) { std::string name = fileName.toStdString(); MeshLib::CFEMesh* msh = FileIO::OGSMeshIO::loadMeshFromFile(name); - if (msh) static_cast<MshModel*>(this->model())->addMesh(msh, name); + if (msh) + static_cast<MshModel*>(this->model())->addMesh(msh, name); } } @@ -60,12 +63,11 @@ void DataView::removeMesh() void DataView::removeAllMeshes() { TreeItem* root = static_cast<MshModel*>(this->model())->getItem(QModelIndex()); - int nChildren = root->childCount()-1; - for (int i=nChildren; i>=0; i--) + int nChildren = root->childCount() - 1; + for (int i = nChildren; i >= 0; i--) emit requestMeshRemoval(this->model()->index(i, 0, QModelIndex())); } - void DataView::contextMenuEvent( QContextMenuEvent* event ) { QModelIndex index = this->selectionModel()->currentIndex(); @@ -94,36 +96,52 @@ void DataView::openMshEditDialog() { MshModel* model = static_cast<MshModel*>(this->model()); QModelIndex index = this->selectionModel()->currentIndex(); - const MeshLib::CFEMesh* mesh = static_cast<MshModel*>(this->model())->getMesh(index)->getCFEMesh(); + const MeshLib::CFEMesh* mesh = + static_cast<MshModel*>(this->model())->getMesh(index)->getCFEMesh(); MshEditDialog meshEdit(mesh); - connect(&meshEdit, SIGNAL(mshEditFinished(MeshLib::CFEMesh*, std::string&)), model, SLOT(addMesh(MeshLib::CFEMesh*, std::string&))); + connect(&meshEdit, + SIGNAL(mshEditFinished(MeshLib::CFEMesh *, + std::string &)), model, + SLOT(addMesh(MeshLib::CFEMesh *, std::string &))); meshEdit.exec(); } int DataView::writeMeshToFile() const { QModelIndex index = this->selectionModel()->currentIndex(); - const MeshLib::CFEMesh* mesh = static_cast<MshModel*>(this->model())->getMesh(index)->getCFEMesh(); + const MeshLib::CFEMesh* mesh = + static_cast<MshModel*>(this->model())->getMesh(index)->getCFEMesh(); if (mesh) { QSettings settings("UFZ", "OpenGeoSys-5"); - QString mshName = QString::fromStdString(static_cast<MshModel*>(this->model())->getMesh(index)->getName()); - std::string fileName = QFileDialog::getSaveFileName(NULL, "Save mesh as", settings.value("lastOpenedFileDirectory").toString(), "GeoSys mesh file (*.msh)").toStdString(); + QString mshName = QString::fromStdString( + static_cast<MshModel*>(this->model())->getMesh(index)->getName()); + std::string fileName = QFileDialog::getSaveFileName(NULL, + "Save mesh as", + settings.value( + "lastOpenedFileDirectory") + .toString(), + "GeoSys mesh file (*.msh)"). + toStdString(); if (!fileName.empty()) { std::ofstream out (fileName.c_str()); - if (out.is_open()) { + if (out.is_open()) + { FileIO::OGSMeshIO::write (mesh, out); out.close(); return 1; } else - std::cout << "MshTabWidget::saveMeshFile() - Could not create file..." << std::endl; + std::cout << + "MshTabWidget::saveMeshFile() - Could not create file..." << + std::endl; } - else OGSError::box("No file name entered."); + else + OGSError::box("No file name entered."); } return 0; } @@ -131,11 +149,11 @@ int DataView::writeMeshToFile() const void DataView::addDIRECTSourceTerms() { QModelIndex index = this->selectionModel()->currentIndex(); - const std::vector<GEOLIB::Point*> *points = static_cast<MshModel*>(this->model())->getMesh(index)->getNodes(); + const std::vector<GEOLIB::Point*>* points = static_cast<MshModel*>(this->model())->getMesh( + index)->getNodes(); emit requestDIRECTSourceTerms(points); } - void DataView::checkMeshQuality () { QModelIndex index = this->selectionModel()->currentIndex(); @@ -143,34 +161,33 @@ void DataView::checkMeshQuality () emit qualityCheckRequested(item->vtkSource()); } - /* -void DataView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) -{ - emit itemSelectionChanged(selected, deselected); - return QTreeView::selectionChanged(selected, deselected); -} + void DataView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) + { + emit itemSelectionChanged(selected, deselected); + return QTreeView::selectionChanged(selected, deselected); + } -void DataView::selectionChangedFromOutside( const QItemSelection &selected, const QItemSelection &deselected ) -{ - QItemSelectionModel* selModel = this->selectionModel(); + void DataView::selectionChangedFromOutside( const QItemSelection &selected, const QItemSelection &deselected ) + { + QItemSelectionModel* selModel = this->selectionModel(); - Q_ASSERT(selModel); + Q_ASSERT(selModel); - selModel->blockSignals(true); - selModel->select(deselected, QItemSelectionModel::Deselect); - selModel->select(selected, QItemSelectionModel::Select); - selModel->blockSignals(false); + selModel->blockSignals(true); + selModel->select(deselected, QItemSelectionModel::Deselect); + selModel->select(selected, QItemSelectionModel::Select); + selModel->blockSignals(false); - Model* model = static_cast<Model*>(this->model()); - //model->setSelectionFromOutside(selected, deselected); + Model* model = static_cast<Model*>(this->model()); + //model->setSelectionFromOutside(selected, deselected); - return QTreeView::selectionChanged(selected, deselected); -} + return QTreeView::selectionChanged(selected, deselected); + } -void DataView::clearSelection() -{ - selectionModel()->clearSelection(); -} -*/ + void DataView::clearSelection() + { + selectionModel()->clearSelection(); + } + */ diff --git a/DataView/DataView.h b/DataView/DataView.h index 12f365f071d9048b1945fed42e6999856ddb5033..94ea2627f1471e42ff80236b10f8f8dfd7579cba 100644 --- a/DataView/DataView.h +++ b/DataView/DataView.h @@ -12,14 +12,15 @@ class GridAdapter; class MshModel; class VtkMeshSource; -namespace MeshLib { - class CFEMesh; +namespace MeshLib +{ +class CFEMesh; } /* -namespace GEOLIB { - class Point; -} -*/ + namespace GEOLIB { + class Point; + } + */ /** * The DataView is table view which acts as a base class for displaying * several OSG data formats. @@ -72,18 +73,17 @@ private slots: */ void checkMeshQuality(); - signals: void qualityCheckRequested(VtkMeshSource*); void requestMeshRemoval(const QModelIndex&); void requestDIRECTSourceTerms(const std::vector<GEOLIB::Point*>*); void saveMeshAction(); - + /* - void itemSelectionChanged(const QItemSelection &selected, - const QItemSelection &deselected); - void itemSelectionChangedFromOutside(const QItemSelection &selected, - const QItemSelection &deselected); -*/ + void itemSelectionChanged(const QItemSelection &selected, + const QItemSelection &deselected); + void itemSelectionChangedFromOutside(const QItemSelection &selected, + const QItemSelection &deselected); + */ }; #endif // DATAVIEW_H diff --git a/DataView/DatabaseConnection.cpp b/DataView/DatabaseConnection.cpp index 3e5f74d6430619b847814305379643edb93f4fa7..77ff0c5d8309d433947cdcebdc06154f0f62f07d 100644 --- a/DataView/DatabaseConnection.cpp +++ b/DataView/DatabaseConnection.cpp @@ -4,22 +4,22 @@ */ #include "DatabaseConnection.h" -#include <QSqlError> -#include <QSqlQuery> -#include <QSqlQueryModel> -#include <QVariant> -#include <QSettings> #include "DateTools.h" #include "OGSError.h" #include "QueryResultsDialog.h" #include "StringTools.h" +#include <QSettings> +#include <QSqlError> +#include <QSqlQuery> +#include <QSqlQueryModel> +#include <QVariant> -#include <iostream> #include <fstream> - +#include <iostream> /// The OGS5-Connection to a database -DatabaseConnection::DatabaseConnection(GEOLIB::GEOObjects* geoObjects, QObject* parent) : QObject(parent), _geoObjects(geoObjects) +DatabaseConnection::DatabaseConnection(GEOLIB::GEOObjects* geoObjects, + QObject* parent) : QObject(parent), _geoObjects(geoObjects) { } @@ -43,7 +43,8 @@ int DatabaseConnection::dbConnect() QString pass = settings.value("DBPass", "").toString(); //default connection - if (protocol.isEmpty() || hostname.isEmpty() || dbname.isEmpty() || user.isEmpty() || pass.isEmpty()) + if (protocol.isEmpty() || hostname.isEmpty() || dbname.isEmpty() || user.isEmpty() || + pass.isEmpty()) { protocol = "QOCI"; hostname = "cora1-vip.leipzig.ufz.de"; @@ -64,7 +65,11 @@ int DatabaseConnection::dbConnect() * \param pass The password for the specified user name * \return 1 if the connection has been established, 0 (and an error message) otherwise. */ -int DatabaseConnection::dbConnect(QString protocol, QString hostname, QString dbname, QString user, QString pass) +int DatabaseConnection::dbConnect(QString protocol, + QString hostname, + QString dbname, + QString user, + QString pass) { QSqlDatabase::removeDatabase(_db.connectionName()); @@ -86,7 +91,11 @@ int DatabaseConnection::dbConnect(QString protocol, QString hostname, QString db * \param pass The password for the specified user name * \return 1 if the connection has been established, 0 (and an error message) otherwise. */ -int DatabaseConnection::setConnection(QString protocol, QString hostname, QString dbname, QString user, QString pass) +int DatabaseConnection::setConnection(QString protocol, + QString hostname, + QString dbname, + QString user, + QString pass) { QSettings settings("UFZ", "OpenGeoSys-5"); @@ -109,8 +118,10 @@ int DatabaseConnection::test(bool showBox) { if (_db.open()) { - if (showBox) OGSError::box("Database connection established."); - else std::cout << "Database connection established...\n"; + if (showBox) + OGSError::box("Database connection established."); + else + std::cout << "Database connection established...\n"; _db.close(); return 1; } @@ -123,7 +134,6 @@ int DatabaseConnection::test(bool showBox) } } - /// Outputting an error related to the database connection void DatabaseConnection::databaseError() { @@ -140,8 +150,9 @@ void DatabaseConnection::getListSelection() { if (_db.open()) { - QSqlQueryModel *qModel = new QSqlQueryModel(); - qModel->setQuery("select l.listid, c.catname, l.listname from lists l, categories c where c.catid=l.catid order by c.catname"); + QSqlQueryModel* qModel = new QSqlQueryModel(); + qModel->setQuery( + "select l.listid, c.catname, l.listname from lists l, categories c where c.catid=l.catid order by c.catname"); QueryResultsDialog* dbView = new QueryResultsDialog(); connect(dbView, SIGNAL(listSelected(int)), this, SLOT(loadStationList(int))); @@ -150,7 +161,6 @@ void DatabaseConnection::getListSelection() dbView->exec(); _db.close(); - } else databaseError(); @@ -169,7 +179,6 @@ bool DatabaseConnection::isConnected() */ int DatabaseConnection::loadStationList(const int &listID) { - return loadStationList(listID, GEOLIB::getRandomColor()); } @@ -185,35 +194,61 @@ int DatabaseConnection::loadStationList(int listID, const GEOLIB::Color* const c { QSqlQuery query, stnQuery; QString stationName; - std::vector<GEOLIB::Point*> *stations = new std::vector<GEOLIB::Point*>; + std::vector<GEOLIB::Point*>* stations = new std::vector<GEOLIB::Point*>; - query.exec("select stationtype from geosysstationtypes where listid=" + QString::number(listID)); + query.exec( + "select stationtype from geosysstationtypes where listid=" + + QString::number(listID)); if (query.next()) { - GEOLIB::Station::StationType type = static_cast<GEOLIB::Station::StationType>(query.value(0).toInt()); + GEOLIB::Station::StationType type = + static_cast<GEOLIB::Station::StationType>(query.value(0).toInt()); if (type == GEOLIB::Station::BOREHOLE) - query.exec("select c.catname, l.listname from lists l, categories c, boreholes b where c.catid=l.catid and l.listid=b.listid and l.listid=" + QString::number(listID)); + query.exec( + "select c.catname, l.listname from lists l, categories c, boreholes b where c.catid=l.catid and l.listid=b.listid and l.listid=" + + QString::number(listID)); else - query.exec("select c.catname, l.listname from lists l, categories c where c.catid=l.catid and l.listid=" + QString::number(listID)); + query.exec( + "select c.catname, l.listname from lists l, categories c where c.catid=l.catid and l.listid=" + + QString::number(listID)); if (query.next()) { - QString listName = (query.value(0)).toString() + " (" + (query.value(1)).toString() + ")"; + QString listName = (query.value(0)).toString() + " (" + + (query.value(1)).toString() + ")"; if (type == GEOLIB::Station::BOREHOLE) - stnQuery.exec("select s.stationid, s.name, s.x, s.y, s.z, b.bdepth, to_char(b.bdate, 'YYYY-MM-DD') from stations s, boreholes b where s.listid=b.listid and s.stationid=b.stationid and s.listid=" + QString::number(listID) + " order by stationid"); + stnQuery.exec( + "select s.stationid, s.name, s.x, s.y, s.z, b.bdepth, to_char(b.bdate, 'YYYY-MM-DD') from stations s, boreholes b where s.listid=b.listid and s.stationid=b.stationid and s.listid=" + + QString::number(listID) + " order by stationid"); else - stnQuery.exec("select stationid, name, x, y, z from stations where listid=" + QString::number(listID) + " order by stationid"); + stnQuery.exec( + "select stationid, name, x, y, z from stations where listid=" + + QString::number(listID) + " order by stationid"); while (stnQuery.next()) { stationName = stnQuery.value(1).toString(); - if (stationName.isEmpty()) stationName = "Station" + stnQuery.value(0).toString(); + if (stationName.isEmpty()) + stationName = "Station" + + stnQuery.value(0).toString(); GEOLIB::Station* newStation; - if (type == GEOLIB::Station::BOREHOLE) newStation = GEOLIB::StationBorehole::createStation(stationName.toStdString(), stnQuery.value(2).toDouble(), stnQuery.value(3).toDouble(), stnQuery.value(4).toDouble(), stnQuery.value(5).toDouble(), stnQuery.value(6).toString().toStdString()); - else newStation = GEOLIB::Station::createStation(stationName.toStdString(), stnQuery.value(2).toDouble(), stnQuery.value(3).toDouble(), stnQuery.value(4).toDouble()); + if (type == GEOLIB::Station::BOREHOLE) + newStation = GEOLIB::StationBorehole::createStation( + stationName.toStdString(), + stnQuery.value(2).toDouble(), + stnQuery.value(3).toDouble(), + stnQuery.value(4).toDouble(), + stnQuery.value(5).toDouble(), + stnQuery.value(6).toString().toStdString()); + else + newStation = GEOLIB::Station::createStation( + stationName.toStdString(), + stnQuery.value(2).toDouble(), + stnQuery.value(3).toDouble(), + stnQuery.value(4).toDouble()); newStation->setColor(color); stations->push_back(newStation); } @@ -223,7 +258,8 @@ int DatabaseConnection::loadStationList(int listID, const GEOLIB::Color* const c addStratigraphy(listID, stations); std::string temp_name (listName.toStdString()); - if (!stations->empty()) _geoObjects->addStationVec(stations, temp_name , color); + if (!stations->empty()) + _geoObjects->addStationVec(stations, temp_name, color); _db.close(); //emit listLoaded(listName); @@ -233,7 +269,9 @@ int DatabaseConnection::loadStationList(int listID, const GEOLIB::Color* const c } else { - std::cout << "DatabaseConnection::loadList() - No database entry found for the selected key." << std::endl; + std::cout << + "DatabaseConnection::loadList() - No database entry found for the selected key." + << std::endl; _db.close(); } } @@ -249,30 +287,40 @@ int DatabaseConnection::loadStationList(int listID, const GEOLIB::Color* const c * \param stations List of station objects for which stratigraphy data will be provided * \return 1 if there were no errors, 0 and an error message otherwise. */ -int DatabaseConnection::addStratigraphy(int listID, std::vector<GEOLIB::Point*> *stations) +int DatabaseConnection::addStratigraphy(int listID, std::vector<GEOLIB::Point*>* stations) { if (_db.open()) { QSqlQuery strat; size_t size = stations->size(); - for (size_t i=0; i<size; i++) + for (size_t i = 0; i < size; i++) { int count = 1; - GEOLIB::StationBorehole* newStation = static_cast<GEOLIB::StationBorehole*>((*stations)[i]); - strat.exec("select s.layerid, s.thickness, s.strat from stations t, stratigraphies s where s.listid=" + QString::number(listID) + " and s.listid=t.listid and s.stationid=t.stationid and t.name='" + QString::fromStdString(static_cast<GEOLIB::Station*>((*stations)[i])->getName()) + "' order by layerid"); + GEOLIB::StationBorehole* newStation = + static_cast<GEOLIB::StationBorehole*>((*stations)[i]); + strat.exec( + "select s.layerid, s.thickness, s.strat from stations t, stratigraphies s where s.listid=" + + QString::number( + listID) + + " and s.listid=t.listid and s.stationid=t.stationid and t.name='" + + QString::fromStdString(static_cast<GEOLIB::Station*>((*stations)[i]) + -> + getName()) + "' order by layerid"); while (strat.next()) { - if (count==strat.value(0)) - { - newStation->addSoilLayer (strat.value(1).toDouble(), (strat.value(2).toString()).toStdString()); + if (count == strat.value(0)) + newStation->addSoilLayer (strat.value(1).toDouble(), + (strat.value( + 2).toString()). + toStdString()); //newStation->type = Station::BOREHOLE; - } else - { - std::cout << "DatabaseConnection::addStratigraphy - Station " << static_cast<GEOLIB::Station*>((*stations)[i])->getName() << ": Stratigraphy incomplete...\n"; - } + std::cout << + "DatabaseConnection::addStratigraphy - Station " << + static_cast<GEOLIB::Station*>((*stations)[i])->getName() << + ": Stratigraphy incomplete...\n"; count++; } (*stations)[i] = newStation; @@ -299,8 +347,11 @@ int DatabaseConnection::getListID(const QString &list, const double &x, const do if (_db.open()) { QSqlQuery query; - query.exec("select l.listid from lists l, categories c, stations s where l.catid = c.catid and l.listid = s.listid and s.x=" - + QString::number(x,'f') + " and s.y=" + QString::number(y,'f') + " and c.catname='" + list.left(list.indexOf(" (")) + "'"); + query.exec( + "select l.listid from lists l, categories c, stations s where l.catid = c.catid and l.listid = s.listid and s.x=" + + QString::number(x,'f') + " and s.y=" + QString::number(y, + 'f') + + " and c.catname='" + list.left(list.indexOf(" (")) + "'"); if (query.next()) return query.value(0).toInt(); @@ -323,7 +374,10 @@ int DatabaseConnection::getStationID(const int &listID, const double &x, const d if (_db.open()) { QSqlQuery query; - query.exec("select stationid from stations where listid=" + QString::number(listID) + " and x=" + QString::number(x,'f') + " and y=" + QString::number(y,'f')); + query.exec("select stationid from stations where listid=" + QString::number( + listID) + " and x=" + QString::number(x, + 'f') + " and y=" + + QString::number(y,'f')); QString oldq = query.lastQuery(); if (query.next()) @@ -349,14 +403,14 @@ int DatabaseConnection::getListProperties(const int &listID, std::vector<QString if (_db.open()) { QSqlQuery query; - query.exec("select column_name,data_type from all_tab_cols where table_name =\'STATIONS\'"); + query.exec( + "select column_name,data_type from all_tab_cols where table_name =\'STATIONS\'"); while (query.next()) - { - if ((query.value(0).toString()).compare("LISTID") != 0 && (query.value(0).toString()).compare("STATIONID") != 0 && (query.value(1).toString()).compare("VARCHAR2") != 0) - { + if ((query.value(0).toString()).compare("LISTID") != 0 && + (query.value(0).toString()).compare("STATIONID") != 0 && + (query.value(1).toString()).compare("VARCHAR2") != 0) propNames.push_back(query.value(0).toString()); - } - } + return 1; } return 0; @@ -370,14 +424,19 @@ int DatabaseConnection::getListProperties(const int &listID, std::vector<QString * \param endDate The value of the last date for that station found in the database * \return 1 if there were no errors, 0 and an error message otherwise. */ -int DatabaseConnection::getDateBounds(const int &listID, const int &stationID, QString &startDate, QString &endDate) +int DatabaseConnection::getDateBounds(const int &listID, + const int &stationID, + QString &startDate, + QString &endDate) { startDate = ""; endDate = ""; if (_db.open()) { QSqlQuery query; - query.exec("select to_char(min(mdate), 'DD.MM.YYYY'), to_char(max(mdate), 'DD.MM.YYYY') from mvalues where listid=" + QString::number(listID) + " and stationID=" + QString::number(stationID)); + query.exec( + "select to_char(min(mdate), 'DD.MM.YYYY'), to_char(max(mdate), 'DD.MM.YYYY') from mvalues where listid=" + + QString::number(listID) + " and stationID=" + QString::number(stationID)); if (query.next()) { startDate = query.value(0).toString(); @@ -397,12 +456,18 @@ int DatabaseConnection::getDateBounds(const int &listID, const int &stationID, Q * \param max The largest value of that property found in the database * \return 1 if there were no errors, 0 and an error message otherwise. */ -int DatabaseConnection::getPropertyBounds(const int &listID, const QString &prop, double &min, double &max) +int DatabaseConnection::getPropertyBounds(const int &listID, + const QString &prop, + double &min, + double &max) { if (_db.open()) { QSqlQuery query; - query.exec("select min(" + prop + "), max(" + prop + ") from stations where listid=" + QString::number(listID)); + query.exec( + "select min(" + prop + "), max(" + prop + + ") from stations where listid=" + + QString::number(listID)); if (query.next()) { min = query.value(0).toDouble(); @@ -423,24 +488,30 @@ int DatabaseConnection::getPropertyBounds(const int &listID, const QString &prop * \param values The data * \return 1 if there were no errors, 0 and an error message otherwise. */ -int DatabaseConnection::loadValues(const int &listID, const int &stationID, const QDateTime &startDate, const QDateTime &endDate, std::vector< std::pair<QDateTime, float> > &values) +int DatabaseConnection::loadValues(const int &listID, + const int &stationID, + const QDateTime &startDate, + const QDateTime &endDate, + std::vector< std::pair<QDateTime, float> > &values) { - if (startDate<endDate && _db.open()) + if (startDate < endDate && _db.open()) { QSqlQuery query; - query.prepare("select to_char(mdate,'YYYY-MM-DD'),mvalue from mvalues where listid=:listID and stationid=:stationID " - "and mdate>=to_date(:startDate,'DD.MM.YYYY') and mdate<=to_date(:endDate,'DD.MM.YYYY') order by mdate"); - query.bindValue(":listID", listID); - query.bindValue(":stationID", stationID); - query.bindValue(":startDate", startDate.toString("dd.MM.yyyy")); - query.bindValue(":endDate", endDate.toString("dd.MM.yyyy")); + query.prepare( + "select to_char(mdate,'YYYY-MM-DD'),mvalue from mvalues where listid=:listID and stationid=:stationID " + "and mdate>=to_date(:startDate,'DD.MM.YYYY') and mdate<=to_date(:endDate,'DD.MM.YYYY') order by mdate"); + query.bindValue(":listID", listID); + query.bindValue(":stationID", stationID); + query.bindValue(":startDate", startDate.toString("dd.MM.yyyy")); + query.bindValue(":endDate", endDate.toString("dd.MM.yyyy")); query.exec(); while (query.next()) - { - values.push_back( std::pair<QDateTime, float>(query.value(0).toDateTime(), static_cast<float>(query.value(1).toDouble())) ); - } + values.push_back( std::pair<QDateTime, float>(query.value(0).toDateTime(), + static_cast<float>(query. + value(1). + toDouble())) ); _db.close(); return 1; @@ -450,21 +521,13 @@ int DatabaseConnection::loadValues(const int &listID, const int &stationID, cons return 0; } - - - - - - - /********************************************* - * Inserting data into the database. * - * Be very careful what you do with any of * - * functions below. * - * You might corrupt the database otherwise. * - * --KR * - *********************************************/ - +* Inserting data into the database. * +* Be very careful what you do with any of * +* functions below. * +* You might corrupt the database otherwise. * +* --KR * +*********************************************/ /** * Inserts a new station list into the database @@ -473,18 +536,22 @@ int DatabaseConnection::loadValues(const int &listID, const int &stationID, cons * \param catName the category of stations (i.e. boreholes) * \param type the OGS5 Stationtype */ -int DatabaseConnection::addListToDB(std::string path, std::string listName, std::string catName, GEOLIB::Station::StationType type) +int DatabaseConnection::addListToDB(std::string path, + std::string listName, + std::string catName, + GEOLIB::Station::StationType type) { if (_db.open()) { int listID, catID(0); - bool status=true, commit=true; + bool status = true, commit = true; std::ifstream in( path.c_str() ); if (!in.is_open()) { - std::cout << "DatabaseConnection::addListToDB() - Could not open file..." << std::endl; + std::cout << + "DatabaseConnection::addListToDB() - Could not open file..." << std::endl; return 0; } @@ -493,8 +560,8 @@ int DatabaseConnection::addListToDB(std::string path, std::string listName, std: */ std::string line; getline(in, line); - if ((line.substr(0,1)).compare("!")==0) - line.substr( 1, line.length()-1 ); + if ((line.substr(0,1)).compare("!") == 0) + line.substr( 1, line.length() - 1 ); QSqlQuery query; query.exec("select max(listid) from lists"); @@ -502,7 +569,9 @@ int DatabaseConnection::addListToDB(std::string path, std::string listName, std: { listID = query.value(0).toInt() + 1; - query.exec("select catid from categories where catname='" + QString::fromStdString(catName) + "'"); + query.exec( + "select catid from categories where catname='" + + QString::fromStdString(catName) + "'"); if (query.next()) catID = query.value(0).toInt(); @@ -511,32 +580,45 @@ int DatabaseConnection::addListToDB(std::string path, std::string listName, std: query.exec("select max(catid) from categories"); if (query.next()) catID = query.value(0).toInt() + 1; - query.prepare("insert into categories values (" + QString::number(catID) + ", '" + QString::fromStdString(catName) +"')"); + query.prepare("insert into categories values (" + + QString::number( + catID) + ", '" + QString::fromStdString( + catName) + "')"); commitTransaction(query); } _db.transaction(); - query.exec("insert into lists values(" + QString::number(listID) + ", '" + QString::fromStdString(listName) + "', " + QString::number(catID) + ", 0)"); - if (type == GEOLIB::Station::BOREHOLE) query.exec("insert into geosysstationtypes values (" + QString::number(listID) + ", 2)"); + query.exec("insert into lists values(" + QString::number( + listID) + ", '" + QString::fromStdString( + listName) + "', " + + QString::number(catID) + ", 0)"); + if (type == GEOLIB::Station::BOREHOLE) + query.exec( + "insert into geosysstationtypes values (" + QString::number( + listID) + ", 2)"); - int stationID=1; + int stationID = 1; /* read all stations */ while ( getline(in, line) ) { - if (type == GEOLIB::Station::BOREHOLE) status = addBoreholeToDB(listID, stationID, line); - else status = addStationToDB(listID, stationID, line); + if (type == GEOLIB::Station::BOREHOLE) + status = addBoreholeToDB(listID, stationID, line); + else + status = addStationToDB(listID, stationID, line); if (!status) { databaseError(); - commit=false; + commit = false; } stationID++; } - if (commit) _db.commit(); - else _db.rollback(); + if (commit) + _db.commit(); + else + _db.rollback(); _db.close(); in.close(); @@ -588,7 +670,8 @@ bool DatabaseConnection::addBoreholeToDB(int listID, int stationID, std::string if (addStationToDB(listID, stationID, line)) { - query.prepare("insert into boreholes values (:listid, :stationid, :bdepth, to_date(:bdate, 'DD.MM.YYYY'))"); + query.prepare( + "insert into boreholes values (:listid, :stationid, :bdepth, to_date(:bdate, 'DD.MM.YYYY'))"); query.bindValue(":listid", listID); query.bindValue(":stationid", stationID); query.bindValue(":bdepth", station->getDepth()); @@ -617,7 +700,8 @@ int DatabaseConnection::addStratigraphyToDB(std::string path, int listID) if (!in.is_open()) { - std::cout << "DatabaseConnection::addListToDB() - Could not open file..." << std::endl; + std::cout << + "DatabaseConnection::addListToDB() - Could not open file..." << std::endl; return 0; } @@ -626,7 +710,6 @@ int DatabaseConnection::addStratigraphyToDB(std::string path, int listID) { if (query.value(0).toInt() == 1) { - _db.transaction(); /* read all stations */ @@ -636,24 +719,37 @@ int DatabaseConnection::addStratigraphyToDB(std::string path, int listID) stationName = fields.front(); fields.pop_front(); - query.exec("select stationid from stations where listid=" + QString::number(listID) + " and name='" + QString::fromStdString(stationName) + "'" ); + query.exec( + "select stationid from stations where listid=" + + QString::number( + listID) + " and name='" + + QString::fromStdString( + stationName) + "'" ); if (query.next() && fields.size() >= 3) { stationID = query.value(0).toInt(); - query.prepare("insert into stratigraphies values (:listid, :stationid, :layerid, :thickness, :strat, :petro)"); + query.prepare( + "insert into stratigraphies values (:listid, :stationid, :layerid, :thickness, :strat, :petro)"); query.bindValue(":listid", listID); query.bindValue(":stationid", stationID); - query.bindValue(":layerid", atoi(fields.front().c_str())); + query.bindValue(":layerid", + atoi(fields.front().c_str())); fields.pop_front(); - query.bindValue(":thickness", strtod(replaceString(",", ".", fields.front()).c_str(),0)); + query.bindValue(":thickness", + strtod(replaceString(",", ".", + fields.front()) + .c_str(),0)); fields.pop_front(); - query.bindValue(":strat", QString::fromStdString(fields.front())); + query.bindValue(":strat", + QString::fromStdString(fields.front())); fields.pop_front(); if (!fields.empty()) - query.bindValue(":petro", QString::fromStdString(fields.front())); + query.bindValue(":petro", + QString::fromStdString( + fields.front())); else query.bindValue(":petro", ""); @@ -696,16 +792,18 @@ int DatabaseConnection::addMeasuredValuesToDB(std::string path, int listID, int if (!in.is_open()) { - std::cout << "DatabaseConnection::addMeasuredValuesToDB() - Could not open file..." << std::endl; + std::cout << + "DatabaseConnection::addMeasuredValuesToDB() - Could not open file..." << + std::endl; return 0; } - query.exec("select count(*) from stations where listid=" + QString::number(listID) + " and stationid=" + QString::number(stationID)); + query.exec("select count(*) from stations where listid=" + QString::number( + listID) + " and stationid=" + QString::number(stationID)); if (query.next()) { if (query.value(0).toInt() == 1) { - _db.transaction(); while ( getline(in, line) ) @@ -714,12 +812,17 @@ int DatabaseConnection::addMeasuredValuesToDB(std::string path, int listID, int QString a = query.lastQuery(); - query.prepare("insert into mvalues values (:listid, :stationid, to_date(:mdatetime,'DD.MM.YYYY'), :mvalue)"); + query.prepare( + "insert into mvalues values (:listid, :stationid, to_date(:mdatetime,'DD.MM.YYYY'), :mvalue)"); query.bindValue(":listid", listID); query.bindValue(":stationid", stationID); - query.bindValue(":mdatetime", QString::fromStdString(fields.front())); + query.bindValue(":mdatetime", + QString::fromStdString(fields.front())); fields.pop_front(); - query.bindValue(":mvalue", strtod(replaceString(",", ".", fields.front()).c_str(),0)); + query.bindValue(":mvalue", + strtod(replaceString(",", ".", + fields.front()).c_str(), + 0)); fields.pop_front(); query.exec(); } @@ -741,8 +844,6 @@ int DatabaseConnection::addMeasuredValuesToDB(std::string path, int listID, int return 0; } - - /** * Executing a query as an encapsulated transaction * \return True if everything is alright, false if there were errors. diff --git a/DataView/DatabaseConnection.h b/DataView/DatabaseConnection.h index 418ff0f9b7c6b4a213a4c2650a143c15653a0247..4ca9409e70b3ace13d045856cb18065e8f687a99 100644 --- a/DataView/DatabaseConnection.h +++ b/DataView/DatabaseConnection.h @@ -6,13 +6,12 @@ #ifndef DATABASECONNECTION_H #define DATABASECONNECTION_H -#include <string> -#include <QObject> -#include <QSqlDatabase> -#include <QDateTime> #include "GEOObjects.h" #include "Station.h" - +#include <QDateTime> +#include <QObject> +#include <QSqlDatabase> +#include <string> /** * \brief Management of a database connection including the actual connection process, error handling and relevant queries. @@ -27,7 +26,10 @@ public: int dbConnect(); - int getDateBounds(const int &listID, const int &stationID, QString &startDate, QString &endDate); + int getDateBounds(const int &listID, + const int &stationID, + QString &startDate, + QString &endDate); int getListID(const QString &list, const double &x, const double &y); int getListProperties(const int &listID, std::vector<QString> &propNames); int getPropertyBounds(const int &listID, const QString &prop, double &min, double &max); @@ -35,22 +37,36 @@ public: void getListSelection(); bool isConnected(); int loadStationList(int listID, const GEOLIB::Color* const color); - int loadValues(const int &listID, const int &stationID, const QDateTime &startDate, const QDateTime &endDate, std::vector< std::pair<QDateTime, float> > &values); + int loadValues(const int &listID, + const int &stationID, + const QDateTime &startDate, + const QDateTime &endDate, + std::vector< std::pair<QDateTime, float> > &values); int test(bool showBox); public slots: - int dbConnect(QString protocol, QString hostname, QString dbname, QString user, QString pass); + int dbConnect(QString protocol, + QString hostname, + QString dbname, + QString user, + QString pass); int loadStationList(const int &listID); - int setConnection(QString protocol, QString hostname, QString dbname, QString user, QString pass); - + int setConnection(QString protocol, + QString hostname, + QString dbname, + QString user, + QString pass); private: void databaseError(); - int addStratigraphy(int listID, std::vector<GEOLIB::Point*> *stations); + int addStratigraphy(int listID, std::vector<GEOLIB::Point*>* stations); bool commitTransaction(QSqlQuery query); //data-insert functions -- be careful! - int addListToDB(std::string path, std::string listName, std::string catName, GEOLIB::Station::StationType type); + int addListToDB(std::string path, + std::string listName, + std::string catName, + GEOLIB::Station::StationType type); bool addStationToDB(int listID, int stationID, std::string line); bool addBoreholeToDB(int listID, int stationID, std::string line); int addStratigraphyToDB(std::string path, int listID); diff --git a/DataView/DiagramView/DetailWindow.cpp b/DataView/DiagramView/DetailWindow.cpp index dfd41f48c36c8d82ee4f4456fd138450f83f0735..d2df79f29247ebdbff72260003f193fa105c9b67 100644 --- a/DataView/DiagramView/DetailWindow.cpp +++ b/DataView/DiagramView/DetailWindow.cpp @@ -3,8 +3,8 @@ * KR Initial implementation */ -#include "DetailWindow.h" #include "Color.h" +#include "DetailWindow.h" #include "DiagramPrefsDialog.h" #include <QFileDialog> @@ -16,47 +16,46 @@ DetailWindow::DetailWindow(QWidget* parent) : QWidget(parent) stationView->setRenderHints( QPainter::Antialiasing ); /* - DiagramList* list = new DiagramList(); - DiagramList* list2 = new DiagramList(); - - - // ================================================== - // input files should be defined in WaterML - // inserting the details below into the list-objects - // kind of simulates the information that would be - // included in a WaterML-file and is needed for - // display - // ================================================== - - // make up list-object for the first test station - list->setName("Water Level Observation Station: Halberstadt 2002"); - list->setXLabel("Time"); - list->setYLabel("Water Level"); - list->setXUnit("day"); - list->setYUnit("metres"); - list->setColor(QColor(Qt::red)); - list->readList("c:\\project\\timeseries-a.stn"); - - // make up list-object for the second test station - list2->setName("Water Level Observation Station: Oschersleben 2002"); - list2->setXLabel("Time"); - list2->setYLabel("Water Level"); - list2->setXUnit("day"); - list2->setYUnit("metres"); - list2->setColor(QColor(Qt::green)); - list2->readList("c:\\project\\timeseries-b.stn"); - - // ================================================== - - - stationView->addGraph(list); - stationView->addGraph(list2); - - resizeWindow(); - */ + DiagramList* list = new DiagramList(); + DiagramList* list2 = new DiagramList(); + + + // ================================================== + // input files should be defined in WaterML + // inserting the details below into the list-objects + // kind of simulates the information that would be + // included in a WaterML-file and is needed for + // display + // ================================================== + + // make up list-object for the first test station + list->setName("Water Level Observation Station: Halberstadt 2002"); + list->setXLabel("Time"); + list->setYLabel("Water Level"); + list->setXUnit("day"); + list->setYUnit("metres"); + list->setColor(QColor(Qt::red)); + list->readList("c:\\project\\timeseries-a.stn"); + + // make up list-object for the second test station + list2->setName("Water Level Observation Station: Oschersleben 2002"); + list2->setXLabel("Time"); + list2->setYLabel("Water Level"); + list2->setXUnit("day"); + list2->setYUnit("metres"); + list2->setColor(QColor(Qt::green)); + list2->readList("c:\\project\\timeseries-b.stn"); + + // ================================================== + + + stationView->addGraph(list); + stationView->addGraph(list2); + + resizeWindow(); + */ } - DetailWindow::DetailWindow(QString filename, QWidget* parent) : QWidget(parent) { setupUi(this); @@ -65,7 +64,7 @@ DetailWindow::DetailWindow(QString filename, QWidget* parent) : QWidget(parent) std::vector<DiagramList*> lists; DiagramList::readList(filename, lists); - for (size_t i=0; i<lists.size(); i++) + for (size_t i = 0; i < lists.size(); i++) stationView->addGraph(lists[i]); resizeWindow(); @@ -88,16 +87,15 @@ void DetailWindow::on_closeButton_clicked() this->close(); } - void DetailWindow::resizeWindow() { - int width = (stationView->getWidth()>800) ? 800 : stationView->getWidth(); - int height = (stationView->getHeight()>600) ? 600 : stationView->getHeight(); + int width = (stationView->getWidth() > 800) ? 800 : stationView->getWidth(); + int height = (stationView->getHeight() > 600) ? 600 : stationView->getHeight(); resize(width, height); } -void DetailWindow::addList(DiagramList* list) -{ +void DetailWindow::addList(DiagramList* list) +{ GEOLIB::Color* c = GEOLIB::getRandomColor(); QColor colour((*c)[0], (*c)[1], (*c)[2]); delete c; @@ -105,19 +103,21 @@ void DetailWindow::addList(DiagramList* list) resizeWindow(); } -void DetailWindow::addList(DiagramList* list, QColor c) -{ +void DetailWindow::addList(DiagramList* list, QColor c) +{ list->setColor(c); - this->stationView->addGraph(list); + this->stationView->addGraph(list); } void DetailWindow::on_addDataButton_clicked() { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName( this, "Select data file to open", - settings.value("lastOpenedFileDirectory").toString(), - "Text files (*.txt);;All files (* *.*)"); - if (!fileName.isEmpty()) + settings.value( + "lastOpenedFileDirectory"). + toString(), + "Text files (*.txt);;All files (* *.*)"); + if (!fileName.isEmpty()) { QDir dir = QDir(fileName); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); diff --git a/DataView/DiagramView/DetailWindow.h b/DataView/DiagramView/DetailWindow.h index 7b2bbf63e071ec096a2b948807693c2b7ba47f3a..653541fe7aae052bc2c1141beb0ca5d0d19f8336 100644 --- a/DataView/DiagramView/DetailWindow.h +++ b/DataView/DiagramView/DetailWindow.h @@ -6,9 +6,8 @@ #ifndef DETAILWINDOW_H #define DETAILWINDOW_H -#include <QtGui/QWidget> #include "ui_DetailWindow.h" - +#include <QtGui/QWidget> /** * \brief Creates a window containing a diagram. diff --git a/DataView/DiagramView/DiagramList.cpp b/DataView/DiagramView/DiagramList.cpp index 7485391581126849fc0511b5408f8fa6cde55f43..9a6edd1ce2df8a86f103c62850ed9bf5f992c6ca 100644 --- a/DataView/DiagramView/DiagramList.cpp +++ b/DataView/DiagramView/DiagramList.cpp @@ -3,14 +3,14 @@ * KR Initial implementation */ -#include <limits> -#include <QFile> -#include <QTextStream> #include "DiagramList.h" #include "StringTools.h" +#include <QFile> +#include <QTextStream> +#include <limits> - -DiagramList::DiagramList() : _maxX(0), _maxY(0), _minX(0), _minY(0), _xLabel(""), _yLabel(""), _xUnit(""), _yUnit(""), _startDate() +DiagramList::DiagramList() : _maxX(0), _maxY(0), _minX(0), _minY(0), _xLabel(""), _yLabel(""), + _xUnit(""), _yUnit(""), _startDate() { } @@ -22,10 +22,9 @@ float DiagramList::calcMinXValue() { float min = std::numeric_limits<float>::max(); size_t nCoords = _coords.size(); - for (size_t i=0; i<nCoords; i++) - { - if (_coords[i].first<min) min=_coords[i].first; - } + for (size_t i = 0; i < nCoords; i++) + if (_coords[i].first < min) + min = _coords[i].first; return min; } @@ -33,10 +32,9 @@ float DiagramList::calcMaxXValue() { float max = std::numeric_limits<float>::min(); size_t nCoords = _coords.size(); - for (size_t i=0; i<nCoords; i++) - { - if (_coords[i].first>max) max=_coords[i].first; - } + for (size_t i = 0; i < nCoords; i++) + if (_coords[i].first > max) + max = _coords[i].first; return max; } @@ -44,10 +42,9 @@ float DiagramList::calcMinYValue() { float min = std::numeric_limits<float>::max(); size_t nCoords = _coords.size(); - for (size_t i=0; i<nCoords; i++) - { - if (_coords[i].second<min) min=_coords[i].second; - } + for (size_t i = 0; i < nCoords; i++) + if (_coords[i].second < min) + min = _coords[i].second; return min; } @@ -55,10 +52,9 @@ float DiagramList::calcMaxYValue() { float max = std::numeric_limits<float>::min(); size_t nCoords = _coords.size(); - for (size_t i=0; i<nCoords; i++) - { - if (_coords[i].second>max) max=_coords[i].second; - } + for (size_t i = 0; i < nCoords; i++) + if (_coords[i].second > max) + max = _coords[i].second; return max; } @@ -67,14 +63,14 @@ bool DiagramList::getPath(QPainterPath &path, float scaleX, float scaleY) QPointF p; if (getPoint(p,0)) { - QPainterPath pp(QPointF(p.x()*scaleX, p.y()*scaleY)); + QPainterPath pp(QPointF(p.x() * scaleX, p.y() * scaleY)); path = pp; size_t nCoords = _coords.size(); - for (size_t i=1; i<nCoords; i++) + for (size_t i = 1; i < nCoords; i++) { getPoint(p,i); - path.lineTo(QPointF(p.x()*scaleX, p.y()*scaleY)); + path.lineTo(QPointF(p.x() * scaleX, p.y() * scaleY)); } return true; } @@ -84,16 +80,16 @@ bool DiagramList::getPath(QPainterPath &path, float scaleX, float scaleY) bool DiagramList::getPoint(QPointF &p, size_t i) { - if (i<_coords.size()) + if (i < _coords.size()) { p.setX(_coords[i].first); p.setY(_coords[i].second); return true; } - else return false; + else + return false; } - /* * Reads an external list into the coordinate arrays. * This method uses files containing the following format: @@ -101,38 +97,38 @@ bool DiagramList::getPoint(QPointF &p, size_t i) * Both values may be int or double. */ /* -int DiagramList::readList(char* path) -{ - int date; - double xVal, yVal; - QString line; - QStringList fields; + int DiagramList::readList(char* path) + { + int date; + double xVal, yVal; + QString line; + QStringList fields; - QFile file(path); - QTextStream in( &file ); + QFile file(path); + QTextStream in( &file ); - if (!file.open(QIODevice::ReadOnly)) + if (!file.open(QIODevice::ReadOnly)) { - return 0; - } - - while (!in.atEnd()) { - line = in.readLine(); - fields = line.split('\t'); - if (fields.size() >= 2) { - xVal = fields.takeFirst().toDouble(); - yVal = fields.takeFirst().toDouble(); - xCoords.push_back(xVal); - yCoords.push_back(yVal); - } - else return 0; - } + return 0; + } + + while (!in.atEnd()) { + line = in.readLine(); + fields = line.split('\t'); + if (fields.size() >= 2) { + xVal = fields.takeFirst().toDouble(); + yVal = fields.takeFirst().toDouble(); + xCoords.push_back(xVal); + yCoords.push_back(yVal); + } + else return 0; + } file.close(); - update(); + update(); return 1; -}*/ + }*/ int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) { @@ -140,19 +136,19 @@ int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) QTextStream in( &file ); if (!file.open(QIODevice::ReadOnly)) - { + { qDebug("Could not open file..."); return 0; } QString line = in.readLine(); QStringList fields = line.split('\t'); - int nLists(fields.size()-1); - - if (fields.size() >= 2) + int nLists(fields.size() - 1); + + if (fields.size() >= 2) { fields.takeFirst(); - for (int i=0; i<nLists; i++) + for (int i = 0; i < nLists; i++) { DiagramList* l = new DiagramList; l->setName(fields.takeFirst()); @@ -161,36 +157,41 @@ int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) //l->addNextPoint(0,value); lists.push_back(l); } - + bool first_loop(true); int numberOfSecs(0); double value(0); QString stringDate(""); QDateTime startDate, currentDate; - while (!in.atEnd()) { - + while (!in.atEnd()) + { line = in.readLine(); fields = line.split('\t'); - if (fields.size() >= (nLists+1)) { + if (fields.size() >= (nLists + 1)) + { stringDate = fields.takeFirst(); currentDate = getDateTime(stringDate); if (first_loop) { startDate = currentDate; - for (int i=0; i<nLists; i++) lists[i]->setStartDate(startDate); + for (int i = 0; i < nLists; i++) + lists[i]->setStartDate(startDate); first_loop = false; } numberOfSecs = startDate.secsTo(currentDate); - for (int i=0; i<nLists; i++) + for (int i = 0; i < nLists; i++) { - value = strtod(replaceString(",", ".", fields.takeFirst().toStdString()).c_str(),0); + value = + strtod(replaceString(",", ".", + fields.takeFirst().toStdString( + )).c_str(),0); lists[i]->addNextPoint(numberOfSecs,value); } } - else + else { qDebug("Unexpected file format..."); file.close(); @@ -206,11 +207,11 @@ int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) } file.close(); - - for (int i=0; i<nLists; i++) + + for (int i = 0; i < nLists; i++) lists[i]->update(); - - return nLists; + + return nLists; } void DiagramList::setList(std::vector< std::pair<QDateTime, float> > coords) @@ -222,7 +223,7 @@ void DiagramList::setList(std::vector< std::pair<QDateTime, float> > coords) _coords.push_back(std::pair<float, float>(0, coords[0].second)); size_t nCoords = coords.size(); - for (size_t i=1; i<nCoords; i++) + for (size_t i = 1; i < nCoords; i++) { numberOfDays = startDate.daysTo(coords[i].first); _coords.push_back(std::pair<float, float>(numberOfDays, coords[i].second)); @@ -234,7 +235,7 @@ void DiagramList::setList(std::vector< std::pair<QDateTime, float> > coords) void DiagramList::setList(std::vector< std::pair<float, float> > coords) { size_t nCoords = coords.size(); - for (size_t i=0; i<nCoords; i++) + for (size_t i = 0; i < nCoords; i++) _coords.push_back(coords[i]); update(); @@ -244,7 +245,8 @@ size_t DiagramList::size() { if (!(_coords.empty())) return _coords.size(); - else return 0; + else + return 0; } void DiagramList::update() @@ -257,8 +259,8 @@ void DiagramList::update() QDateTime DiagramList::getDateTime(QString stringDate) { - if (stringDate.length() <=10) + if (stringDate.length() <= 10) return QDateTime::fromString(stringDate, "dd.MM.yyyy"); - else + else return QDateTime::fromString(stringDate, "dd.MM.yyyy.HH.mm.ss"); } diff --git a/DataView/DiagramView/DiagramList.h b/DataView/DiagramView/DiagramList.h index 40b7b9642703124dec71e3b0a8d6cf52edfe7353..3bec7989b3c1c2f98011806354c31483cd3be003 100644 --- a/DataView/DiagramView/DiagramList.h +++ b/DataView/DiagramView/DiagramList.h @@ -6,12 +6,11 @@ #ifndef DIAGRAMLIST_H #define DIAGRAMLIST_H -#include <vector> -#include <QPoint> -#include <QPainterPath> #include <QColor> #include <QDateTime> - +#include <QPainterPath> +#include <QPoint> +#include <vector> /** * \brief A List of data points and all the necessary meta-information to draw a graph. @@ -24,10 +23,10 @@ public: ~DiagramList(); /// Returns the colour of the graph. - QColor getColor() const { return _colour; } + QColor getColor() const { return _colour; } /// Returns the height of the bounding box of all data points within the list. - float height() const { return (_maxY-_minY); } + float height() const { return _maxY - _minY; } /// Returns the minimum x-value. float minXValue() const { return _minX; } @@ -42,10 +41,10 @@ public: float maxYValue() const { return _maxY; } /// Returns the start date of this list - const QDateTime getStartDate() const { return _startDate; }; + const QDateTime getStartDate() const { return _startDate; } /// Returns the name of the diagram. - QString getName() const { return _name; }; + QString getName() const { return _name; } /** * Returns all the data points in form of a QPainterPath in scene coordinates. @@ -77,7 +76,7 @@ public: /// Returns the unit associated with the y-axis QString getYUnit() const { return _yUnit; } - /** + /** * Reads information from a file. The reader assumes that values in the file are seperated * by tabstops. Also, the first row should contain identifiers for the values and the first * column should contain timestamps. Currently accepted timestamps are of the following @@ -114,7 +113,7 @@ public: /** * Sets the list of x/y-coordinates. - * Note: This function converts QDateTime values to float values of the number of + * Note: This function converts QDateTime values to float values of the number of * days from the first date (which is set as day 0) * \param coords List of coordinates. */ @@ -130,7 +129,7 @@ public: size_t size(); /// Returns the width of the bounding box of all data points within the list. - double width() const { return _maxX-_minX; } + double width() const { return _maxX - _minX; } private: /// Returns the minimum x-value of all the data points. @@ -143,7 +142,7 @@ private: float calcMinYValue(); /// Returns the maximum y-value of all the data points. - float calcMaxYValue(); + float calcMaxYValue(); static QDateTime getDateTime(QString s); @@ -169,9 +168,8 @@ private: QString _yLabel; QString _xUnit; QString _yUnit; - QColor _colour; + QColor _colour; QDateTime _startDate; - }; #endif //DIAGRAMLIST_H diff --git a/DataView/DiagramView/DiagramPrefsDialog.cpp b/DataView/DiagramView/DiagramPrefsDialog.cpp index fc29389ff01b3f84c95b31634310c6952248ed59..2d0f7ea820f32534655890023ec0994da1cef34b 100644 --- a/DataView/DiagramView/DiagramPrefsDialog.cpp +++ b/DataView/DiagramView/DiagramPrefsDialog.cpp @@ -3,10 +3,10 @@ * KR Initial implementation */ -#include "DiagramPrefsDialog.h" #include "DatabaseConnection.h" #include "DetailWindow.h" #include "DiagramList.h" +#include "DiagramPrefsDialog.h" #include "OGSError.h" #include "Station.h" @@ -14,13 +14,16 @@ #include <QFileDialog> #include <QMessageBox> - -DiagramPrefsDialog::DiagramPrefsDialog(GEOLIB::Station* stn, QString listName, DatabaseConnection* db, QDialog* parent) -: QDialog(parent) +DiagramPrefsDialog::DiagramPrefsDialog(GEOLIB::Station* stn, + QString listName, + DatabaseConnection* db, + QDialog* parent) + : QDialog(parent) { setAttribute(Qt::WA_DeleteOnClose); - _listID = -1; _stationID = -1; + _listID = -1; + _stationID = -1; setupUi(this); stationNameLabel->setText(QString::fromStdString(stn->getName())); stationTypeLabel->setText(listName); @@ -42,8 +45,10 @@ DiagramPrefsDialog::DiagramPrefsDialog(GEOLIB::Station* stn, QString listName, D } } -DiagramPrefsDialog::DiagramPrefsDialog(const QString &filename, DetailWindow* window, QDialog* parent) -: QDialog(parent), _window(window) +DiagramPrefsDialog::DiagramPrefsDialog(const QString &filename, + DetailWindow* window, + QDialog* parent) + : QDialog(parent), _window(window) { QFileInfo fi(filename); setupUi(this); @@ -59,21 +64,26 @@ DiagramPrefsDialog::~DiagramPrefsDialog() void DiagramPrefsDialog::accept() { - if ((fromDateLine->text().length()>0) && (toDateLine->text().length()>0) && (!_list.empty())) + if ((fromDateLine->text().length() > 0) && (toDateLine->text().length() > 0) && + (!_list.empty())) { - if (_list[0]->size() == 0) // data will be read from the database (if data has been loaded from file, size is already >0) - { + if (_list[0]->size() == 0) // data will be read from the database (if data has been loaded from file, size is already >0) + if (_listID > 0 && _stationID > 0) { std::vector< std::pair<QDateTime, float> > values; - _db->loadValues(_listID, _stationID, QDateTime::fromString(fromDateLine->text(), "dd.MM.yyyy"), QDateTime::fromString(toDateLine->text(), "dd.MM.yyyy"), values); + _db->loadValues(_listID, _stationID, + QDateTime::fromString( + fromDateLine->text(), + "dd.MM.yyyy"), + QDateTime::fromString(toDateLine->text(), + "dd.MM.yyyy"), values); if (!loadList(values)) OGSError::box("No data found."); } - } - + // data has been loaded - if (_list[0]->size()>0) + if (_list[0]->size() > 0) { bool window_is_empty(false); if (_window == NULL) @@ -82,16 +92,13 @@ void DiagramPrefsDialog::accept() _window->setAttribute(Qt::WA_DeleteOnClose); window_is_empty = true; } - - - for (size_t i=0; i<_list.size(); i++) - { + + for (size_t i = 0; i < _list.size(); i++) if (this->_visability[i]->isChecked()) { _window->addList(_list[i]); window_is_empty = false; } - } if (!window_is_empty) { @@ -105,7 +112,7 @@ void DiagramPrefsDialog::accept() OGSError::box("No dataset selected."); } } - else + else { OGSError::box("Invalid station data."); this->done(QDialog::Rejected); @@ -122,7 +129,10 @@ void DiagramPrefsDialog::reject() void DiagramPrefsDialog::on_loadFileButton_clicked() { - QString fileName = QFileDialog::getOpenFileName(this, "Select time series file to open", "","Time series files (*.stn *.txt)"); + QString fileName = QFileDialog::getOpenFileName(this, + "Select time series file to open", + "", + "Time series files (*.stn *.txt)"); if (!fileName.isEmpty()) loadFile(fileName); } @@ -131,7 +141,7 @@ int DiagramPrefsDialog::loadFile(const QString &filename) { if (DiagramList::readList(filename, _list)) { - for (size_t i=0; i<_list.size(); i++) + for (size_t i = 0; i < _list.size(); i++) { //_list[i]->setName(stationTypeLabel->text() + ": " + stationNameLabel->text()); _list[i]->setXLabel("Time"); @@ -140,9 +150,10 @@ int DiagramPrefsDialog::loadFile(const QString &filename) //_list[i]->setYUnit("metres"); _list[i]->setColor(QColor(Qt::red)); } - fromDateLine->setText(_list[0]->getStartDate().toString("dd.MM.yyyy"));//QString::number(_list[0]->minXValue())); - QDateTime endDate = _list[0]->getStartDate().addSecs(static_cast<int>(_list[0]->maxXValue())); - toDateLine->setText(endDate.toString("dd.MM.yyyy"));//QString::number(_list[0]->maxXValue())); + fromDateLine->setText(_list[0]->getStartDate().toString("dd.MM.yyyy")); //QString::number(_list[0]->minXValue())); + QDateTime endDate = + _list[0]->getStartDate().addSecs(static_cast<int>(_list[0]->maxXValue())); + toDateLine->setText(endDate.toString("dd.MM.yyyy")); //QString::number(_list[0]->maxXValue())); this->createVisibilityCheckboxes(); return 1; } @@ -171,7 +182,7 @@ int DiagramPrefsDialog::loadList(const std::vector< std::pair<QDateTime, float> void DiagramPrefsDialog::createVisibilityCheckboxes() { - for (size_t i=0; i<_list.size(); i++) + for (size_t i = 0; i < _list.size(); i++) { QCheckBox* box = new QCheckBox(_list[i]->getName()); box->setChecked(true); diff --git a/DataView/DiagramView/DiagramPrefsDialog.h b/DataView/DiagramView/DiagramPrefsDialog.h index 0827f010d23f70a0e98e93134c50ef15e4bba606..7ae6a16eda7c634b3b8519ac5bb1efcddc6b2b2e 100644 --- a/DataView/DiagramView/DiagramPrefsDialog.h +++ b/DataView/DiagramView/DiagramPrefsDialog.h @@ -6,16 +6,17 @@ #ifndef DIAGRAMPREFSDIALOG_H #define DIAGRAMPREFSDIALOG_H -#include <QtGui/QMainWindow> #include "ui_DiagramPrefs.h" +#include <QtGui/QMainWindow> class DatabaseConnection; class DetailWindow; class DiagramList; class QCheckBox; -namespace GEOLIB { - class Station; +namespace GEOLIB +{ +class Station; } /** @@ -40,7 +41,10 @@ public: * \param db The database connection were the diagram-related data can be found * \param parent The parent QDialog. */ - DiagramPrefsDialog(GEOLIB::Station* stn, QString listName, DatabaseConnection* db, QDialog* parent = 0); + DiagramPrefsDialog(GEOLIB::Station* stn, + QString listName, + DatabaseConnection* db, + QDialog* parent = 0); /** * Opens a new dialog and automatically reads data from the specified file. The diagram is not associated @@ -48,11 +52,12 @@ public: * \param filename File containing data for the diagram(s) to be visualised. * \param parent The parent QDialog. */ - DiagramPrefsDialog(const QString &filename, DetailWindow* window = NULL, QDialog* parent = 0); + DiagramPrefsDialog(const QString &filename, + DetailWindow* window = NULL, + QDialog* parent = 0); ~DiagramPrefsDialog(void); - private: /** * Creates checkboxes for every list of data values found. Per default all of these are checked, i.e. all @@ -82,7 +87,6 @@ private: int _stationID; DetailWindow* _window; - private slots: /// Instructions if the OK-Button has been pressed. /// Note: Clicking the "Load from file"-button overrides the database input! @@ -90,13 +94,11 @@ private slots: /// Instructions if the Cancel-Button has been pressed. void reject(); - + /// Instructions if the "Load File"-Button has been pressed. void on_loadFileButton_clicked(); signals: - - }; #endif //DIAGRAMPREFSDIALOG_H diff --git a/DataView/DiagramView/DiagramScene.cpp b/DataView/DiagramView/DiagramScene.cpp index 3179554612a0f01129ede838be454c95f33b7f37..16765ad473cc0c6bac2081d76b0be05658d51e3a 100644 --- a/DataView/DiagramView/DiagramScene.cpp +++ b/DataView/DiagramView/DiagramScene.cpp @@ -3,9 +3,9 @@ * KR Initial implementation */ +#include "DiagramScene.h" #include <limits> #include <math.h> -#include "DiagramScene.h" // default size of a new window const float DEFAULTX = 500.0; @@ -41,15 +41,20 @@ DiagramScene::~DiagramScene() delete _yLabel; delete _xUnit; delete _yUnit; - for (int i=0; i<_graphCaptions.size(); i++) delete _graphCaptions[i]; + for (int i = 0; i < _graphCaptions.size(); i++) + delete _graphCaptions[i]; _graphCaptions.clear(); - for (int i=0; i<_graphs.size(); i++) delete _graphs[i]; + for (int i = 0; i < _graphs.size(); i++) + delete _graphs[i]; _graphs.clear(); - for (int i=0; i<_xTicksText.size(); i++) delete _xTicksText[i]; + for (int i = 0; i < _xTicksText.size(); i++) + delete _xTicksText[i]; _xTicksText.clear(); - for (int i=0; i<_yTicksText.size(); i++) delete _yTicksText[i]; + for (int i = 0; i < _yTicksText.size(); i++) + delete _yTicksText[i]; _yTicksText.clear(); - for (int i=0; i<_lists.size(); i++) delete _lists[i]; + for (int i = 0; i < _lists.size(); i++) + delete _lists[i]; _lists.clear(); } @@ -61,7 +66,6 @@ QArrow* DiagramScene::addArrow(float length, float angle, QPen &pen) return arrow; } - /// Adds a caption for a graph beneath the actual diagram. void DiagramScene::addCaption(const QString &name, QPen &pen) { @@ -69,16 +73,16 @@ void DiagramScene::addCaption(const QString &name, QPen &pen) QGraphicsLineItem* l = addLine(0,0,100,0,pen); QGraphicsTextItem* t = addText(name); l->setPos(0,0); - t->setPos(110, -(t->boundingRect()).height()/2); + t->setPos(110, -(t->boundingRect()).height() / 2); caption->addToGroup(l); caption->addToGroup(t); caption->setFlag(QGraphicsItem::ItemIgnoresTransformations, true); _graphCaptions.push_back(caption); - addItem(_graphCaptions[_graphCaptions.size()-1]); + addItem(_graphCaptions[_graphCaptions.size() - 1]); } - /// Adds a graph to the scene, including all data points and meta-information. +/// Adds a graph to the scene, including all data points and meta-information. void DiagramScene::addGraph(DiagramList* list) { setDiagramBoundaries(list); @@ -92,7 +96,7 @@ void DiagramScene::addGraph(DiagramList* list) constructGrid(); _lists.push_back(list); - for (int i=0; i<_lists.size(); i++) + for (int i = 0; i < _lists.size(); i++) drawGraph(_lists[i]); update(); @@ -107,33 +111,32 @@ QGraphicsGrid* DiagramScene::addGrid(const QRectF &rect, int xTicks, int yTicks, } /// Adds a non-scalable text object to the scene -QNonScalableGraphicsTextItem* DiagramScene::addNonScalableText(const QString &text, const QFont &font) +QNonScalableGraphicsTextItem* DiagramScene::addNonScalableText(const QString &text, + const QFont &font) { - QNonScalableGraphicsTextItem *item = new QNonScalableGraphicsTextItem(text); - item->setFont(font); - addItem(item); - return item; + QNonScalableGraphicsTextItem* item = new QNonScalableGraphicsTextItem(text); + item->setFont(font); + addItem(item); + return item; } - /// Resizes a given axis to "nice" dimensions and calculates an adequate number of ticks to be placed on it void DiagramScene::adjustAxis(float &min, float &max, int &numberOfTicks) { - const int MinTicks = 4; - double grossStep = (max - min) / MinTicks; - double step = pow(10.0, floor(log10(grossStep))); - if (5 * step < grossStep) { - step *= 5; - } else if (2 * step < grossStep) { - step *= 2; - } - numberOfTicks = int(ceil(max / step) - floor(min / step)); - if (numberOfTicks < MinTicks) numberOfTicks = MinTicks; - min = floor(min / step) * step; - max = ceil(max / step) * step; + const int MinTicks = 4; + double grossStep = (max - min) / MinTicks; + double step = pow(10.0, floor(log10(grossStep))); + if (5 * step < grossStep) + step *= 5; + else if (2 * step < grossStep) + step *= 2; + numberOfTicks = int(ceil(max / step) - floor(min / step)); + if (numberOfTicks < MinTicks) + numberOfTicks = MinTicks; + min = floor(min / step) * step; + max = ceil(max / step) * step; } - ///Calculates scaling factors to set coordinate system and graphs to default window size void DiagramScene::adjustScaling() { @@ -147,13 +150,18 @@ void DiagramScene::adjustScaling() /// Destroys the grid object (coordinate system) when a new graph is added. void DiagramScene::clearGrid() { - if (!_lists.isEmpty()) { + if (!_lists.isEmpty()) + { removeItem(_grid); - for (int i = 0; i < _xTicksText.size(); ++i) removeItem(_xTicksText[i]); - for (int j = 0; j < _yTicksText.size(); ++j) removeItem(_yTicksText[j]); - for (int k = 0; k < _graphs.size(); k++) removeItem(_graphs[k]); - for (int l = 0; l < _graphCaptions.size(); l++) removeItem(_graphCaptions[l]); + for (int i = 0; i < _xTicksText.size(); ++i) + removeItem(_xTicksText[i]); + for (int j = 0; j < _yTicksText.size(); ++j) + removeItem(_yTicksText[j]); + for (int k = 0; k < _graphs.size(); k++) + removeItem(_graphs[k]); + for (int l = 0; l < _graphCaptions.size(); l++) + removeItem(_graphCaptions[l]); _xTicksText.clear(); _yTicksText.clear(); @@ -176,27 +184,33 @@ void DiagramScene::constructGrid() adjustAxis(yMin, yMax, numYTicks); // adjust boundaries of coordinate system according to scaling - _bounds.setRect( xMin*_scaleX, - yMin*_scaleY, - (xMax-xMin)*_scaleX, - (yMax-yMin)*_scaleY - ); + _bounds.setRect( xMin * _scaleX, + yMin * _scaleY, + (xMax - xMin) * _scaleX, + (yMax - yMin) * _scaleY + ); QPen pen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin); _grid = addGrid(_bounds, numXTicks, numYTicks, pen); - for (int i = 0; i <= numXTicks; ++i) { - int x = static_cast<int>(_bounds.left()/_scaleX + (i * (_bounds.width()/_scaleX) / numXTicks)); + for (int i = 0; i <= numXTicks; ++i) + { + int x = + static_cast<int>(_bounds.left() / _scaleX + + (i * (_bounds.width() / _scaleX) / numXTicks)); QDateTime currentDate = _startDate.addSecs(x); _xTicksText.push_back(addNonScalableText(currentDate.toString("dd.MM.yyyy"))); - _xTicksText.last()->setPos(x*_scaleX, _bounds.bottom() + 15); + _xTicksText.last()->setPos(x * _scaleX, _bounds.bottom() + 15); } - for (int j = 0; j <= numYTicks; ++j) { - float y = _bounds.bottom()/_scaleY - (j * (_bounds.height()/_scaleY) / numYTicks); - float label = _bounds.top() /_scaleY + (j * (_bounds.height()/_scaleY) / numYTicks); + for (int j = 0; j <= numYTicks; ++j) + { + float y = _bounds.bottom() / _scaleY - + (j * (_bounds.height() / _scaleY) / numYTicks); + float label = _bounds.top() / _scaleY + + (j * (_bounds.height() / _scaleY) / numYTicks); _yTicksText.push_back(addNonScalableText(QString::number(label))); - _yTicksText.last()->setPos(_bounds.left() - MARGIN/2, y*_scaleY); + _yTicksText.last()->setPos(_bounds.left() - MARGIN / 2, y * _scaleY); } } @@ -212,13 +226,16 @@ void DiagramScene::drawGraph(DiagramList* list) _graphs.push_back(addPath(path, pen)); addCaption(list->getName(), pen); - int last = _graphs.size()-1; + int last = _graphs.size() - 1; /** * For correct display the graph needs to be flipped vertically and then * translated back to its original position */ - int verticalShift = static_cast<int>(2 * (list->minYValue()*_scaleY) + (_graphs[last]->boundingRect()).height()); + int verticalShift = + static_cast<int>(2 * + (list->minYValue() * + _scaleY) + (_graphs[last]->boundingRect()).height()); _graphs[last]->setTransform(QTransform(QMatrix(1,0,0,-1,0,verticalShift))); } } @@ -227,15 +244,16 @@ void DiagramScene::drawGraph(DiagramList* list) /// This value is zero if minYValue<0<maxYValue and minYValue otherwise. int DiagramScene::getXAxisOffset() { - return (_bounds.top()<=0 && _bounds.bottom()>0) ? (int)(_bounds.bottom()+_bounds.top()) : (int)_bounds.bottom(); + return (_bounds.top() <= 0 && _bounds.bottom() > 0) ? (int)(_bounds.bottom() + + _bounds.top()) : (int)_bounds. + bottom(); } - /// Returns the x-value at which the y-axis should cross the x-axis. /// This value is zero if minXValue<0<maxXValue and minXValue otherwise. int DiagramScene::getYAxisOffset() { - return (_bounds.left()<=0 && _bounds.right()>0) ? 0 : (int)_bounds.left(); + return (_bounds.left() <= 0 && _bounds.right() > 0) ? 0 : (int)_bounds.left(); } /// Initialises the coordinate axes, adds labels and/or units to the axes, @@ -257,23 +275,28 @@ void DiagramScene::initialize() update(); } - /// Updates the (unscaled) boundaries of the visible coordinate system when a new /// list is added (boundaries are rescaled in the constructGrid-method void DiagramScene::setDiagramBoundaries(DiagramList* list) { if (!_lists.isEmpty()) { - if (list->minXValue()<_unscaledBounds.left()) _unscaledBounds.setLeft(list->minXValue()); - if (list->minYValue()<_unscaledBounds.top()) _unscaledBounds.setTop(list->minYValue()); - if (list->maxXValue()>_unscaledBounds.right()) _unscaledBounds.setRight(list->maxXValue()); - if (list->maxYValue()>_unscaledBounds.bottom()) _unscaledBounds.setBottom(list->maxYValue()); - if (_startDate>list->getStartDate()) _startDate = list->getStartDate(); + if (list->minXValue() < _unscaledBounds.left()) + _unscaledBounds.setLeft(list->minXValue()); + if (list->minYValue() < _unscaledBounds.top()) + _unscaledBounds.setTop(list->minYValue()); + if (list->maxXValue() > _unscaledBounds.right()) + _unscaledBounds.setRight(list->maxXValue()); + if (list->maxYValue() > _unscaledBounds.bottom()) + _unscaledBounds.setBottom(list->maxYValue()); + if (_startDate > list->getStartDate()) + _startDate = list->getStartDate(); } else { _unscaledBounds.setRect(list->minXValue(), list->minYValue(), - list->maxXValue()-list->minXValue(), list->maxYValue()-list->minYValue()); + list->maxXValue() - list->minXValue(), + list->maxYValue() - list->minYValue()); _startDate = list->getStartDate(); } } @@ -291,22 +314,22 @@ void DiagramScene::update() _xAxis->setLength(_bounds.width()); _yAxis->setLength(_bounds.height()); - _xLabel->setPos( _bounds.left() + _bounds.width()/2, _bounds.bottom()+1.5*MARGIN ); - _yLabel->setPos( _bounds.left()-1.5*MARGIN, _bounds.top() + _bounds.height()/2 ); + _xLabel->setPos( _bounds.left() + _bounds.width() / 2, _bounds.bottom() + 1.5 * MARGIN ); + _yLabel->setPos( _bounds.left() - 1.5 * MARGIN, _bounds.top() + _bounds.height() / 2 ); - _xUnit->setPos( _bounds.right(), _bounds.bottom()+1.2*MARGIN); - _yUnit->setPos( _bounds.left(), _bounds.top()-0.5*MARGIN); + _xUnit->setPos( _bounds.right(), _bounds.bottom() + 1.2 * MARGIN); + _yUnit->setPos( _bounds.left(), _bounds.top() - 0.5 * MARGIN); /* update graphs and their captions */ QRectF rect; - for (int i=0;i<_graphs.size();i++) + for (int i = 0; i < _graphs.size(); i++) { rect = _graphs[i]->boundingRect(); - int offset = static_cast<int>(fabs(rect.bottom()-_bounds.bottom()) - - fabs(rect.top()-_bounds.top())); + int offset = static_cast<int>(fabs(rect.bottom() - _bounds.bottom()) + - fabs(rect.top() - _bounds.top())); _graphs[i]->setPos(0, offset); rect = itemsBoundingRect(); - _graphCaptions[i]->setPos(_bounds.left(),rect.bottom()+10); + _graphCaptions[i]->setPos(_bounds.left(),rect.bottom() + 10); } } diff --git a/DataView/DiagramView/DiagramScene.h b/DataView/DiagramView/DiagramScene.h index b17784df01b36dc3bf8b6879cedf54c13500df38..466c3134e480a51610841a160f046f6a808c662a 100644 --- a/DataView/DiagramView/DiagramScene.h +++ b/DataView/DiagramView/DiagramScene.h @@ -6,11 +6,11 @@ #ifndef DIAGRAMSCENE_H #define DIAGRAMSCENE_H -#include <QGraphicsScene> -#include "QArrow.h" #include "DiagramList.h" +#include "QArrow.h" #include "QGraphicsGrid.h" #include "QNonScalableGraphicsTextItem.h" +#include <QGraphicsScene> class QDateTime; @@ -28,11 +28,12 @@ public: void addGraph(DiagramList* list); QGraphicsGrid* addGrid(const QRectF &rect, int xTicks, int yTicks, const QPen &pen); - static const int MARGIN=30; /// The margin between the boundary of the scene and the bounding box of all items within the scene + static const int MARGIN = 30; /// The margin between the boundary of the scene and the bounding box of all items within the scene private: void addCaption(const QString &name, QPen &pen); - QNonScalableGraphicsTextItem* addNonScalableText(const QString &text, const QFont &font = QFont()); + QNonScalableGraphicsTextItem* addNonScalableText(const QString &text, + const QFont &font = QFont()); void adjustAxis(float &min, float &max, int &numberOfTicks); void adjustScaling(); void clearGrid(); diff --git a/DataView/DiagramView/DiagramView.cpp b/DataView/DiagramView/DiagramView.cpp index 162fe1c1399d1fcd2bb5b288fad85788e331aadf..44e9dd5ce8cd771d9755ea807ffe4243adaa1fa9 100644 --- a/DataView/DiagramView/DiagramView.cpp +++ b/DataView/DiagramView/DiagramView.cpp @@ -3,10 +3,9 @@ * KR Initial implementation */ -#include <math.h> #include "DiagramView.h" #include <QGraphicsTextItem> - +#include <math.h> DiagramView::DiagramView(QWidget* parent) : QGraphicsView(parent) { @@ -65,27 +64,27 @@ void DiagramView::initialize() * appropriate transform for every single QGraphicsTextItem seperately. */ /* -void DiagramView::keepItemAspectRatio() -{ - double xFactor = transform().mapRect(QRectF(0, 0, 1, 1)).width(); - double yFactor = transform().mapRect(QRectF(0, 0, 1, 1)).height(); + void DiagramView::keepItemAspectRatio() + { + double xFactor = transform().mapRect(QRectF(0, 0, 1, 1)).width(); + double yFactor = transform().mapRect(QRectF(0, 0, 1, 1)).height(); QMatrix invertedScaling; invertedScaling.scale(1.0 , xFactor / yFactor); - scene->xLabel->setTransform(QTransform(invertedScaling)); - scene->yLabel->setTransform(QTransform(invertedScaling)); - scene->yLabel->rotate(-90); -} -*/ + scene->xLabel->setTransform(QTransform(invertedScaling)); + scene->yLabel->setTransform(QTransform(invertedScaling)); + scene->yLabel->rotate(-90); + } + */ QSize DiagramView::minimumSizeHint() const { - return QSize(3*_scene->MARGIN,2*_scene->MARGIN); + return QSize(3 * _scene->MARGIN,2 * _scene->MARGIN); } QSize DiagramView::sizeHint() const { - return QSize(6*_scene->MARGIN, 4*_scene->MARGIN); + return QSize(6 * _scene->MARGIN, 4 * _scene->MARGIN); } void DiagramView::resizeEvent(QResizeEvent* event) @@ -106,6 +105,7 @@ void DiagramView::update() //setResizeAnchor(QGraphicsView::AnchorViewCenter); QRectF viewRect = _scene->itemsBoundingRect(); _scene->setSceneRect(viewRect); - QRectF sceneInView(0/*_scene->MARGIN*/,_scene->MARGIN/2,viewRect.width()/*+_scene->MARGIN*/,viewRect.height()+_scene->MARGIN); + QRectF sceneInView(0 /*_scene->MARGIN*/,_scene->MARGIN / 2, + viewRect.width() /*+_scene->MARGIN*/,viewRect.height() + _scene->MARGIN); fitInView(sceneInView, Qt::IgnoreAspectRatio); } diff --git a/DataView/DiagramView/DiagramView.h b/DataView/DiagramView/DiagramView.h index 8a6ca3923297253ce3206a7e778fced277f62c84..98e8f236414b9ba7b804b63cc73d01e7cf904d4c 100644 --- a/DataView/DiagramView/DiagramView.h +++ b/DataView/DiagramView/DiagramView.h @@ -6,12 +6,12 @@ #ifndef DIAGRAMVIEW_H #define DIAGRAMVIEW_H -#include <QtGui/QWidget> -#include <QGraphicsView> #include "DiagramScene.h" +#include <QGraphicsView> +#include <QtGui/QWidget> /** - * \brief A view in which to display a DiagramScene. + * \brief A view in which to display a DiagramScene. * * A view in which to display a DiagramScene. It supports resizing of the window and loading of data into the diagram. */ @@ -45,8 +45,8 @@ protected: private: void initialize(); void keepItemAspectRatio(); - QSize minimumSizeHint() const; - QSize sizeHint() const; + QSize minimumSizeHint() const; + QSize sizeHint() const; void update(); DiagramScene* _scene; diff --git a/DataView/DiagramView/QArrow.cpp b/DataView/DiagramView/QArrow.cpp index b6776dd4e5ab4f4c23d80f729c44e9b191945794..1db08f7596557b9fbbdb1c0d0e82a30a7cb19354 100644 --- a/DataView/DiagramView/QArrow.cpp +++ b/DataView/DiagramView/QArrow.cpp @@ -3,10 +3,9 @@ * KR Initial implementation */ -#include <math.h> -#include <QPainter> #include "QArrow.h" - +#include <QPainter> +#include <math.h> /** * Creates an arrow as a QGraphicItem. @@ -17,13 +16,14 @@ * \param pen The pen for drawing the arrow * \param parent The parent QGraphicsItem. */ -QArrow::QArrow(float l, float a, float hl, float hw, QPen &pen, QGraphicsItem* parent) : QGraphicsItem(parent) +QArrow::QArrow(float l, float a, float hl, float hw, QPen &pen, + QGraphicsItem* parent) : QGraphicsItem(parent) { _arrowLength = l; _arrowAngle = a; _headLength = hl; _headWidth = hw; - _arrowPen = pen; + _arrowPen = pen; } /** @@ -37,9 +37,9 @@ QArrow::QArrow(float l, float a, QPen &pen, QGraphicsItem* parent) : QGraphicsIt { _arrowLength = l; _arrowAngle = a; - _headLength = 8; // default headlength - _headWidth = 5; // default headwidth - _arrowPen = pen; + _headLength = 8; // default headlength + _headWidth = 5; // default headwidth + _arrowPen = pen; } QArrow::~QArrow() @@ -48,19 +48,19 @@ QArrow::~QArrow() double QArrow::calcCos(double angle) { - return cos (angle*PI/180); + return cos (angle * PI / 180); } double QArrow::calcSin(double angle) { - return sin (angle*PI/180); + return sin (angle * PI / 180); } /// The bounding box of the arrow QRectF QArrow::boundingRect() const { - double deltaX = cos(_arrowAngle)*_arrowLength; - double deltaY = sin(_arrowAngle)*_arrowLength; + double deltaX = cos(_arrowAngle) * _arrowLength; + double deltaY = sin(_arrowAngle) * _arrowLength; return QRectF(0, 0, deltaX, deltaY); } @@ -81,25 +81,31 @@ double QArrow::getAngle() * Overloaded paint-method from QGraphicsItem. * Basically it draws a line with an arrowhead consisting of two short lines at the end */ -void QArrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void QArrow::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { Q_UNUSED (option) Q_UNUSED (widget) - double ddeltaX = calcCos(_arrowAngle)*_arrowLength; - double ddeltaY = calcSin(_arrowAngle)*_arrowLength; - double theta = atan(ddeltaY/ddeltaX); - double theta2 = (ddeltaX < 0.0) ? (theta+PI) : theta; - int lengthdeltaX = -static_cast<int>(cos(theta2)*_headLength); - int lengthdeltaY = -static_cast<int>(sin(theta2)*_headLength); - int widthdeltaX = static_cast<int>(sin(theta2)*_headWidth); - int widthdeltaY = static_cast<int>(cos(theta2)*_headWidth); + double ddeltaX = calcCos(_arrowAngle) * _arrowLength; + double ddeltaY = calcSin(_arrowAngle) * _arrowLength; + double theta = atan(ddeltaY / ddeltaX); + double theta2 = (ddeltaX < 0.0) ? (theta + PI) : theta; + int lengthdeltaX = -static_cast<int>(cos(theta2) * _headLength); + int lengthdeltaY = -static_cast<int>(sin(theta2) * _headLength); + int widthdeltaX = static_cast<int>(sin(theta2) * _headWidth); + int widthdeltaY = static_cast<int>(cos(theta2) * _headWidth); int deltaX = static_cast<int>(ddeltaX); int deltaY = static_cast<int>(ddeltaY); painter->setPen(_arrowPen); painter->drawLine(0, 0, deltaX, deltaY); - painter->drawLine(deltaX, deltaY, deltaX+lengthdeltaX+widthdeltaX, deltaY+lengthdeltaY-widthdeltaY); - painter->drawLine(deltaX, deltaY, deltaX+lengthdeltaX-widthdeltaX, deltaY+lengthdeltaY+widthdeltaY); + painter->drawLine(deltaX, + deltaY, + deltaX + lengthdeltaX + widthdeltaX, + deltaY + lengthdeltaY - widthdeltaY); + painter->drawLine(deltaX, + deltaY, + deltaX + lengthdeltaX - widthdeltaX, + deltaY + lengthdeltaY + widthdeltaY); } /// Changes orientation of the arrow. diff --git a/DataView/DiagramView/QArrow.h b/DataView/DiagramView/QArrow.h index 97200bbb086f9f1cf9d0ed4130711f775e65ad8f..be30a7ad71b6b8825c4716b76ca284e1cd4df1ca 100644 --- a/DataView/DiagramView/QArrow.h +++ b/DataView/DiagramView/QArrow.h @@ -11,7 +11,7 @@ const double PI = 3.14159265; /** - * \brief An arrow as a QGraphicsObject + * \brief An arrow as a QGraphicsObject */ class QArrow : public QGraphicsItem { @@ -22,7 +22,7 @@ public: double getLength(); double getAngle(); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); QRectF boundingRect() const; void setAngle(double a); void setLength(double l); @@ -35,7 +35,7 @@ private: float _arrowAngle; float _headLength; float _headWidth; - QPen _arrowPen; + QPen _arrowPen; }; #endif //QARROW_H diff --git a/DataView/DiagramView/QGraphicsGrid.cpp b/DataView/DiagramView/QGraphicsGrid.cpp index 83b7e45b007c07a13290cb893e183f92986b5c4a..01a40db427ec5bc80702d11479f02dc364cc8f7c 100644 --- a/DataView/DiagramView/QGraphicsGrid.cpp +++ b/DataView/DiagramView/QGraphicsGrid.cpp @@ -3,8 +3,8 @@ * KR Initial implementation */ -#include <QPainter> #include "QGraphicsGrid.h" +#include <QPainter> /** * Creates a grid using a QRectF object and a default pen and no ticks. @@ -13,12 +13,13 @@ * \param yCells The number of grid cells in y-direction. * \param parent The parent QGraphicsItem. */ -QGraphicsGrid::QGraphicsGrid(QRectF rect, int xCells, int yCells, QGraphicsItem* parent) : QGraphicsItem(parent) +QGraphicsGrid::QGraphicsGrid(QRectF rect, int xCells, int yCells, + QGraphicsItem* parent) : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = rect; - _showTicks = false; + _bounds = rect; + _showTicks = false; initDefaultPens(); } @@ -33,12 +34,18 @@ QGraphicsGrid::QGraphicsGrid(QRectF rect, int xCells, int yCells, QGraphicsItem* * \param yCells The number of grid cells in y-direction. * \param parent The parent QGraphicsItem. */ -QGraphicsGrid::QGraphicsGrid(int x, int y, int width, int height, int xCells, int yCells, QGraphicsItem* parent) : QGraphicsItem(parent) +QGraphicsGrid::QGraphicsGrid(int x, + int y, + int width, + int height, + int xCells, + int yCells, + QGraphicsItem* parent) : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = QRectF(x,y,width,height); - _showTicks = false; + _bounds = QRectF(x,y,width,height); + _showTicks = false; initDefaultPens(); } @@ -52,12 +59,17 @@ QGraphicsGrid::QGraphicsGrid(int x, int y, int width, int height, int xCells, in * \param pen The pen for drawing the grid. * \param parent The parent QGraphicsItem. */ -QGraphicsGrid::QGraphicsGrid(QRectF rect, int xCells, int yCells, bool ticks, QPen pen, QGraphicsItem* parent) : QGraphicsItem(parent) +QGraphicsGrid::QGraphicsGrid(QRectF rect, + int xCells, + int yCells, + bool ticks, + QPen pen, + QGraphicsItem* parent) : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = rect; - _showTicks = ticks; + _bounds = rect; + _showTicks = ticks; _outside = pen; _outside.setCosmetic(true); @@ -68,7 +80,6 @@ QGraphicsGrid::QGraphicsGrid(QRectF rect, int xCells, int yCells, bool ticks, QP _inside.setColor(iColour); _inside.setStyle(Qt::DotLine); _inside.setCosmetic(true); - } /** @@ -83,12 +94,20 @@ QGraphicsGrid::QGraphicsGrid(QRectF rect, int xCells, int yCells, bool ticks, QP * \param pen The pen for drawing the grid. * \param parent The parent QGraphicsItem. */ -QGraphicsGrid::QGraphicsGrid(int x, int y, int width, int height, int xCells, int yCells, bool ticks, QPen pen, QGraphicsItem* parent) : QGraphicsItem(parent) +QGraphicsGrid::QGraphicsGrid(int x, + int y, + int width, + int height, + int xCells, + int yCells, + bool ticks, + QPen pen, + QGraphicsItem* parent) : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = QRectF(x,y,width,height); - _showTicks = ticks; + _bounds = QRectF(x,y,width,height); + _showTicks = ticks; _outside = pen; _outside.setCosmetic(true); @@ -123,58 +142,67 @@ void QGraphicsGrid::initDefaultPens() } /// Paints the grid. -void QGraphicsGrid::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void QGraphicsGrid::paint(QPainter* painter, + const QStyleOptionGraphicsItem* option, + QWidget* widget) { Q_UNUSED (option) Q_UNUSED (widget) - if (!_bounds.isValid()) return; - + if (!_bounds.isValid()) + return; + /* draw outside rectangle */ QBrush brush(Qt::NoBrush); painter->setPen(_outside); painter->drawRect(_bounds); /* draw horizontal lines */ - for (int i = 0; i <= _numberOfXCells; ++i) { - int x = static_cast<int>(_bounds.left() + (i * (_bounds.width()-1) / _numberOfXCells)); - - if (i>0 && i<_numberOfXCells) - { - painter->setPen(_inside); - painter->drawLine(x, (int)_bounds.top(), x, (int)_bounds.bottom()); - } - - /* draw ticks on x-axis */ - if (_showTicks) - { - //double label = bounds.left() + (i * bounds.width() / numberOfXCells); - painter->setPen(_outside); - painter->drawLine(x, (int)_bounds.bottom(), x, (int)_bounds.bottom() + 5); - //painter->drawText(x - margin, bounds.bottom() + 5, 2*margin, 20, + for (int i = 0; i <= _numberOfXCells; ++i) + { + int x = + static_cast<int>(_bounds.left() + + (i * (_bounds.width() - 1) / _numberOfXCells)); + + if (i > 0 && i < _numberOfXCells) + { + painter->setPen(_inside); + painter->drawLine(x, (int)_bounds.top(), x, (int)_bounds.bottom()); + } + + /* draw ticks on x-axis */ + if (_showTicks) + { + //double label = bounds.left() + (i * bounds.width() / numberOfXCells); + painter->setPen(_outside); + painter->drawLine(x, (int)_bounds.bottom(), x, (int)_bounds.bottom() + 5); + //painter->drawText(x - margin, bounds.bottom() + 5, 2*margin, 20, // Qt::AlignHCenter | Qt::AlignTop, QString::number(label)); - } - } + } + } /* draw vertical lines */ - for (int j = 0; j <= _numberOfYCells; ++j) { - int y = static_cast<int>(_bounds.bottom() - (j * (_bounds.height()-1) / _numberOfYCells)); - - if (j>0 && j<_numberOfYCells) - { - painter->setPen(_inside); - painter->drawLine((int)_bounds.left(), y, (int)_bounds.right(), y); - } - - /* draw ticks on y-axis */ - if (_showTicks) - { - //double label = bounds.top() + (j * bounds.height() / numberOfYCells); - painter->setPen(_outside); - painter->drawLine((int)_bounds.left() - 5, y, (int)_bounds.left(), y); - //painter->drawText(bounds.left() - margin, y - 10, margin - 5, 20, - // Qt::AlignRight | Qt::AlignVCenter, QString::number(label)); - } + for (int j = 0; j <= _numberOfYCells; ++j) + { + int y = + static_cast<int>(_bounds.bottom() - + (j * (_bounds.height() - 1) / _numberOfYCells)); + + if (j > 0 && j < _numberOfYCells) + { + painter->setPen(_inside); + painter->drawLine((int)_bounds.left(), y, (int)_bounds.right(), y); + } + + /* draw ticks on y-axis */ + if (_showTicks) + { + //double label = bounds.top() + (j * bounds.height() / numberOfYCells); + painter->setPen(_outside); + painter->drawLine((int)_bounds.left() - 5, y, (int)_bounds.left(), y); + //painter->drawText(bounds.left() - margin, y - 10, margin - 5, 20, + // Qt::AlignRight | Qt::AlignVCenter, QString::number(label)); + } } } diff --git a/DataView/DiagramView/QGraphicsGrid.h b/DataView/DiagramView/QGraphicsGrid.h index fdcf01a1cda6414275fc2f45e1e046487936bd44..76f931f747dcf607ac68e54bc436a3e6d3607fd2 100644 --- a/DataView/DiagramView/QGraphicsGrid.h +++ b/DataView/DiagramView/QGraphicsGrid.h @@ -8,23 +8,41 @@ #include <QGraphicsItem> - /** * \brief A 2D carthesian grid as a QGraphicsItem. - * + * * A 2D carthesian grid as a QGraphicsItem. The size of the grid cells is constant but can be anisotroph. */ class QGraphicsGrid : public QGraphicsItem { public: QGraphicsGrid(QRectF rect, int xCells, int yCells, QGraphicsItem* parent = 0); - QGraphicsGrid(int x, int y, int width, int height, int xCells, int yCells, QGraphicsItem* parent = 0); - QGraphicsGrid(QRectF rect, int xCells, int yCells, bool ticks, QPen pen, QGraphicsItem* parent = 0); - QGraphicsGrid(int x, int y, int width, int height, int xCells, int yCells, bool ticks, QPen pen, QGraphicsItem* parent = 0); + QGraphicsGrid(int x, + int y, + int width, + int height, + int xCells, + int yCells, + QGraphicsItem* parent = 0); + QGraphicsGrid(QRectF rect, + int xCells, + int yCells, + bool ticks, + QPen pen, + QGraphicsItem* parent = 0); + QGraphicsGrid(int x, + int y, + int width, + int height, + int xCells, + int yCells, + bool ticks, + QPen pen, + QGraphicsItem* parent = 0); ~QGraphicsGrid(); QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void setNumberOfXCells(int xCells); void setNumberOfYCells(int yCells); void setRect(QRectF rect); diff --git a/DataView/ElementTreeModel.cpp b/DataView/ElementTreeModel.cpp index 942448663d9bed0e98fb04cea90e723d97768ab1..9abe05670b53105883e595f9b5908fd106be439e 100644 --- a/DataView/ElementTreeModel.cpp +++ b/DataView/ElementTreeModel.cpp @@ -3,15 +3,15 @@ * 2011/05/10 KR Initial implementation */ -#include "OGSError.h" #include "ElementTreeModel.h" +#include "OGSError.h" #include "TreeItem.h" /** * Constructor. */ -ElementTreeModel::ElementTreeModel( QObject *parent ) -: TreeModel(parent) +ElementTreeModel::ElementTreeModel( QObject* parent ) + : TreeModel(parent) { QList<QVariant> rootData; delete _rootItem; @@ -44,7 +44,8 @@ void ElementTreeModel::setElement(const GridAdapter* grid, const size_t elem_ind elemItem->appendChild(matItem); QList<QVariant> volData; - volData << "Area/Volume: " << QString::number(grid->getCFEMesh()->getElementVector()[elem_index]->calcVolume()); + volData << "Area/Volume: " << + QString::number(grid->getCFEMesh()->getElementVector()[elem_index]->calcVolume()); TreeItem* volItem = new TreeItem(volData, elemItem); elemItem->appendChild(volItem); @@ -53,11 +54,13 @@ void ElementTreeModel::setElement(const GridAdapter* grid, const size_t elem_ind TreeItem* nodeListItem = new TreeItem(nodeListData, elemItem); elemItem->appendChild(nodeListItem); - const std::vector<GEOLIB::Point*> *nodes = grid->getNodes(); - for (size_t i=0; i<elem->nodes.size(); i++) + const std::vector<GEOLIB::Point*>* nodes = grid->getNodes(); + for (size_t i = 0; i < elem->nodes.size(); i++) { QList<QVariant> nodeData; - nodeData << "Node " + QString::number(elem->nodes[i]) << QString::number((*(*nodes)[i])[0]) << QString::number((*(*nodes)[i])[1]) << QString::number((*(*nodes)[i])[2]); + nodeData << "Node " + QString::number(elem->nodes[i]) << + QString::number((*(*nodes)[i])[0]) << QString::number((*(*nodes)[i])[1]) << + QString::number((*(*nodes)[i])[2]); TreeItem* nodeItem = new TreeItem(nodeData, nodeListItem); nodeListItem->appendChild(nodeItem); } diff --git a/DataView/ElementTreeModel.h b/DataView/ElementTreeModel.h index 6b5e23b41dffeb2f2852f5afc91a565e6fc6e4f1..5c75e467fbdc7af2fd81f792f478140a66104386 100644 --- a/DataView/ElementTreeModel.h +++ b/DataView/ElementTreeModel.h @@ -6,14 +6,12 @@ #ifndef ELEMENTTREEMODEL_H #define ELEMENTTREEMODEL_H - -#include "TreeModel.h" #include "GridAdapter.h" - +#include "TreeModel.h" /** * \brief A model for the display of information concerning element information implemented as a TreeModel. - * \sa TreeModel, ElementTreeView, TreeItem + * \sa TreeModel, ElementTreeView, TreeItem */ class ElementTreeModel : public TreeModel { @@ -31,8 +29,6 @@ public slots: void setElement(const GridAdapter* grid, const size_t elem_index); private: - - }; #endif //ELEMENTTREEMODEL_H diff --git a/DataView/GEOModels.cpp b/DataView/GEOModels.cpp index 34dfb17f0507590fbe0bec47289a656b5c5de305..ec684f79b2cdb55fdd0d9433aa13a83d2116715f 100644 --- a/DataView/GEOModels.cpp +++ b/DataView/GEOModels.cpp @@ -28,12 +28,17 @@ GEOModels::~GEOModels() void GEOModels::removeGeometry(std::string geo_name, GEOLIB::GEOTYPE type) { - if (type==GEOLIB::INVALID || type==GEOLIB::SURFACE) this->removeSurfaceVec(geo_name); - if (type==GEOLIB::INVALID || type==GEOLIB::POLYLINE) this->removePolylineVec(geo_name); - if (type==GEOLIB::INVALID || type==GEOLIB::POINT) this->removePointVec(geo_name); + if (type == GEOLIB::INVALID || type == GEOLIB::SURFACE) + this->removeSurfaceVec(geo_name); + if (type == GEOLIB::INVALID || type == GEOLIB::POLYLINE) + this->removePolylineVec(geo_name); + if (type == GEOLIB::INVALID || type == GEOLIB::POINT) + this->removePointVec(geo_name); } -void GEOModels::addPointVec( std::vector<GEOLIB::Point*> *points, std::string &name, std::map<std::string, size_t>* name_pnt_id_map ) +void GEOModels::addPointVec( std::vector<GEOLIB::Point*>* points, + std::string &name, + std::map<std::string, size_t>* name_pnt_id_map ) { GEOObjects::addPointVec(points, name, name_pnt_id_map); _geoModel->addPointList(QString::fromStdString(name), this->getPointVecObj(name)); @@ -41,7 +46,7 @@ void GEOModels::addPointVec( std::vector<GEOLIB::Point*> *points, std::string &n } bool GEOModels::appendPointVec(const std::vector<GEOLIB::Point*> &points, - const std::string &name, std::vector<size_t>* ids) + const std::string &name, std::vector<size_t>* ids) { bool ret (GEOLIB::GEOObjects::appendPointVec (points, name, ids)); // TODO import new points into geo-treeview @@ -50,17 +55,21 @@ bool GEOModels::appendPointVec(const std::vector<GEOLIB::Point*> &points, bool GEOModels::removePointVec( const std::string &name ) { - - if (! isPntVecUsed(name)) { + if (!isPntVecUsed(name)) + { emit geoDataRemoved(_geoModel, name, GEOLIB::POINT); this->_geoModel->removeGeoList(name, GEOLIB::POINT); return GEOObjects::removePointVec(name); } - std::cout << "GEOModels::removePointVec() - There are still Polylines or Surfaces depending on these points." << std::endl; + std::cout << + "GEOModels::removePointVec() - There are still Polylines or Surfaces depending on these points." + << std::endl; return false; } -void GEOModels::addStationVec( std::vector<GEOLIB::Point*> *stations, std::string &name, const GEOLIB::Color* const color ) +void GEOModels::addStationVec( std::vector<GEOLIB::Point*>* stations, + std::string &name, + const GEOLIB::Color* const color ) { GEOObjects::addStationVec(stations, name, color); @@ -71,7 +80,7 @@ void GEOModels::addStationVec( std::vector<GEOLIB::Point*> *stations, std::strin void GEOModels::filterStationVec(const std::string &name, const std::vector<PropertyBounds> &bounds) { emit stationVectorRemoved(_stationModel, name); - const std::vector<GEOLIB::Point*> *stations (GEOObjects::getStationVec(name)); + const std::vector<GEOLIB::Point*>* stations (GEOObjects::getStationVec(name)); _stationModel->filterStations(name, stations, bounds); emit stationVectorAdded(_stationModel, name); } @@ -83,16 +92,20 @@ bool GEOModels::removeStationVec( const std::string &name ) return GEOObjects::removeStationVec(name); } -void GEOModels::addPolylineVec( std::vector<GEOLIB::Polyline*> *lines, const std::string &name, std::map<std::string,size_t>* ply_names ) +void GEOModels::addPolylineVec( std::vector<GEOLIB::Polyline*>* lines, + const std::string &name, + std::map<std::string,size_t>* ply_names ) { GEOObjects::addPolylineVec(lines, name, ply_names); - if (lines->empty()) return; + if (lines->empty()) + return; _geoModel->addPolylineList(QString::fromStdString(name), this->getPolylineVecObj(name)); emit geoDataAdded(_geoModel, name, GEOLIB::POLYLINE); } -bool GEOModels::appendPolylineVec(const std::vector<GEOLIB::Polyline*> &polylines, const std::string &name) +bool GEOModels::appendPolylineVec(const std::vector<GEOLIB::Polyline*> &polylines, + const std::string &name) { bool ret (GEOLIB::GEOObjects::appendPolylineVec (polylines, name)); @@ -107,16 +120,20 @@ bool GEOModels::removePolylineVec( const std::string &name ) return GEOObjects::removePolylineVec (name); } -void GEOModels::addSurfaceVec( std::vector<GEOLIB::Surface*> *surfaces, const std::string &name, std::map<std::string,size_t>* sfc_names ) +void GEOModels::addSurfaceVec( std::vector<GEOLIB::Surface*>* surfaces, + const std::string &name, + std::map<std::string,size_t>* sfc_names ) { GEOObjects::addSurfaceVec(surfaces, name, sfc_names); - if (surfaces->empty()) return; + if (surfaces->empty()) + return; _geoModel->addSurfaceList(QString::fromStdString(name), this->getSurfaceVecObj(name)); emit geoDataAdded(_geoModel, name, GEOLIB::SURFACE); } -bool GEOModels::appendSurfaceVec(const std::vector<GEOLIB::Surface*> &surfaces, const std::string &name) +bool GEOModels::appendSurfaceVec(const std::vector<GEOLIB::Surface*> &surfaces, + const std::string &name) { bool ret (GEOLIB::GEOObjects::appendSurfaceVec (surfaces, name)); @@ -124,8 +141,8 @@ bool GEOModels::appendSurfaceVec(const std::vector<GEOLIB::Surface*> &surfaces, this->_geoModel->appendSurfaces(name, this->getSurfaceVecObj(name)); else { - std::vector<GEOLIB::Surface*> *sfc = new std::vector<GEOLIB::Surface*>; - for (size_t i=0; i<surfaces.size(); i++) + std::vector<GEOLIB::Surface*>* sfc = new std::vector<GEOLIB::Surface*>; + for (size_t i = 0; i < surfaces.size(); i++) sfc->push_back(surfaces[i]); this->addSurfaceVec(sfc, name); } @@ -140,19 +157,26 @@ bool GEOModels::removeSurfaceVec( const std::string &name ) return GEOObjects::removeSurfaceVec (name); } -void GEOModels::connectPolylineSegments(const std::string &geoName, std::vector<size_t> indexlist, double proximity, std::string ply_name, bool closePly, bool triangulatePly) +void GEOModels::connectPolylineSegments(const std::string &geoName, + std::vector<size_t> indexlist, + double proximity, + std::string ply_name, + bool closePly, + bool triangulatePly) { GEOLIB::PolylineVec* plyVec = this->getPolylineVecObj(geoName); if (plyVec) { - const std::vector<GEOLIB::Polyline*> *polylines = plyVec->getVector(); + const std::vector<GEOLIB::Polyline*>* polylines = plyVec->getVector(); std::vector<GEOLIB::Polyline*> ply_list; - for (size_t i=0; i<indexlist.size(); i++) + for (size_t i = 0; i < indexlist.size(); i++) ply_list.push_back( (*polylines)[indexlist[i]] ); // connect polylines - GEOLIB::Polyline* new_line = GEOLIB::Polyline::constructPolylineFromSegments(ply_list, proximity); + GEOLIB::Polyline* new_line = GEOLIB::Polyline::constructPolylineFromSegments( + ply_list, + proximity); if (new_line) { diff --git a/DataView/GEOModels.h b/DataView/GEOModels.h index 5ed12b68e1999144463ab5a2f62aab0a0dcaaea3..7532bc76165f138a19ef95addda87301407173c0 100644 --- a/DataView/GEOModels.h +++ b/DataView/GEOModels.h @@ -4,14 +4,13 @@ * */ - #ifndef GEOMODELS_H #define GEOMODELS_H // ** INCLUDES ** -#include <QObject> #include "GEOObjects.h" #include "GeoType.h" +#include <QObject> class GeoTreeModel; class Model; @@ -42,28 +41,44 @@ public slots: /// Removes all parts (points, lines, surfaces) of the geometry with the given name. virtual void removeGeometry(std::string geo_name, GEOLIB::GEOTYPE type); - virtual void addPointVec(std::vector<GEOLIB::Point*> *points, std::string &name, std::map<std::string, size_t>* name_pnt_id_map = NULL); - virtual bool appendPointVec(const std::vector<GEOLIB::Point*> &points, const std::string &name, std::vector<size_t>* ids = NULL); + virtual void addPointVec(std::vector<GEOLIB::Point*>* points, + std::string &name, + std::map<std::string, size_t>* name_pnt_id_map = NULL); + virtual bool appendPointVec(const std::vector<GEOLIB::Point*> &points, + const std::string &name, + std::vector<size_t>* ids = NULL); virtual bool removePointVec(const std::string &name); - virtual void addStationVec(std::vector<GEOLIB::Point*> *stations, std::string &name, const GEOLIB::Color* const color); + virtual void addStationVec(std::vector<GEOLIB::Point*>* stations, + std::string &name, + const GEOLIB::Color* const color); void filterStationVec(const std::string &name, const std::vector<PropertyBounds> &bounds); virtual bool removeStationVec(const std::string &name); - virtual void addPolylineVec(std::vector<GEOLIB::Polyline*> *lines, const std::string &name, std::map<std::string,size_t>* ply_names = NULL); - virtual bool appendPolylineVec(const std::vector<GEOLIB::Polyline*> &polylines, const std::string &name); + virtual void addPolylineVec(std::vector<GEOLIB::Polyline*>* lines, + const std::string &name, + std::map<std::string,size_t>* ply_names = NULL); + virtual bool appendPolylineVec(const std::vector<GEOLIB::Polyline*> &polylines, + const std::string &name); virtual bool removePolylineVec(const std::string &name); - virtual void addSurfaceVec(std::vector<GEOLIB::Surface*> *surfaces, const std::string &name, std::map<std::string,size_t>* sfc_names = NULL); - - /// @brief + virtual void addSurfaceVec(std::vector<GEOLIB::Surface*>* surfaces, + const std::string &name, + std::map<std::string,size_t>* sfc_names = NULL); + + /// @brief /// @param surfaces The surface vector. - virtual bool appendSurfaceVec(const std::vector<GEOLIB::Surface*> &surfaces, const std::string &name); + virtual bool appendSurfaceVec(const std::vector<GEOLIB::Surface*> &surfaces, + const std::string &name); virtual bool removeSurfaceVec(const std::string &name); /// Calls all necessary functions to connect polyline-segments and update all views and windows. - void connectPolylineSegments(const std::string &geoName, std::vector<size_t> indexlist, double proximity, std::string ply_name, bool closePly, bool triangulatePly); - + void connectPolylineSegments(const std::string &geoName, + std::vector<size_t> indexlist, + double proximity, + std::string ply_name, + bool closePly, + bool triangulatePly); protected: GeoTreeModel* _geoModel; diff --git a/DataView/GMSHPrefsDialog.cpp b/DataView/GMSHPrefsDialog.cpp index 74a9dc1558d7c2120b5ecd00923d1aa252ba97e3..b087545d18ce4777920400ed46312fc95c8d516c 100644 --- a/DataView/GMSHPrefsDialog.cpp +++ b/DataView/GMSHPrefsDialog.cpp @@ -16,7 +16,7 @@ #include <QStringListModel> GMSHPrefsDialog::GMSHPrefsDialog(const GEOLIB::GEOObjects* geoObjects, QDialog* parent) -: QDialog(parent), _allGeo(new QStringListModel), _selGeo(new QStringListModel) + : QDialog(parent), _allGeo(new QStringListModel), _selGeo(new QStringListModel) { setupUi(this); @@ -27,13 +27,25 @@ GMSHPrefsDialog::GMSHPrefsDialog(const GEOLIB::GEOObjects* geoObjects, QDialog* this->param4->setText("0"); // object will be deleted by Qt - StrictIntValidator *max_number_of_points_in_quadtree_leaf_validator (new StrictIntValidator (1, 1000, this->param1)); + StrictIntValidator* max_number_of_points_in_quadtree_leaf_validator (new StrictIntValidator ( + 1, + 1000, + this->param1)); param1->setValidator (max_number_of_points_in_quadtree_leaf_validator); // object will be deleted by Qt - StrictDoubleValidator *mesh_density_scaling_pnts_validator(new StrictDoubleValidator (1e-10, 1.0, 5, this->param2)); + StrictDoubleValidator* mesh_density_scaling_pnts_validator(new StrictDoubleValidator ( + 1e-10, + 1.0, + 5, + this + ->param2)); param2->setValidator (mesh_density_scaling_pnts_validator); // object will be deleted by Qt# - StrictDoubleValidator *mesh_density_scaling_stations_validator(new StrictDoubleValidator (1e-10, 1.0, 5, this->param3)); + StrictDoubleValidator* mesh_density_scaling_stations_validator(new StrictDoubleValidator ( + 1e-10, + 1.0, + 5, + this->param3)); param3->setValidator (mesh_density_scaling_stations_validator); std::vector<std::string> geoNames; @@ -43,17 +55,14 @@ GMSHPrefsDialog::GMSHPrefsDialog(const GEOLIB::GEOObjects* geoObjects, QDialog* std::vector<std::string> geo_station_names; geoObjects->getStationNames(geo_station_names); - for (size_t k(0); k<geo_station_names.size(); k++) { + for (size_t k(0); k < geo_station_names.size(); k++) geoNames.push_back (geo_station_names[k]); - } size_t nGeoObjects(geoNames.size()); QStringList list; - for (size_t i=0; i<nGeoObjects; i++) - { + for (size_t i = 0; i < nGeoObjects; i++) list.append(QString::fromStdString(geoNames[i])); - } if (list.empty()) { @@ -64,7 +73,7 @@ GMSHPrefsDialog::GMSHPrefsDialog(const GEOLIB::GEOObjects* geoObjects, QDialog* _allGeo->setStringList(list); this->allGeoView->setModel(_allGeo); this->selectedGeoView->setModel(_selGeo); - this->radioAdaptive->toggle(); // default is adaptive meshing + this->radioAdaptive->toggle(); // default is adaptive meshing this->on_radioAdaptive_toggled(true); } @@ -130,10 +139,10 @@ void GMSHPrefsDialog::accept() if (this->radioAdaptive->isChecked()) { - max_number_of_points_in_quadtree_leaf = str2number<size_t> (param1->text().toStdString().c_str()); - if (max_number_of_points_in_quadtree_leaf == 0) { + max_number_of_points_in_quadtree_leaf = str2number<size_t> ( + param1->text().toStdString().c_str()); + if (max_number_of_points_in_quadtree_leaf == 0) max_number_of_points_in_quadtree_leaf = 10; - } mesh_density_scaling_pnts = fabs (strtod(param2->text().toStdString().c_str(), 0)); if (mesh_density_scaling_pnts < sqrt(std::numeric_limits<double>::min())) mesh_density_scaling_pnts = 0.5; @@ -142,12 +151,15 @@ void GMSHPrefsDialog::accept() mesh_density_scaling_stations = 0.05; } else - { val4 = strtod(param4->text().toStdString().c_str(), 0); - } bool delete_geo_file = this->geoFileDelete->isChecked(); - emit requestMeshing(selectedObjects, max_number_of_points_in_quadtree_leaf, mesh_density_scaling_pnts, mesh_density_scaling_stations, val4, delete_geo_file); + emit requestMeshing(selectedObjects, + max_number_of_points_in_quadtree_leaf, + mesh_density_scaling_pnts, + mesh_density_scaling_stations, + val4, + delete_geo_file); this->done(QDialog::Accepted); } @@ -160,8 +172,6 @@ std::vector<std::string> GMSHPrefsDialog::getSelectedObjects(QStringList list) { std::vector<std::string> indexList; for (QStringList::iterator it = list.begin(); it != list.end(); ++it) - { indexList.push_back(it->toStdString()); - } return indexList; } diff --git a/DataView/GMSHPrefsDialog.h b/DataView/GMSHPrefsDialog.h index 91645651bce6c24ac11dffc098b973770a84b470..c3c520c3680e1ddc281054c2667a95b52341235d 100644 --- a/DataView/GMSHPrefsDialog.h +++ b/DataView/GMSHPrefsDialog.h @@ -6,13 +6,14 @@ #ifndef GMSHPREFSDIALOG_H #define GMSHPREFSDIALOG_H -#include <QtGui/QMainWindow> #include "ui_GMSHPrefs.h" +#include <QtGui/QMainWindow> class QStringListModel; -namespace GEOLIB { - class GEOObjects; +namespace GEOLIB +{ +class GEOObjects; } /** @@ -26,15 +27,12 @@ public: GMSHPrefsDialog(const GEOLIB::GEOObjects* geoObjects, QDialog* parent = 0); ~GMSHPrefsDialog(void); - - private: std::vector<std::string> getSelectedObjects(QStringList list); QStringListModel* _allGeo; QStringListModel* _selGeo; - private slots: void on_selectGeoButton_pressed(); void on_deselectGeoButton_pressed(); @@ -48,7 +46,6 @@ private slots: signals: void requestMeshing(std::vector<std::string> const &, size_t, double, double, double, bool); - }; #endif //GMSHPREFSDIALOG_H diff --git a/DataView/GeoObjectListItem.h b/DataView/GeoObjectListItem.h index ea4819b4d9ce6be046418f07b209938f37fe0f4d..9cd2c68fda602ae9eabb0f24a56248d846c6227d 100644 --- a/DataView/GeoObjectListItem.h +++ b/DataView/GeoObjectListItem.h @@ -6,22 +6,22 @@ #ifndef GEOOBJECTLISTITEM_H #define GEOOBJECTLISTITEM_H - #include "GeoType.h" -#include <vtkPolyDataAlgorithm.h> #include "VtkPointsSource.h" #include "VtkPolylinesSource.h" #include "VtkSurfacesSource.h" #include <QModelIndex> - +#include <vtkPolyDataAlgorithm.h> class GeoObjectListItem : public TreeItem { - public: /// Constructor for the TreeItem specifying the "Points"-subtree of a geometry. - GeoObjectListItem(const QList<QVariant> &data, TreeItem *parent, const std::vector<GEOLIB::Point*> *geo_data = NULL, GEOLIB::GEOTYPE type = GEOLIB::POINT) + GeoObjectListItem(const QList<QVariant> &data, + TreeItem* parent, + const std::vector<GEOLIB::Point*>* geo_data = NULL, + GEOLIB::GEOTYPE type = GEOLIB::POINT) : TreeItem(data, parent), _vtkSource(VtkPointsSource::New()), _type(type) { QString geo_name = parent->data(0).toString(); @@ -30,7 +30,10 @@ public: } /// Constructor for the TreeItem specifying the "Polylines"-subtree of a geometry. - GeoObjectListItem(const QList<QVariant> &data, TreeItem *parent, const std::vector<GEOLIB::Polyline*> *geo_data = NULL, GEOLIB::GEOTYPE type = GEOLIB::POLYLINE) + GeoObjectListItem(const QList<QVariant> &data, + TreeItem* parent, + const std::vector<GEOLIB::Polyline*>* geo_data = NULL, + GEOLIB::GEOTYPE type = GEOLIB::POLYLINE) : TreeItem(data, parent), _vtkSource(VtkPolylinesSource::New()), _type(type) { QString geo_name = parent->data(0).toString(); @@ -39,7 +42,10 @@ public: } /// Constructor for the TreeItem specifying the "Surfaces"-subtree of a geometry. - GeoObjectListItem(const QList<QVariant> &data, TreeItem *parent, const std::vector<GEOLIB::Surface*> *geo_data = NULL, GEOLIB::GEOTYPE type = GEOLIB::SURFACE) + GeoObjectListItem(const QList<QVariant> &data, + TreeItem* parent, + const std::vector<GEOLIB::Surface*>* geo_data = NULL, + GEOLIB::GEOTYPE type = GEOLIB::SURFACE) : TreeItem(data, parent), _vtkSource(VtkSurfacesSource::New()), _type(type) { QString geo_name = parent->data(0).toString(); @@ -53,10 +59,10 @@ public: } /// Returns the type of geo-objects contained in the subtree of this item. - GEOLIB::GEOTYPE getType() { return _type; }; + GEOLIB::GEOTYPE getType() { return _type; } /// Returns the Vtk polydata source object - vtkPolyDataAlgorithm* vtkSource() const { return _vtkSource; }; + vtkPolyDataAlgorithm* vtkSource() const { return _vtkSource; } private: /// The Vtk data source object. This is the starting point for a Vtk data diff --git a/DataView/GeoTabWidget.cpp b/DataView/GeoTabWidget.cpp index f4e787157235de903c104712fb5f8fe435e4f4bb..13089a21e4741fd0b2311c6e1db09cbe7a455e25 100644 --- a/DataView/GeoTabWidget.cpp +++ b/DataView/GeoTabWidget.cpp @@ -7,7 +7,7 @@ #include "GeoTabWidget.h" GeoTabWidget::GeoTabWidget( QWidget* parent /*= 0*/ ) -: QWidget(parent) + : QWidget(parent) { setupUi(this); } diff --git a/DataView/GeoTabWidget.h b/DataView/GeoTabWidget.h index b619611f698e7ebb72bb9b647a0037b127db0daa..d17a90c62e6d66e8045e063c984a410ff2770ed5 100644 --- a/DataView/GeoTabWidget.h +++ b/DataView/GeoTabWidget.h @@ -4,7 +4,6 @@ * */ - #ifndef GEOTABWIDGET_H #define GEOTABWIDGET_H @@ -21,10 +20,7 @@ class GeoTabWidget : public QWidget, public Ui_GeoTabWidgetBase public: GeoTabWidget(QWidget* parent = 0); - - private: - }; #endif // GEOTABWIDGET_H diff --git a/DataView/GeoTreeItem.h b/DataView/GeoTreeItem.h index b093adf176fc4262a80149b88f8845d67a9e6c0b..b9e091d79af2ed99181484d31b8c9d9d6e6e75ce 100644 --- a/DataView/GeoTreeItem.h +++ b/DataView/GeoTreeItem.h @@ -24,11 +24,13 @@ public: * \param parent The parent item in the tree * \param item The GeoObject (i.e. Point, Polyline or Surface) */ - GeoTreeItem(const QList<QVariant> &data, TreeItem *parent, const GEOLIB::GeoObject* item = NULL) : TreeItem(data, parent), _item(item) {}; - ~GeoTreeItem() {}; - + GeoTreeItem(const QList<QVariant> &data, + TreeItem* parent, + const GEOLIB::GeoObject* item = NULL) : TreeItem(data, parent), _item(item) {} + ~GeoTreeItem() {} + /// Returns the geo-object associated with this item (i.e. a point, polyline or surface). - const GEOLIB::GeoObject* getGeoObject() const { return _item; }; + const GEOLIB::GeoObject* getGeoObject() const { return _item; } private: const GEOLIB::GeoObject* _item; diff --git a/DataView/GeoTreeModel.cpp b/DataView/GeoTreeModel.cpp index b6bfe15107a64a7f30ff69285bb2c3db7fd3eddf..652add5b54d6e8fc165b99514503459b9d780493 100644 --- a/DataView/GeoTreeModel.cpp +++ b/DataView/GeoTreeModel.cpp @@ -3,16 +3,16 @@ * 2011/02/07 KR Initial implementation */ +#include "GeoObjectListItem.h" +#include "GeoTreeItem.h" #include "GeoTreeModel.h" #include "OGSError.h" -#include "GeoTreeItem.h" -#include "GeoObjectListItem.h" /** * Constructor. */ -GeoTreeModel::GeoTreeModel( QObject *parent ) -: TreeModel(parent) +GeoTreeModel::GeoTreeModel( QObject* parent ) + : TreeModel(parent) { QList<QVariant> rootData; delete _rootItem; @@ -24,21 +24,21 @@ GeoTreeModel::~GeoTreeModel() { } /* -const GEOLIB::GeoObject* GeoTreeModel::objectFromIndex( const QModelIndex& index, QString &geoName ) const -{ - if (index.isValid()) - { - GeoTreeItem* treeItem = static_cast<GeoTreeItem*>(index.internalPointer()); - //TreeItem* parentItem = treeItem->parentItem(); - //geoName = parentItem->data(0).toString(); - if (treeItem) return treeItem->getGeoObject(); - } - return NULL; -} -*/ + const GEOLIB::GeoObject* GeoTreeModel::objectFromIndex( const QModelIndex& index, QString &geoName ) const + { + if (index.isValid()) + { + GeoTreeItem* treeItem = static_cast<GeoTreeItem*>(index.internalPointer()); + //TreeItem* parentItem = treeItem->parentItem(); + //geoName = parentItem->data(0).toString(); + if (treeItem) return treeItem->getGeoObject(); + } + return NULL; + } + */ void GeoTreeModel::addPointList(QString geoName, const GEOLIB::PointVec* pointVec) { - const std::vector<GEOLIB::Point*> *points = pointVec->getVector(); + const std::vector<GEOLIB::Point*>* points = pointVec->getVector(); QList<QVariant> geoData; geoData << QVariant(geoName) << "" << "" << ""; @@ -53,14 +53,18 @@ void GeoTreeModel::addPointList(QString geoName, const GEOLIB::PointVec* pointVe GeoObjectListItem* pointList = new GeoObjectListItem(pointData, geo, points, GEOLIB::POINT); geo->appendChild(pointList); - size_t nPoints = points->size(); - for (size_t j=0; j<nPoints; j++) + for (size_t j = 0; j < nPoints; j++) { QList<QVariant> pnt; - pnt << static_cast<unsigned>(j) << QString::number((*(*points)[j])[0],'f') << QString::number((*(*points)[j])[1],'f') << QString::number((*(*points)[j])[2],'f'); - GeoTreeItem* point = new GeoTreeItem(pnt, pointList, static_cast<GEOLIB::Point*>((*points)[j])); + pnt << static_cast<unsigned>(j) << + QString::number((*(*points)[j])[0], + 'f') << QString::number((*(*points)[j])[1],'f') << QString::number( + (*(*points)[j])[2], + 'f'); + GeoTreeItem* point = + new GeoTreeItem(pnt, pointList, static_cast<GEOLIB::Point*>((*points)[j])); pointList->appendChild(point); } @@ -74,19 +78,19 @@ void GeoTreeModel::addPolylineList(QString geoName, const GEOLIB::PolylineVec* p { int nLists = _rootItem->childCount(); TreeItem* geo(NULL); - for (int i=0; i<nLists; i++) - { + for (int i = 0; i < nLists; i++) if (_rootItem->child(i)->data(0).toString().compare(geoName) == 0) geo = _rootItem->child(i); - } if (geo == NULL) { - std::cout << "GeoTreeModel::addPolylineList() - Error: No corresponding geometry found..." << std::endl; + std::cout << + "GeoTreeModel::addPolylineList() - Error: No corresponding geometry found..." << + std::endl; return; } - const std::vector<GEOLIB::Polyline*> *lines = polylineVec->getVector(); + const std::vector<GEOLIB::Polyline*>* lines = polylineVec->getVector(); QList<QVariant> plyData; plyData << "Polylines" << "" << "" << ""; @@ -99,71 +103,80 @@ void GeoTreeModel::addPolylineList(QString geoName, const GEOLIB::PolylineVec* p void GeoTreeModel::appendPolylines(const std::string &name, const GEOLIB::PolylineVec* polylineVec) { - for (size_t i=0; i<_lists.size(); i++) + for (size_t i = 0; i < _lists.size(); i++) { if ( name.compare( _lists[i]->data(0).toString().toStdString() ) == 0 ) - { - for (int j=0; j<_lists[i]->childCount(); j++) + for (int j = 0; j < _lists[i]->childCount(); j++) { - GeoObjectListItem* parent = static_cast<GeoObjectListItem*>(_lists[i]->child(j)); + GeoObjectListItem* parent = + static_cast<GeoObjectListItem*>(_lists[i]->child(j)); if (GEOLIB::POLYLINE == parent->getType()) { - this->addChildren(parent, polylineVec, parent->childCount(), polylineVec->getVector()->size()); + this->addChildren(parent, polylineVec, + parent->childCount(), + polylineVec->getVector()->size()); reset(); parent->vtkSource()->Modified(); return; } } - } } OGSError::box("Error adding polyline to geometry."); } -void GeoTreeModel::addChildren(GeoObjectListItem* plyList, const GEOLIB::PolylineVec* polyline_vec, size_t start_index, size_t end_index) +void GeoTreeModel::addChildren(GeoObjectListItem* plyList, + const GEOLIB::PolylineVec* polyline_vec, + size_t start_index, + size_t end_index) { - const std::vector<GEOLIB::Polyline*> *lines = polyline_vec->getVector(); + const std::vector<GEOLIB::Polyline*>* lines = polyline_vec->getVector(); - for (size_t i=start_index; i<end_index; i++) + for (size_t i = start_index; i < end_index; i++) { QList<QVariant> line; std::string ply_name(""); line << "Line " + QString::number(i); - if (polyline_vec->getNameOfElementByID(i, ply_name)) line << QString::fromStdString(ply_name) << "" << ""; - else line << "" << "" << ""; - + if (polyline_vec->getNameOfElementByID(i, ply_name)) + line << QString::fromStdString(ply_name) << "" << ""; + else + line << "" << "" << ""; GeoTreeItem* lineItem = new GeoTreeItem(line, plyList, (*lines)[i]); plyList->appendChild(lineItem); int nPoints = static_cast<int>((*lines)[i]->getNumberOfPoints()); - for (int j=0; j<nPoints; j++) + for (int j = 0; j < nPoints; j++) { QList<QVariant> pnt; - pnt << static_cast<int>((*lines)[i]->getPointID(j)) << QString::number((*(*(*lines)[i])[j])[0],'f') << QString::number((*(*(*lines)[i])[j])[1],'f') << QString::number((*(*(*lines)[i])[j])[2],'f'); + pnt << static_cast<int>((*lines)[i]->getPointID(j)) << + QString::number((*(*(*lines)[i])[j])[0], + 'f') << + QString::number((*(*(*lines)[i])[j])[1], + 'f') << QString::number((*(*(*lines)[i])[j])[2],'f'); TreeItem* child = new TreeItem(pnt, lineItem); lineItem->appendChild(child); } } - std::cout << end_index-start_index << " polylines added." << std::endl; + std::cout << end_index - start_index << " polylines added." << std::endl; } void GeoTreeModel::addSurfaceList(QString geoName, const GEOLIB::SurfaceVec* surfaceVec) { int nLists = _rootItem->childCount(); TreeItem* geo(NULL); - for (int i=0; i<nLists; i++) - { + for (int i = 0; i < nLists; i++) if (_rootItem->child(i)->data(0).toString().compare(geoName) == 0) geo = _rootItem->child(i); - } if (geo == NULL) { - std::cout << "GeoTreeModel::addSurfaceList() - Error: No corresponding geometry found..." << std::endl; + std::cout << + "GeoTreeModel::addSurfaceList() - Error: No corresponding geometry found..." << + std::endl; return; } - const std::vector<GEOLIB::Surface*> *surfaces = surfaceVec->getVector(); + const std::vector<GEOLIB::Surface*>* surfaces = surfaceVec->getVector(); QList<QVariant> sfcData; sfcData << "Surfaces" << "" << "" << ""; @@ -176,61 +189,75 @@ void GeoTreeModel::addSurfaceList(QString geoName, const GEOLIB::SurfaceVec* sur void GeoTreeModel::appendSurfaces(const std::string &name, GEOLIB::SurfaceVec* surfaceVec) { - for (size_t i=0; i<_lists.size(); i++) + for (size_t i = 0; i < _lists.size(); i++) { if ( name.compare( _lists[i]->data(0).toString().toStdString() ) == 0 ) - { - for (int j=0; j<_lists[i]->childCount(); j++) + for (int j = 0; j < _lists[i]->childCount(); j++) { - GeoObjectListItem* parent = static_cast<GeoObjectListItem*>(_lists[i]->child(j)); + GeoObjectListItem* parent = + static_cast<GeoObjectListItem*>(_lists[i]->child(j)); if (GEOLIB::SURFACE == parent->getType()) { - this->addChildren(parent, surfaceVec, parent->childCount(), surfaceVec->getVector()->size()); + this->addChildren(parent, surfaceVec, + parent->childCount(), + surfaceVec->getVector()->size()); reset(); parent->vtkSource()->Modified(); return; } } - } } OGSError::box("Error adding surface to geometry."); } -void GeoTreeModel::addChildren(GeoObjectListItem* sfcList, const GEOLIB::SurfaceVec* surface_vec, size_t start_index, size_t end_index) +void GeoTreeModel::addChildren(GeoObjectListItem* sfcList, + const GEOLIB::SurfaceVec* surface_vec, + size_t start_index, + size_t end_index) { - const std::vector<GEOLIB::Surface*> *surfaces = surface_vec->getVector(); + const std::vector<GEOLIB::Surface*>* surfaces = surface_vec->getVector(); - for (size_t i=start_index; i<end_index; i++) + for (size_t i = start_index; i < end_index; i++) { QList<QVariant> surface; std::string sfc_name(""); surface << "Surface " + QString::number(i); - if (surface_vec->getNameOfElementByID(i, sfc_name)) surface << QString::fromStdString(sfc_name) << "" << ""; - else surface << "" << "" << ""; + if (surface_vec->getNameOfElementByID(i, sfc_name)) + surface << QString::fromStdString(sfc_name) << "" << ""; + else + surface << "" << "" << ""; GeoTreeItem* surfaceItem = new GeoTreeItem(surface, sfcList, (*surfaces)[i]); sfcList->appendChild(surfaceItem); - const std::vector<GEOLIB::Point*> *nodesVec = (*surfaces)[i]->getPointVec(); + const std::vector<GEOLIB::Point*>* nodesVec = (*surfaces)[i]->getPointVec(); int nElems = static_cast<int>((*surfaces)[i]->getNTriangles()); - for (int j=0; j<nElems; j++) + for (int j = 0; j < nElems; j++) { QList<QVariant> elem; - elem << j << static_cast<int>((*(*(*surfaces)[i])[j])[0]) << static_cast<int>((*(*(*surfaces)[i])[j])[1]) << static_cast<int>((*(*(*surfaces)[i])[j])[2]); + elem << j << static_cast<int>((*(*(*surfaces)[i])[j])[0]) << + static_cast<int>((*(*(*surfaces)[i])[j])[1]) << + static_cast<int>((*(*(*surfaces)[i])[j])[2]); TreeItem* child = new TreeItem(elem, surfaceItem); surfaceItem->appendChild(child); - for (int k=0; k<3; k++) + for (int k = 0; k < 3; k++) { QList<QVariant> node; - node << static_cast<int>((*(*(*surfaces)[i])[j])[k]) << QString::number((*(*nodesVec)[(*(*(*surfaces)[i])[j])[k]])[0],'f') << QString::number((*(*nodesVec)[(*(*(*surfaces)[i])[j])[k]])[1],'f') << QString::number((*(*nodesVec)[(*(*(*surfaces)[i])[j])[k]])[2],'f'); + node << static_cast<int>((*(*(*surfaces)[i])[j])[k]) << + QString::number((*(*nodesVec)[(*(*(*surfaces)[i])[j])[k]])[0], + 'f') << QString::number( + (*(*nodesVec)[(*(*(*surfaces)[i])[j])[k]])[1], + 'f') << QString::number( + (*(*nodesVec)[(*(*(*surfaces)[i])[j])[k]])[2], + 'f'); TreeItem* nchild = new TreeItem(node, child); child->appendChild(nchild); } } } - std::cout << end_index-start_index << " surfaces added." << std::endl; + std::cout << end_index - start_index << " surfaces added." << std::endl; } /** @@ -238,43 +265,39 @@ void GeoTreeModel::addChildren(GeoObjectListItem* sfcList, const GEOLIB::Surface */ void GeoTreeModel::removeGeoList(const std::string &name, GEOLIB::GEOTYPE type) { - for (size_t i=0; i<_lists.size(); i++) - { + for (size_t i = 0; i < _lists.size(); i++) if ( name.compare( _lists[i]->data(0).toString().toStdString() ) == 0 ) { - for (int j=0; j<_lists[i]->childCount(); j++) - { - if (type == static_cast<GeoObjectListItem*>(_lists[i]->child(j))->getType()) + for (int j = 0; j < _lists[i]->childCount(); j++) + if (type == + static_cast<GeoObjectListItem*>(_lists[i]->child(j))->getType()) { QModelIndex index = createIndex(j, 0, _lists[i]->child(j)); removeRows(0, _lists[i]->child(j)->childCount(), index); removeRows(j, 1, parent(index)); break; } - } if (_lists[i]->childCount() == 0) { _lists.erase(_lists.begin() + i); removeRows(i, 1, QModelIndex()); } } - } } vtkPolyDataAlgorithm* GeoTreeModel::vtkSource(const std::string &name, GEOLIB::GEOTYPE type) const { size_t nLists = _lists.size(); - for (size_t i=0; i<nLists; i++) + for (size_t i = 0; i < nLists; i++) { if ( name.compare( _lists[i]->data(0).toString().toStdString() ) == 0 ) - { - for (int j=0; j<_lists[i]->childCount(); j++) + for (int j = 0; j < _lists[i]->childCount(); j++) { - GeoObjectListItem* item = dynamic_cast<GeoObjectListItem*>(_lists[i]->child(j)); + GeoObjectListItem* item = + dynamic_cast<GeoObjectListItem*>(_lists[i]->child(j)); if (item->getType() == type) return item->vtkSource(); } - } } return NULL; } diff --git a/DataView/GeoTreeModel.h b/DataView/GeoTreeModel.h index a280ba8c4146bc00c11e291028aadd7388f5bedf..3dc20199f6b59dc8783f4ef5ed2a817a06270d75 100644 --- a/DataView/GeoTreeModel.h +++ b/DataView/GeoTreeModel.h @@ -6,7 +6,6 @@ #ifndef GEOTREEMODEL_H #define GEOTREEMODEL_H - #include <vector> #include "GeoType.h" @@ -16,8 +15,9 @@ #include "TreeModel.h" #include <vtkPolyDataAlgorithm.h> -namespace GEOLIB { - class GeoObject; +namespace GEOLIB +{ +class GeoObject; } class QString; @@ -27,7 +27,7 @@ class GeoObjectListItem; /** * \brief A model for the GeoTreeView implementing a tree as a double-linked list. - * \sa TreeModel, GeoTreeView, TreeItem, GeoTreeItem + * \sa TreeModel, GeoTreeView, TreeItem, GeoTreeItem */ class GeoTreeModel : public TreeModel { @@ -72,13 +72,18 @@ public: private: /// Adds children to the "Polylines" node - void addChildren(GeoObjectListItem* plyList, const GEOLIB::PolylineVec* polyline_vec, size_t start_index, size_t end_index); - + void addChildren(GeoObjectListItem* plyList, + const GEOLIB::PolylineVec* polyline_vec, + size_t start_index, + size_t end_index); + /// Adds children to the "Surfaces" node - void addChildren(GeoObjectListItem* sfcList, const GEOLIB::SurfaceVec* surface_vec, size_t start_index, size_t end_index); + void addChildren(GeoObjectListItem* sfcList, + const GEOLIB::SurfaceVec* surface_vec, + size_t start_index, + size_t end_index); std::vector<GeoTreeItem*> _lists; - }; #endif //GEOTREEMODEL_H diff --git a/DataView/GeoTreeView.cpp b/DataView/GeoTreeView.cpp index b331b498dd13b21d7c6ad4026bce556076adc8f3..4a64a5bd7467ecfa1282e6a99ae27737fa474a0b 100644 --- a/DataView/GeoTreeView.cpp +++ b/DataView/GeoTreeView.cpp @@ -3,20 +3,18 @@ * 2011/02/07 KR Initial implementation */ -#include <iostream> #include <QFileDialog> #include <QMenu> +#include <iostream> -#include "GeoTreeView.h" -#include "GeoTreeModel.h" -#include "GeoTreeItem.h" #include "GeoObjectListItem.h" +#include "GeoTreeItem.h" +#include "GeoTreeModel.h" +#include "GeoTreeView.h" #include "OGSError.h" #include "XMLInterface.h" - - GeoTreeView::GeoTreeView(QWidget* parent) : QTreeView(parent) { // setContextMenuPolicy(Qt::CustomContextMenu); @@ -37,13 +35,15 @@ void GeoTreeView::on_Clicked(QModelIndex idx) qDebug("%d, %d",idx.parent().row(), idx.row()); } -void GeoTreeView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) +void GeoTreeView::selectionChanged( const QItemSelection &selected, + const QItemSelection &deselected ) { emit itemSelectionChanged(selected, deselected); return QTreeView::selectionChanged(selected, deselected); } -void GeoTreeView::selectionChangedFromOutside( const QItemSelection &selected, const QItemSelection &deselected ) +void GeoTreeView::selectionChangedFromOutside( const QItemSelection &selected, + const QItemSelection &deselected ) { QItemSelectionModel* selModel = this->selectionModel(); @@ -82,7 +82,8 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) if (list->getType() == GEOLIB::POLYLINE) { connectPlyAction = menu.addAction("Connect Polylines..."); - connect(connectPlyAction, SIGNAL(triggered()), this, SLOT(connectPolylines())); + connect(connectPlyAction, SIGNAL(triggered()), this, + SLOT(connectPolylines())); } menu.addSeparator(); QAction* removeAction = menu.addAction("Remove " + item->data(0).toString()); @@ -93,23 +94,23 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) { QString temp_name; QMenu menu; - /* - if (static_cast<GeoTreeModel*>(model())->objectFromIndex(index, temp_name)->type() == GEOLIB::POINT) - { - QAction* stratAction = menu.addAction("Display Stratigraphy..."); - QAction* exportAction = menu.addAction("Export to GMS..."); - connect(stratAction, SIGNAL(triggered()), this, SLOT(displayStratigraphy())); - connect(exportAction, SIGNAL(triggered()), this, SLOT(exportStation())); - menu.exec(event->globalPos()); - } - else - { - menu.addAction("View Information..."); - QAction* showDiagramAction = menu.addAction("View Diagram..."); - connect(showDiagramAction, SIGNAL(triggered()), this, SLOT(showDiagramPrefsDialog())); - menu.exec(event->globalPos()); - } - */ + /* + if (static_cast<GeoTreeModel*>(model())->objectFromIndex(index, temp_name)->type() == GEOLIB::POINT) + { + QAction* stratAction = menu.addAction("Display Stratigraphy..."); + QAction* exportAction = menu.addAction("Export to GMS..."); + connect(stratAction, SIGNAL(triggered()), this, SLOT(displayStratigraphy())); + connect(exportAction, SIGNAL(triggered()), this, SLOT(exportStation())); + menu.exec(event->globalPos()); + } + else + { + menu.addAction("View Information..."); + QAction* showDiagramAction = menu.addAction("View Diagram..."); + connect(showDiagramAction, SIGNAL(triggered()), this, SLOT(showDiagramPrefsDialog())); + menu.exec(event->globalPos()); + } + */ } } menu.exec(event->globalPos()); @@ -117,32 +118,41 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) void GeoTreeView::addFEMConditions() { - TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem(this->selectionModel()->currentIndex()); + TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( + this->selectionModel()->currentIndex()); emit loadFEMCondFileRequested(item->data(0).toString().toStdString()); } void GeoTreeView::writeToFile() const { - TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem(this->selectionModel()->currentIndex()); + TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( + this->selectionModel()->currentIndex()); QString gliName = item->data(0).toString(); - QString fileName = QFileDialog::getSaveFileName(NULL, "Save geometry as", gliName, "GeoSys mesh file (*.gml)"); - if (!fileName.isEmpty()) { + QString fileName = QFileDialog::getSaveFileName(NULL, + "Save geometry as", + gliName, + "GeoSys mesh file (*.gml)"); + if (!fileName.isEmpty()) emit saveToFileRequested(gliName, fileName); - } } void GeoTreeView::removeList() { - TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem(this->selectionModel()->currentIndex()); + TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( + this->selectionModel()->currentIndex()); GeoObjectListItem* list = dynamic_cast<GeoObjectListItem*>(item); - if (list) emit listRemoved((item->parentItem()->data(0).toString()).toStdString(), list->getType()); - else emit listRemoved((item->data(0).toString()).toStdString(), GEOLIB::INVALID); + if (list) + emit listRemoved((item->parentItem()->data( + 0).toString()).toStdString(), list->getType()); + else + emit listRemoved((item->data(0).toString()).toStdString(), GEOLIB::INVALID); } void GeoTreeView::connectPolylines() { - TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem(this->selectionModel()->currentIndex())->parentItem(); + TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( + this->selectionModel()->currentIndex())->parentItem(); emit requestLineEditDialog(item->data(0).toString().toStdString()); } diff --git a/DataView/GeoTreeView.h b/DataView/GeoTreeView.h index fae45c90647cdb26fff2231c86407e25fcb211f0..fc75c36f5c82ee70cf1fe520df649536e221c90c 100644 --- a/DataView/GeoTreeView.h +++ b/DataView/GeoTreeView.h @@ -6,12 +6,12 @@ #ifndef GEOTREEVIEW_H #define GEOTREEVIEW_H -#include <QTreeView> -#include <QContextMenuEvent> #include "GeoType.h" +#include <QContextMenuEvent> +#include <QTreeView> /** - * \brief A view for the GeoTreeModel + * \brief A view for the GeoTreeModel * \sa GeoTreeModel, GeoTreeItem */ class GeoTreeView : public QTreeView @@ -30,7 +30,8 @@ protected slots: void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); /// Instructions if the selection of items in the view has changed by events outside the view (i.e. by actions made in the visualisation). - void selectionChangedFromOutside(const QItemSelection &selected, const QItemSelection &deselected); + void selectionChangedFromOutside(const QItemSelection &selected, + const QItemSelection &deselected); private: /// Actions to be taken after a right mouse click is performed in the station view. @@ -46,9 +47,10 @@ private slots: void writeToFile() const; /// Removes a whole geometry or parts of it. void removeList(); - + signals: - void itemSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected); + void itemSelectionChanged(const QItemSelection & selected, + const QItemSelection & deselected); void listRemoved(std::string name, GEOLIB::GEOTYPE); void loadFEMCondFileRequested(std::string); void saveToFileRequested(QString, QString) const; diff --git a/DataView/LineEditDialog.cpp b/DataView/LineEditDialog.cpp index 95b5052d54203690de47741ebb0c96cc3636384c..a063e471a8821fd6a05762fb678dd93942d6d20b 100644 --- a/DataView/LineEditDialog.cpp +++ b/DataView/LineEditDialog.cpp @@ -3,14 +3,14 @@ * 2010/12/09 KR Initial implementation */ -#include "OGSError.h" #include "LineEditDialog.h" +#include "OGSError.h" #include <QStringList> #include <QStringListModel> - LineEditDialog::LineEditDialog(const GEOLIB::PolylineVec &ply_vec, QDialog* parent) -: QDialog(parent), _allPly(new QStringListModel), _selPly(new QStringListModel), _geoName(ply_vec.getName()) + : QDialog(parent), _allPly(new QStringListModel), _selPly(new QStringListModel), + _geoName(ply_vec.getName()) { setupUi(this); @@ -18,7 +18,7 @@ LineEditDialog::LineEditDialog(const GEOLIB::PolylineVec &ply_vec, QDialog* pare size_t nPly(ply_vec.size()); QStringList list; - for (size_t i=0; i<nPly; i++) + for (size_t i = 0; i < nPly; i++) { std::string ply_name(""); ply_vec.getNameOfElementByID(i, ply_name); @@ -72,8 +72,15 @@ void LineEditDialog::accept() { std::string prox_string = this->proximityEdit->text().toStdString(); double prox = (prox_string.empty()) ? 0.0 : strtod( prox_string.c_str(), 0 ); - std::string ply_name = (plyNameEdit->text().toStdString().empty()) ? "" : plyNameEdit->text().toStdString(); - emit connectPolylines(_geoName, selectedIndeces, prox, ply_name, this->closePlyCheckBox->isChecked(), this->createSfcCheckBox->isChecked()); + std::string ply_name = + (plyNameEdit->text().toStdString().empty()) ? "" : plyNameEdit->text(). + toStdString(); + emit connectPolylines(_geoName, + selectedIndeces, + prox, + ply_name, + this->closePlyCheckBox->isChecked(), + this->createSfcCheckBox->isChecked()); this->done(QDialog::Accepted); } else @@ -90,7 +97,7 @@ std::vector<size_t> LineEditDialog::getSelectedIndeces(QStringList list) std::vector<size_t> indexList; for (QStringList::iterator it = list.begin(); it != list.end(); ++it) { - QString s = it->mid(5, it->indexOf(" ")-5); + QString s = it->mid(5, it->indexOf(" ") - 5); indexList.push_back(atoi(s.toStdString().c_str())); } return indexList; diff --git a/DataView/LineEditDialog.h b/DataView/LineEditDialog.h index e8c2886c18d89ad3d1efefe505c6829f15278eed..ec709b743ad7d6377d3fedbf8cd564b29c94ea03 100644 --- a/DataView/LineEditDialog.h +++ b/DataView/LineEditDialog.h @@ -6,8 +6,8 @@ #ifndef LINEEDITDIALOG_H #define LINEEDITDIALOG_H -#include <QtGui/QMainWindow> #include "ui_LineEdit.h" +#include <QtGui/QMainWindow> #include "PolylineVec.h" @@ -15,7 +15,7 @@ class QStringListModel; /** * \brief A dialog window for manipulation of polylines. - * Currently included functionality is the concatenation of polylines + * Currently included functionality is the concatenation of polylines * as well as creating polygons or surfaces from polylines. */ class LineEditDialog : public QDialog, private Ui_LineEdit @@ -26,8 +26,6 @@ public: LineEditDialog(const GEOLIB::PolylineVec &ply_vec, QDialog* parent = 0); ~LineEditDialog(void); - - private: std::vector<size_t> getSelectedIndeces(QStringList list); @@ -35,7 +33,6 @@ private: QStringListModel* _selPly; std::string _geoName; - private slots: /// Instructions when polylines are selected. void on_selectPlyButton_pressed(); @@ -50,9 +47,13 @@ private slots: void reject(); signals: - void connectPolylines(const std::string&, std::vector<size_t>, double, std::string, bool, bool); + void connectPolylines(const std::string&, + std::vector<size_t>, + double, + std::string, + bool, + bool); void triangulateSurface(const GEOLIB::Polyline); - }; #endif //LINEEDITDIALOG_H diff --git a/DataView/ListPropertiesDialog.cpp b/DataView/ListPropertiesDialog.cpp index 2c39bbbb9268a81424cefe97ba5c028fe6961bdf..8f1027cc5eb0c8b6e3b484cb3a5562ae72bdd7d9 100644 --- a/DataView/ListPropertiesDialog.cpp +++ b/DataView/ListPropertiesDialog.cpp @@ -3,30 +3,30 @@ * KR Initial implementation */ -#include <QLabel> -#include <QLineEdit> -#include <QDialogButtonBox> -#include <QGridLayout> -#include "ListPropertiesDialog.h" #include "DateTools.h" +#include "ListPropertiesDialog.h" #include "PropertyBounds.h" #include "StringTools.h" - +#include <QDialogButtonBox> +#include <QGridLayout> +#include <QLabel> +#include <QLineEdit> /** * Creates a new dialog. */ -ListPropertiesDialog::ListPropertiesDialog(std::string listName, GEOModels* geoModels, QDialog* parent) : +ListPropertiesDialog::ListPropertiesDialog(std::string listName, + GEOModels* geoModels, + QDialog* parent) : QDialog(parent), _listName(listName), _geoModels(geoModels) { setupDialog(); show(); } - ListPropertiesDialog::~ListPropertiesDialog() { - for (size_t i=0; i<_propLabel.size(); i++) + for (size_t i = 0; i < _propLabel.size(); i++) { delete _propLabel[i]; delete _minValue[i]; @@ -36,22 +36,23 @@ ListPropertiesDialog::~ListPropertiesDialog() delete _buttonBox; } - /// Constructs a dialog window based on the properties retrieved from the station objects void ListPropertiesDialog::setupDialog() { - int i=0; - double minVal=0, maxVal=0; + int i = 0; + double minVal = 0, maxVal = 0; - const std::vector<GEOLIB::Point*> *stations ( _geoModels->getStationVec(_listName)); + const std::vector<GEOLIB::Point*>* stations ( _geoModels->getStationVec(_listName)); - std::map<std::string, double> properties = static_cast<GEOLIB::Station*>((*stations)[0])->getProperties(); + std::map<std::string, + double> properties = static_cast<GEOLIB::Station*>((*stations)[0])->getProperties(); QGridLayout* layout = new QGridLayout; setWindowTitle("List Properties"); - for(std::map<std::string, double>::const_iterator it = properties.begin(); it != properties.end(); ++it) - { + for(std::map<std::string, double>::const_iterator it = properties.begin(); + it != properties.end(); ++it) + { QLabel* _prop = new QLabel(this); QLineEdit* _min = new QLineEdit(this); QLineEdit* _max = new QLineEdit(this); @@ -60,19 +61,21 @@ void ListPropertiesDialog::setupDialog() if (getPropertyBounds(stations, it->first, minVal, maxVal)) { _min->setText(QString::number(minVal, 'f')); - if (_prop->text().compare("date")==0) _min->setText(QString::fromStdString(date2string(minVal))); + if (_prop->text().compare("date") == 0) + _min->setText(QString::fromStdString(date2string(minVal))); _max->setText(QString::number(maxVal, 'f')); - if (_prop->text().compare("date")==0) _max->setText(QString::fromStdString(date2string(maxVal))); + if (_prop->text().compare("date") == 0) + _max->setText(QString::fromStdString(date2string(maxVal))); } _propLabel.push_back(_prop); _minValue.push_back(_min); _maxValue.push_back(_max); - layout->addWidget( _propLabel[i] , i, 0 ); - layout->addWidget( _minValue[i] , i, 1 ); - layout->addWidget( _maxValue[i] , i, 2 ); + layout->addWidget( _propLabel[i], i, 0 ); + layout->addWidget( _minValue[i], i, 1 ); + layout->addWidget( _maxValue[i], i, 2 ); i++; } @@ -80,25 +83,31 @@ void ListPropertiesDialog::setupDialog() connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - layout->addWidget(_buttonBox, i+1, 1, 1, 2 ); + layout->addWidget(_buttonBox, i + 1, 1, 1, 2 ); setLayout(layout); } -int ListPropertiesDialog::getPropertyBounds(const std::vector<GEOLIB::Point*> *stations, const std::string &prop, double &minVal, double &maxVal) +int ListPropertiesDialog::getPropertyBounds(const std::vector<GEOLIB::Point*>* stations, + const std::string &prop, + double &minVal, + double &maxVal) { if (!stations->empty()) { - std::map<std::string, double> properties (static_cast<GEOLIB::Station*>((*stations)[0])->getProperties()); + std::map<std::string, double> properties ( + static_cast<GEOLIB::Station*>((*stations)[0])->getProperties()); minVal = properties[prop]; maxVal = properties[prop]; size_t size = stations->size(); - for (size_t i=1; i<size; i++) + for (size_t i = 1; i < size; i++) { properties = static_cast<GEOLIB::Station*>((*stations)[i])->getProperties(); - if (minVal > properties[prop]) minVal = properties[prop]; - if (maxVal < properties[prop]) maxVal = properties[prop]; + if (minVal > properties[prop]) + minVal = properties[prop]; + if (maxVal < properties[prop]) + maxVal = properties[prop]; } return 1; } @@ -112,17 +121,20 @@ void ListPropertiesDialog::accept() int noProp = _propLabel.size(); double minVal, maxVal; - for (int i=0; i<noProp; i++) + for (int i = 0; i < noProp; i++) { - if (_propLabel[i]->text().compare("date")==0) + if (_propLabel[i]->text().compare("date") == 0) { minVal = xmlDate2double(_minValue[i]->text().toStdString()); maxVal = xmlDate2double(_maxValue[i]->text().toStdString()); } else { - minVal = strtod(replaceString(",", ".", _minValue[i]->text().toStdString()).c_str() ,0); - maxVal = strtod(replaceString(",", ".", _maxValue[i]->text().toStdString()).c_str(), 0); + minVal = strtod(replaceString(",", ".", + _minValue[i]->text().toStdString()).c_str(),0); + maxVal = strtod(replaceString(",", ".", + _maxValue[i]->text().toStdString()).c_str(), + 0); } PropertyBounds b(_propLabel[i]->text().toStdString(), minVal, maxVal); bounds.push_back(b); diff --git a/DataView/ListPropertiesDialog.h b/DataView/ListPropertiesDialog.h index 7bd5ce488aae8df5081cd185e6af8ae5b0600959..e3e306a79df63f80d367aeaf97b01b7a1cc8af3f 100644 --- a/DataView/ListPropertiesDialog.h +++ b/DataView/ListPropertiesDialog.h @@ -6,12 +6,11 @@ #ifndef LISTPROPERTIESDIALOG_H #define LISTPROPERTIESDIALOG_H -#include <vector> -#include <QtGui/QMainWindow> -#include <QDialog> #include "GEOModels.h" #include "Station.h" - +#include <QDialog> +#include <QtGui/QMainWindow> +#include <vector> class QLabel; class QLineEdit; @@ -32,13 +31,16 @@ public: ~ListPropertiesDialog(); private: - int getPropertyBounds(const std::vector<GEOLIB::Point*> *stations, const std::string &prop, double &minVal, double &maxVal); + int getPropertyBounds(const std::vector<GEOLIB::Point*>* stations, + const std::string &prop, + double &minVal, + double &maxVal); void setupDialog(); - QDialogButtonBox* _buttonBox; /// The buttons used in this dialog. - std::vector<QLabel*> _propLabel; /// The names of the properties. - std::vector<QLineEdit*> _minValue; /// The minimum values of each property. - std::vector<QLineEdit*> _maxValue; /// The maximum values of each property. + QDialogButtonBox* _buttonBox; /// The buttons used in this dialog. + std::vector<QLabel*> _propLabel; /// The names of the properties. + std::vector<QLineEdit*> _minValue; /// The minimum values of each property. + std::vector<QLineEdit*> _maxValue; /// The maximum values of each property. std::string _listName; GEOModels* _geoModels; diff --git a/DataView/ModelTreeItem.cpp b/DataView/ModelTreeItem.cpp index 6bca87d4eba7ffed912c68a365518346ef89122e..039d6705a86bfa442c981082aaebb2cbd9628432 100644 --- a/DataView/ModelTreeItem.cpp +++ b/DataView/ModelTreeItem.cpp @@ -5,8 +5,8 @@ #include "ModelTreeItem.h" -ModelTreeItem::ModelTreeItem(const QList<QVariant> &data, TreeItem *parent, BaseItem* item) -:TreeItem(data, parent), _item(item) +ModelTreeItem::ModelTreeItem(const QList<QVariant> &data, TreeItem* parent, BaseItem* item) + : TreeItem(data, parent), _item(item) { } @@ -17,4 +17,3 @@ BaseItem* ModelTreeItem::getItem() const return NULL; } - diff --git a/DataView/ModelTreeItem.h b/DataView/ModelTreeItem.h index 304ef3810968143230b068f02cb1262dcae24867..9f149aefc6174a34934cb0ae8474dee819c9ff90 100644 --- a/DataView/ModelTreeItem.h +++ b/DataView/ModelTreeItem.h @@ -6,9 +6,9 @@ #ifndef QMODELTREEITEM_H #define QMODELTREEITEM_H -#include "TreeItem.h" -#include "Station.h" #include "BaseItem.h" +#include "Station.h" +#include "TreeItem.h" /** * \brief A TreeItem containing some additional information used in the StationModel. @@ -24,21 +24,20 @@ public: * \param parent The parent item in the tree * \param item The ModelItem-object */ - ModelTreeItem(const QList<QVariant> &data, TreeItem *parent, BaseItem* item = NULL); - ~ModelTreeItem() { delete _item; }; + ModelTreeItem(const QList<QVariant> &data, TreeItem* parent, BaseItem* item = NULL); + ~ModelTreeItem() { delete _item; } /// Returns the station object from which this item has been constructed - GEOLIB::Station* getStation() { return _stn; }; - + GEOLIB::Station* getStation() { return _stn; } + /// Returns the BaseItem associated with this item BaseItem* getItem() const; /// Associates a station object with this item - void setStation(GEOLIB::Station* stn) { _stn = stn; }; + void setStation(GEOLIB::Station* stn) { _stn = stn; } /// Associates a BaseItem with this item - void setItem( BaseItem* item ) { _item = item; }; - + void setItem( BaseItem* item ) { _item = item; } private: BaseItem* _item; diff --git a/DataView/MshEditDialog.cpp b/DataView/MshEditDialog.cpp index 70e5d1b77d4240f603096e062b0054cc5721ac7e..43804784d9b7c4181c364d8f827658a4d96cc7a9 100644 --- a/DataView/MshEditDialog.cpp +++ b/DataView/MshEditDialog.cpp @@ -4,17 +4,17 @@ */ #include "MshEditDialog.h" +#include "OGSError.h" #include "StringTools.h" #include "msh_mesh.h" -#include "OGSError.h" +#include <QCheckBox> #include <QFileDialog> #include <QPushButton> #include <QSettings> -#include <QCheckBox> -MshEditDialog::MshEditDialog(const MeshLib::CFEMesh* mesh, QDialog* parent) -: QDialog(parent), _msh(mesh), _noDataDeleteBox(NULL) +MshEditDialog::MshEditDialog(const MeshLib::CFEMesh* mesh, QDialog* parent) + : QDialog(parent), _msh(mesh), _noDataDeleteBox(NULL) { setupUi(this); @@ -25,9 +25,10 @@ MshEditDialog::MshEditDialog(const MeshLib::CFEMesh* mesh, QDialog* parent) this->gridLayoutLayerMapping->setColumnStretch(2, 10); size_t nLayers = mesh->getNumberOfMeshLayers(); - if (nLayers==0) nLayers=1; // adapt to old files where 2D meshes officially had "0" layers which makes no sense + if (nLayers == 0) + nLayers = 1; // adapt to old files where 2D meshes officially had "0" layers which makes no sense - for (size_t i=0; i<nLayers; i++) + for (size_t i = 0; i < nLayers; i++) { QString text = (i) ? "Layer" + QString::number(i) : "Surface"; QLabel* label = new QLabel(text); @@ -48,19 +49,18 @@ MshEditDialog::MshEditDialog(const MeshLib::CFEMesh* mesh, QDialog* parent) _noDataDeleteBox = new QCheckBox("Remove mesh nodes at NoData values"); _noDataDeleteBox->setChecked(false); _noDataDeleteBox->setEnabled(false); - if (nLayers==1) + if (nLayers == 1) { _noDataDeleteBox->setEnabled(true); this->gridLayoutLayerMapping->addWidget(_noDataDeleteBox, 2, 1); } - } MshEditDialog::~MshEditDialog() { delete _noDataDeleteBox; - for (int i=0; i<_labels.size(); i++) + for (int i = 0; i < _labels.size(); i++) { delete _labels[i]; delete _edits[i]; @@ -72,50 +72,59 @@ void MshEditDialog::accept() { int tabIndex = this->tabWidget->currentIndex(); - if (tabIndex>=0) + if (tabIndex >= 0) { MeshLib::CFEMesh* new_mesh = NULL; switch (tabIndex) { - case 0: - { - int nLayers = atoi(this->editNLayers->text().toStdString().c_str()); - double thickness = strtod(replaceString(",", ".", this->editThickness->text().toStdString()).c_str(), 0); + case 0: + { + int nLayers = atoi(this->editNLayers->text().toStdString().c_str()); + double thickness = + strtod(replaceString(",", ".", + this->editThickness->text().toStdString()). + c_str(), 0); + + new_mesh = MshLayerMapper::CreateLayers(_msh, nLayers, thickness); + break; + } + case 1: + { + size_t nLayers = _msh->getNumberOfMeshLayers(); + if (nLayers == 0) + nLayers = 1; // adapt to old files where 2D meshes officially had "0" layers which makes no sense - new_mesh = MshLayerMapper::CreateLayers(_msh, nLayers, thickness); - break; - } - case 1: + for (size_t i = 0; i < nLayers; i++) { - size_t nLayers = _msh->getNumberOfMeshLayers(); - if (nLayers==0) nLayers=1; // adapt to old files where 2D meshes officially had "0" layers which makes no sense - - for (size_t i=0; i<nLayers; i++) - { - std::string imgPath ( this->_edits[i]->text().toStdString() ); - if (!imgPath.empty()) - { - new_mesh = MshLayerMapper::LayerMapping(_msh, imgPath, nLayers, i, _noDataDeleteBox->isChecked()); - } - } - //if (nLayers>1) MshLayerMapper::CheckLayerMapping(new_mesh, nLayers, 1); //TODO !!! - break; + std::string imgPath ( this->_edits[i]->text().toStdString() ); + if (!imgPath.empty()) + new_mesh = MshLayerMapper::LayerMapping( + _msh, + imgPath, + nLayers, + i, + _noDataDeleteBox-> + isChecked()); } - default: - std::cout << "Error in MshEditDialog::accept() - No instructions found for selected tab..." << std::endl; + //if (nLayers>1) MshLayerMapper::CheckLayerMapping(new_mesh, nLayers, 1); //TODO !!! + break; } - if (new_mesh) + default: + std::cout << + "Error in MshEditDialog::accept() - No instructions found for selected tab..." + << std::endl; + } + if (new_mesh) { std::string mshname("NewMesh"); emit mshEditFinished(new_mesh, mshname); } - else OGSError::box("Error creating mesh"); + else + OGSError::box("Error creating mesh"); } else - { std::cout << "Error in MshEditDialog::accept() - No tab selected... " << std::endl; - } this->done(QDialog::Accepted); } @@ -128,10 +137,12 @@ void MshEditDialog::getFileName() { QPushButton* button = dynamic_cast<QPushButton*>(this->sender()); QSettings settings("UFZ", "OpenGeoSys-5"); - QString filename = QFileDialog::getOpenFileName(this, - "Select raster file to open", - settings.value("lastOpenedFileDirectory").toString(), - "ASCII raster files (*.asc);;All files (* *.*)"); + QString filename = QFileDialog::getOpenFileName(this, + "Select raster file to open", + settings.value( + "lastOpenedFileDirectory").toString( + ), + "ASCII raster files (*.asc);;All files (* *.*)"); _fileButtonMap[button]->setText(filename); QDir dir = QDir(filename); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); diff --git a/DataView/MshEditDialog.h b/DataView/MshEditDialog.h index 772c37aeea24aa69b6509c830c485707a9b5ef3d..3b115a02bfd1a250b01da878f5add1da5d257bf3 100644 --- a/DataView/MshEditDialog.h +++ b/DataView/MshEditDialog.h @@ -6,8 +6,8 @@ #ifndef MSHEDITDIALOG_H #define MSHEDITDIALOG_H -#include <QtGui/QMainWindow> #include "ui_MshEdit.h" +#include <QtGui/QMainWindow> #include "MshLayerMapper.h" @@ -16,7 +16,7 @@ class QCheckBox; namespace MeshLib { - class CFEMesh; +class CFEMesh; } /** @@ -30,8 +30,6 @@ public: MshEditDialog(const MeshLib::CFEMesh* mesh, QDialog* parent = 0); ~MshEditDialog(void); - - private: const MeshLib::CFEMesh* _msh; QVector<QLabel*> _labels; @@ -40,7 +38,6 @@ private: QVector<QPushButton*> _buttons; QCheckBox* _noDataDeleteBox; - private slots: void getFileName(); @@ -52,7 +49,6 @@ private slots: signals: void mshEditFinished(MeshLib::CFEMesh*, std::string&); - }; #endif //MSHEDITDIALOG_H diff --git a/DataView/MshItem.cpp b/DataView/MshItem.cpp index 23bfb5efef2181101639f6129c2bac2269362889..d34b0b0ad0414993010f03baed7ed630b0744927 100644 --- a/DataView/MshItem.cpp +++ b/DataView/MshItem.cpp @@ -3,20 +3,18 @@ * 17/05/2010 KR Initial implementation */ -#include "MshItem.h" #include "GridAdapter.h" +#include "MshItem.h" #include "VtkMeshSource.h" - - /** * Constructor. * \param data The data associated with each column * \param parent The parent item in the tree * \param grid The mesh associated with this item */ -MshItem::MshItem(const QList<QVariant> &data, TreeItem *parent, GridAdapter* grid) -: TreeItem(data, parent) +MshItem::MshItem(const QList<QVariant> &data, TreeItem* parent, GridAdapter* grid) + : TreeItem(data, parent) { _meshSource = VtkMeshSource::New(); _meshSource->SetGrid(grid); diff --git a/DataView/MshItem.h b/DataView/MshItem.h index e0d2170c0e4722f6ebc9730d06151cdfb70d0aa8..548ee347b47e757ff8c530207970a64d409bd859 100644 --- a/DataView/MshItem.h +++ b/DataView/MshItem.h @@ -18,17 +18,15 @@ class VtkMeshSource; */ class MshItem : public TreeItem { - public: /// Constructor, automatically generates VTK object of the given mesh. - MshItem(const QList<QVariant> &data, TreeItem *parent, GridAdapter* grid); + MshItem(const QList<QVariant> &data, TreeItem* parent, GridAdapter* grid); ~MshItem(); /// Returns the mesh as a GridAdapter. - const GridAdapter* getGrid() const { return this->_meshSource->GetGrid(); }; + const GridAdapter* getGrid() const { return this->_meshSource->GetGrid(); } /// Returns the VTK object. - VtkMeshSource* vtkSource() const { return _meshSource; }; - + VtkMeshSource* vtkSource() const { return _meshSource; } private: VtkMeshSource* _meshSource; diff --git a/DataView/MshLayerMapper.cpp b/DataView/MshLayerMapper.cpp index 577c70a1050477886cdcfc9ee2cd05a081f36fe4..5322f611425a82425f76bc6f33a6a700937e6f5c 100644 --- a/DataView/MshLayerMapper.cpp +++ b/DataView/MshLayerMapper.cpp @@ -7,66 +7,78 @@ #include "OGSRaster.h" #include "MshEditor.h" -#include "msh_mesh.h" #include "matrix_class.h" +#include "msh_mesh.h" #include <QImage> - -MeshLib::CFEMesh* MshLayerMapper::CreateLayers(const MeshLib::CFEMesh* mesh, size_t nLayers, double thickness) +MeshLib::CFEMesh* MshLayerMapper::CreateLayers(const MeshLib::CFEMesh* mesh, + size_t nLayers, + double thickness) { if (nLayers < 1 || thickness <= 0) { - std::cout << "Error in MshLayerMapper::CreateLayers() - Invalid parameter: nLayers > 0 and thickness > 0 are required." << std::endl; + std::cout << + "Error in MshLayerMapper::CreateLayers() - Invalid parameter: nLayers > 0 and thickness > 0 are required." + << std::endl; return NULL; } /* - if ((mesh->ele_vector[0]->GetElementType() != MshElemType::TRIANGLE) && (mesh->ele_vector[0]->GetElementType() != MshElemType::QUAD)) // check if mesh elements are triangles or quads - { - std::cout << "Error in MshLayerMapper::CreateLayers() - Method can only handle triangle- or quad-meshes... " << std::endl; - return NULL; - } -*/ + if ((mesh->ele_vector[0]->GetElementType() != MshElemType::TRIANGLE) && (mesh->ele_vector[0]->GetElementType() != MshElemType::QUAD)) // check if mesh elements are triangles or quads + { + std::cout << "Error in MshLayerMapper::CreateLayers() - Method can only handle triangle- or quad-meshes... " << std::endl; + return NULL; + } + */ MeshLib::CFEMesh* new_mesh ( new MeshLib::CFEMesh() ); size_t nNodes = mesh->nod_vector.size(); size_t nElems = mesh->ele_vector.size(); - for (size_t layer_id=0; layer_id<nLayers; layer_id++) + for (size_t layer_id = 0; layer_id < nLayers; layer_id++) { // add nodes for new layer - size_t node_offset ( nNodes*layer_id ); + size_t node_offset ( nNodes * layer_id ); // TF unused variable double z_offset ( layer_id*thickness ); - for (size_t i=0; i<nNodes; i++) - { - new_mesh->nod_vector.push_back(new MeshLib::CNode( node_offset + i, mesh->nod_vector[i]->getData())); - } + for (size_t i = 0; i < nNodes; i++) + new_mesh->nod_vector.push_back(new MeshLib::CNode( node_offset + i, + mesh->nod_vector[i]-> + getData())); - if (layer_id>0) // starting with the 2nd layer prism (or hex) elements can be created + if (layer_id > 0) // starting with the 2nd layer prism (or hex) elements can be created { // create prism elements connecting the last layer with the current one - node_offset = (layer_id-1)*nNodes; - for (size_t i=0; i<nElems; i++) + node_offset = (layer_id - 1) * nNodes; + for (size_t i = 0; i < nElems; i++) { MeshLib::CElem* elem( new MeshLib::CElem() ); size_t nElemNodes = mesh->ele_vector[i]->nodes_index.Size(); - if (mesh->ele_vector[i]->GetElementType()==MshElemType::TRIANGLE) elem->setElementProperties(MshElemType::PRISM); // extrude triangles to prism - else if (mesh->ele_vector[i]->GetElementType()==MshElemType::QUAD) elem->setElementProperties(MshElemType::HEXAHEDRON); // extrude quads to hexes - else if (mesh->ele_vector[i]->GetElementType()==MshElemType::LINE) continue; // line elements are ignored and not duplicated + if (mesh->ele_vector[i]->GetElementType() == MshElemType::TRIANGLE) + elem->setElementProperties(MshElemType::PRISM); // extrude triangles to prism + else if (mesh->ele_vector[i]->GetElementType() == MshElemType::QUAD) + elem->setElementProperties(MshElemType::HEXAHEDRON); // extrude quads to hexes + else if (mesh->ele_vector[i]->GetElementType() == MshElemType::LINE) + continue; // line elements are ignored and not duplicated else { - std::cout << "Error in MshLayerMapper::CreateLayers() - Method can only handle 2D mesh elements ..." << std::endl; - std::cout << "Element " << i << " is of type \"" << MshElemType2String(mesh->ele_vector[i]->GetElementType()) << "\"." << std::endl; + std::cout << + "Error in MshLayerMapper::CreateLayers() - Method can only handle 2D mesh elements ..." + << std::endl; + std::cout << "Element " << i << " is of type \"" << + MshElemType2String(mesh->ele_vector[i]->GetElementType()) + << + "\"." << std::endl; delete new_mesh; return NULL; } - elem->SetPatchIndex(layer_id-1); - elem->SetNodesNumber(2*nElemNodes); - elem->nodes_index.resize(2*nElemNodes); - for (size_t j=0; j<nElemNodes; j++) + elem->SetPatchIndex(layer_id - 1); + elem->SetNodesNumber(2 * nElemNodes); + elem->nodes_index.resize(2 * nElemNodes); + for (size_t j = 0; j < nElemNodes; j++) { long idx = mesh->ele_vector[i]->GetNodeIndex(j); - elem->SetNodeIndex(j, node_offset+idx); - elem->SetNodeIndex(j+nElemNodes, node_offset+nNodes+idx); + elem->SetNodeIndex(j, node_offset + idx); + elem->SetNodeIndex(j + nElemNodes, + node_offset + nNodes + idx); } new_mesh->ele_vector.push_back(elem); } @@ -84,34 +96,43 @@ MeshLib::CFEMesh* MshLayerMapper::CreateLayers(const MeshLib::CFEMesh* mesh, siz } // KR, based on code by WW -MeshLib::CFEMesh* MshLayerMapper::LayerMapping(const MeshLib::CFEMesh* msh, const std::string &rasterfile, const size_t nLayers, const size_t layer_id, bool removeNoDataValues) +MeshLib::CFEMesh* MshLayerMapper::LayerMapping(const MeshLib::CFEMesh* msh, + const std::string &rasterfile, + const size_t nLayers, + const size_t layer_id, + bool removeNoDataValues) { - if (msh == NULL) return NULL; + if (msh == NULL) + return NULL; if (msh->getNumberOfMeshLayers() >= layer_id) { - if (msh==NULL) + if (msh == NULL) { - std::cout << "Error in MshLayerMapper::LayerMapping() - Passed Mesh is NULL..." << std::endl; + std::cout << + "Error in MshLayerMapper::LayerMapping() - Passed Mesh is NULL..." << + std::endl; return NULL; } MeshLib::CFEMesh* new_mesh( new MeshLib::CFEMesh(*msh) ); double x0(0), y0(0), delta(1); size_t width(1), height(1); - double* elevation = OGSRaster::loadDataFromASC(QString::fromStdString(rasterfile), x0, y0, width, height, delta); + double* elevation = OGSRaster::loadDataFromASC(QString::fromStdString( + rasterfile), x0, y0, width, + height, delta); - if (elevation==NULL) + if (elevation == NULL) { - delete []elevation; + delete [] elevation; return NULL; } - std::pair<double, double> xDim(x0, x0+width*delta); // extension in x-dimension - std::pair<double, double> yDim(y0, y0+height*delta); // extension in y-dimension + std::pair<double, double> xDim(x0, x0 + width * delta); // extension in x-dimension + std::pair<double, double> yDim(y0, y0 + height * delta); // extension in y-dimension if (!meshFitsImage(new_mesh, xDim, yDim)) { - delete []elevation; + delete [] elevation; return NULL; } @@ -127,44 +148,48 @@ MeshLib::CFEMesh* MshLayerMapper::LayerMapping(const MeshLib::CFEMesh* msh, cons std::vector<size_t> noData_nodes; - for(size_t i=firstNode; i<lastNode; i++) + for(size_t i = firstNode; i < lastNode; i++) { - size_t xPos (static_cast<size_t>(floor((msh->nod_vector[i]->getData()[0] - xDim.first) / delta))); - size_t yPos (static_cast<size_t>(floor((msh->nod_vector[i]->getData()[1] - yDim.first) / delta))); + size_t xPos (static_cast<size_t>(floor( + (msh->nod_vector[i]->getData()[0] + - xDim.first) / delta))); + size_t yPos (static_cast<size_t>(floor( + (msh->nod_vector[i]->getData()[1] + - yDim.first) / delta))); - locX[0] = xDim.first+xPos*delta; - locY[0] = yDim.first+yPos*delta; - locZ[0] = elevation[yPos*width+xPos]; + locX[0] = xDim.first + xPos * delta; + locY[0] = yDim.first + yPos * delta; + locZ[0] = elevation[yPos * width + xPos]; - locX[1] = xDim.first+(xPos+1)*delta; - locY[1] = yDim.first+yPos*delta; - locZ[1] = elevation[yPos*width+(xPos+1)]; + locX[1] = xDim.first + (xPos + 1) * delta; + locY[1] = yDim.first + yPos * delta; + locZ[1] = elevation[yPos * width + (xPos + 1)]; - locX[2] = xDim.first+(xPos+1)*delta; - locY[2] = yDim.first+(yPos+1)*delta; - locZ[2] = elevation[(yPos+1)*width+(xPos+1)]; + locX[2] = xDim.first + (xPos + 1) * delta; + locY[2] = yDim.first + (yPos + 1) * delta; + locZ[2] = elevation[(yPos + 1) * width + (xPos + 1)]; - locX[3] = xDim.first+xPos*delta; - locY[3] = yDim.first+(yPos+1)*delta; - locZ[3] = elevation[(yPos+1)*width+xPos]; + locX[3] = xDim.first + xPos * delta; + locY[3] = yDim.first + (yPos + 1) * delta; + locZ[3] = elevation[(yPos + 1) * width + xPos]; bool noData(false); - for(size_t j=0; j<4; j++) - { - if(fabs(locZ[j]+9999)<std::numeric_limits<double>::min()) noData = true; - } + for(size_t j = 0; j < 4; j++) + if(fabs(locZ[j] + 9999) < std::numeric_limits<double>::min()) + noData = true; if(!noData) { - // Interpolate + // Interpolate double ome[4]; - double const*const coords (msh->nod_vector[i]->getData()); - double xi = 2.0*(coords[0]-0.5*(locX[0]+locX[1]))/delta; - double eta = 2.0*(coords[1]-0.5*(locY[1]+locY[2]))/delta; + double const* const coords (msh->nod_vector[i]->getData()); + double xi = 2.0 * (coords[0] - 0.5 * (locX[0] + locX[1])) / delta; + double eta = 2.0 * (coords[1] - 0.5 * (locY[1] + locY[2])) / delta; MPhi2D(ome, xi, eta); double z(0.0); - for(size_t j=0; j<4; j++) z += ome[j]*locZ[j]; + for(size_t j = 0; j < 4; j++) + z += ome[j] * locZ[j]; new_mesh->nod_vector[i]->SetZ(z); new_mesh->nod_vector[i]->SetMark(true); } @@ -179,10 +204,13 @@ MeshLib::CFEMesh* MshLayerMapper::LayerMapping(const MeshLib::CFEMesh* msh, cons if ((nLayers == 1) && removeNoDataValues) { - if (noData_nodes.size() < (new_mesh->nod_vector.size()-2)) + if (noData_nodes.size() < (new_mesh->nod_vector.size() - 2)) { - std::cout << "Warning: Removing " << noData_nodes.size() << " mesh nodes at NoData values ... " << std::endl; - MeshLib::CFEMesh* red_mesh = MshEditor::removeMeshNodes(new_mesh, noData_nodes); + std::cout << "Warning: Removing " << noData_nodes.size() << + " mesh nodes at NoData values ... " << std::endl; + MeshLib::CFEMesh* red_mesh = MshEditor::removeMeshNodes( + new_mesh, + noData_nodes); if (!new_mesh->ele_vector.empty()) { delete new_mesh; @@ -193,7 +221,6 @@ MeshLib::CFEMesh* MshLayerMapper::LayerMapping(const MeshLib::CFEMesh* msh, cons delete red_mesh; std::cout << "Too many NoData values..." << std::endl; } - } else std::cout << "Too many NoData values..." << std::endl; @@ -202,18 +229,20 @@ MeshLib::CFEMesh* MshLayerMapper::LayerMapping(const MeshLib::CFEMesh* msh, cons new_mesh->ConstructGrid(); new_mesh->FillTransformMatrix(); - delete []elevation; + delete [] elevation; return new_mesh; } else - { - std::cout << "Error in MshLayerMapper::LayerMapping() - Mesh has only " << msh->getNumberOfMeshLayers() << " Layers, cannot assign layer " << layer_id << "..." << std::endl; - } + std::cout << "Error in MshLayerMapper::LayerMapping() - Mesh has only " << + msh->getNumberOfMeshLayers() << " Layers, cannot assign layer " << layer_id << + "..." << std::endl; return NULL; } // KR, based on code by WW (Note: this method has not been tested yet and will probably fail miserably!) -bool MshLayerMapper::meshFitsImage(const MeshLib::CFEMesh* msh, const std::pair<double, double> &xDim, const std::pair<double, double> &yDim) +bool MshLayerMapper::meshFitsImage(const MeshLib::CFEMesh* msh, + const std::pair<double, double> &xDim, + const std::pair<double, double> &yDim) { double const* pnt (msh->nod_vector[0]->getData()); double xMin(pnt[0]); @@ -222,14 +251,18 @@ bool MshLayerMapper::meshFitsImage(const MeshLib::CFEMesh* msh, const std::pair< double yMax(pnt[1]); size_t nNodes = msh->nod_vector.size(); - for (size_t i=1; i<nNodes; i++) + for (size_t i = 1; i < nNodes; i++) { pnt = msh->nod_vector[i]->getData(); - if (xMin > pnt[0]) xMin = pnt[0]; - else if (xMax < pnt[0]) xMax = pnt[0]; - - if (yMin > pnt[1]) yMin = pnt[1]; - else if (yMax < pnt[1]) yMax = pnt[1]; + if (xMin > pnt[0]) + xMin = pnt[0]; + else if (xMax < pnt[0]) + xMax = pnt[0]; + + if (yMin > pnt[1]) + yMin = pnt[1]; + else if (yMax < pnt[1]) + yMax = pnt[1]; } if (xMin < xDim.first || xMax > xDim.second || yMin < yDim.first || yMax > yDim.second) @@ -244,54 +277,57 @@ void MshLayerMapper::CheckLayerMapping(MeshLib::CFEMesh* mesh, const size_t nLay { double ref_dep = -999999999.0; - size_t nNodesPerLayer = mesh->nod_vector.size() / (nLayers+1); + size_t nNodesPerLayer = mesh->nod_vector.size() / (nLayers + 1); //18.02.2009 WW if (integ) { - for (size_t i=0; i<nNodesPerLayer; i++) - { - for (size_t k=0; k<nLayers; k++) - { - MeshLib::CNode* node = mesh->nod_vector[k*nNodesPerLayer+i]; - if (k==0) node->SetBoundaryType('0'); // on the surface - else if (k==(nLayers-1)) node->SetBoundaryType('1'); // on the bottom - else node->SetBoundaryType('I'); // interior node - } - } + for (size_t i = 0; i < nNodesPerLayer; i++) + for (size_t k = 0; k < nLayers; k++) + { + MeshLib::CNode* node = mesh->nod_vector[k * nNodesPerLayer + i]; + if (k == 0) + node->SetBoundaryType('0'); // on the surface + else if (k == (nLayers - 1)) + node->SetBoundaryType('1'); // on the bottom + else + node->SetBoundaryType('I'); // interior node + } } - size_t flat(0); - for (size_t i=0; i<nNodesPerLayer; i++) + for (size_t i = 0; i < nNodesPerLayer; i++) { std::vector<long> tmp_connected_nodes; flat = 0; - for (size_t k=0; k<nLayers-2; k++) // top layer is not checked + for (size_t k = 0; k < nLayers - 2; k++) // top layer is not checked { - MeshLib::CNode* bNode = mesh->nod_vector[k*nNodesPerLayer+i]; // current node - MeshLib::CNode* tNode = mesh->nod_vector[(k+1)*nNodesPerLayer+i]; // same node but one layer below + MeshLib::CNode* bNode = mesh->nod_vector[k * nNodesPerLayer + i]; // current node + MeshLib::CNode* tNode = mesh->nod_vector[(k + 1) * nNodesPerLayer + i]; // same node but one layer below if (!tNode->GetMark()) { - if (k==0) + if (k == 0) { tmp_connected_nodes.clear(); - std::vector<size_t> const& connected_nodes (tNode->getConnectedNodes()); + std::vector<size_t> const& connected_nodes ( + tNode->getConnectedNodes()); const size_t n_connected_nodes (connected_nodes.size()); - for (size_t j=0; j<n_connected_nodes; j++) + for (size_t j = 0; j < n_connected_nodes; j++) tmp_connected_nodes.push_back(connected_nodes[j]); } tNode->SetZ(bNode->getData()[2]); // z coordinate changed to layer above tNode->getConnectedNodes().clear(); - for (int j=k; j>=0; j--) //WW/YW. 23.01.2009 + for (int j = k; j >= 0; j--) //WW/YW. 23.01.2009 { - MeshLib::CNode* nNode = mesh->nod_vector[j*nNodesPerLayer+i]; + MeshLib::CNode* nNode = + mesh->nod_vector[j * nNodesPerLayer + i]; if (nNode->GetMark()) { - tNode->getConnectedNodes().push_back(nNode->GetIndex()); + tNode->getConnectedNodes().push_back( + nNode->GetIndex()); break; } } @@ -300,156 +336,157 @@ void MshLayerMapper::CheckLayerMapping(MeshLib::CFEMesh* mesh, const size_t nLay } //---- 27.01.2009. WW - if (flat==nLayers-2/*1*/) + if (flat == nLayers - 2 /*1*/) { - - MeshLib::CNode* bNode = mesh->nod_vector[nNodesPerLayer+i]; + MeshLib::CNode* bNode = mesh->nod_vector[nNodesPerLayer + i]; bNode->SetMark(true); bNode->getConnectedNodes().clear(); - for (size_t j=0; j<tmp_connected_nodes.size(); j++) + for (size_t j = 0; j < tmp_connected_nodes.size(); j++) bNode->getConnectedNodes().push_back(tmp_connected_nodes[j]); - MeshLib::CNode* tNode = mesh->nod_vector[(nLayers-1)*nNodesPerLayer+i]; + MeshLib::CNode* tNode = + mesh->nod_vector[(nLayers - 1) * nNodesPerLayer + i]; tNode->SetMark(false); bNode->SetZ(tNode->getData()[2]); bNode->SetBoundaryType('1'); // - for (size_t k=1; k<nLayers; k++) + for (size_t k = 1; k < nLayers; k++) { - tNode = mesh->nod_vector[(k+1)*nNodesPerLayer+i]; + tNode = mesh->nod_vector[(k + 1) * nNodesPerLayer + i]; tNode->SetZ(ref_dep); tNode->getConnectedNodes().clear(); tNode->getConnectedNodes().push_back(bNode->GetIndex()); } } - } - std::vector<MeshLib::CElem*> new_elems; std::vector<size_t> false_node_idx; size_t nElems = mesh->ele_vector.size(); - for(size_t i=0; i<nElems; i++) + for(size_t i = 0; i < nElems; i++) { MeshLib::CElem* elem = mesh->ele_vector[i]; elem->SetMark(true); flat = 0; - for (size_t k=0; k<3;k++) //skip element when one node is marked ref_dep - { - if ( fabs(elem->GetNode(k)->getData()[2] +ref_dep)<std::numeric_limits<double>::min() || - fabs(elem->GetNode(k+3)->getData()[2]+ref_dep)<std::numeric_limits<double>::min() ) + for (size_t k = 0; k < 3; k++) //skip element when one node is marked ref_dep + + if ( fabs(elem->GetNode(k)->getData()[2] + ref_dep) < + std::numeric_limits<double>::min() || + fabs(elem->GetNode(k + 3)->getData()[2] + ref_dep) < + std::numeric_limits<double>::min() ) { flat = 1; elem->SetMark(false); break; } - } - if (flat==1) continue; + if (flat == 1) + continue; // If all nodes are okay, check if two z-values are identical - for (size_t k=0; k<3;k++) - { - if(fabs(elem->GetNode(k+3)->getData()[2]-elem->GetNode(k)->getData()[2]) < std::numeric_limits<double>::min()) + for (size_t k = 0; k < 3; k++) + if(fabs(elem->GetNode(k + + 3)->getData()[2] - elem->GetNode(k)->getData()[2]) < + std::numeric_limits<double>::min()) false_node_idx.push_back(k); - } switch(false_node_idx.size()) { - case 0: // everything okay, take the prism as it is - { - elem->SetMark(true); - break; - } - case 1: // one node of the prism is marked false, i.e. create two tetrahedron elements from the remaining 5 prism nodes - { - size_t a = false_node_idx[0]; - size_t b = (a+2)%3; - size_t c = (a+1)%3; - - if (elem->GetNode(a+3)->GetBoundaryType()=='1') //24.02.2009. WW - elem->GetNode(a)->SetBoundaryType('1'); - - // create a new tetrahedron - MeshLib::CElem* new_elem( new MeshLib::CElem() ); - new_elem->SetMark(true); - new_elem->SetElementType(MshElemType::TETRAHEDRON); - new_elem->SetPatchIndex(elem->GetPatchIndex()); - new_elem->SetBoundaryType('I'); - new_elem->SetNodesNumber(4); - - Math_Group::vec<MeshLib::CNode*> nodes(4); - nodes[0] = mesh->nod_vector[elem->nodes_index[a]]; - nodes[1] = mesh->nod_vector[elem->nodes_index[b+3]]; - nodes[2] = mesh->nod_vector[elem->nodes_index[c+3]]; - nodes[3] = mesh->nod_vector[elem->nodes_index[c]]; - new_elem->SetNodes(nodes, true); - - new_elem->nodes_index.resize(4); - for (size_t k=0; k<4; k++) - new_elem->nodes_index[k] = elem->GetNode(k)->GetIndex(); - new_elems.push_back(new_elem); - - // change prism-element to 2nd tetrahedron - elem->SetMark(true); - elem->SetElementType(MshElemType::TETRAHEDRON); - elem->SetNodesNumber(4); - - nodes[0] = mesh->nod_vector[elem->nodes_index[b]]; - nodes[1] = mesh->nod_vector[elem->nodes_index[a]]; - nodes[2] = mesh->nod_vector[elem->nodes_index[c]]; - nodes[3] = mesh->nod_vector[elem->nodes_index[b+3]]; - elem->SetNodes(nodes, true); - - elem->nodes_index.resize(4); - for (size_t k=0; k<4; k++) - elem->nodes_index[k] = elem->GetNode(k)->GetIndex(); - break; - } - case 2: // two nodes of the prism are marked false, i.e. create a tetrahedron element from the remaining 4 prism nodes - { - size_t a = false_node_idx[0]; - size_t b = (a+2)%3; - size_t c = (a+1)%3; - if (false_node_idx[1]==b) a = c; - else if(false_node_idx[1]==c) a = b; - - elem->SetMark(true); - elem->SetElementType(MshElemType::TETRAHEDRON); - elem->SetNodesNumber(4); - - Math_Group::vec<MeshLib::CNode*> nodes(4); - nodes[0] = mesh->nod_vector[elem->nodes_index[b]]; - nodes[1] = mesh->nod_vector[elem->nodes_index[a]]; - nodes[2] = mesh->nod_vector[elem->nodes_index[c]]; - nodes[3] = mesh->nod_vector[elem->nodes_index[a+3]]; - elem->SetNodes(nodes, true); - - elem->nodes_index.resize(4); - for (size_t k=0; k<4; k++) - elem->nodes_index[k] = elem->GetNode(k)->GetIndex(); - /* - //for j, l nodes if they becomes on top surface. 24.02.2009. WW - if (node_b->GetBoundaryType()=='1') - elem->nodes[0]->SetBoundaryType('1'); - if (node_t->GetBoundaryType()=='1') - elem->nodes[2]->SetBoundaryType('1'); - */ - break; - } - case 3: // three nodes of the prism is marked false, ditch the whole element - { - elem->SetMark(false); - break; - } + case 0: // everything okay, take the prism as it is + { + elem->SetMark(true); + break; + } + case 1: // one node of the prism is marked false, i.e. create two tetrahedron elements from the remaining 5 prism nodes + { + size_t a = false_node_idx[0]; + size_t b = (a + 2) % 3; + size_t c = (a + 1) % 3; + + if (elem->GetNode(a + 3)->GetBoundaryType() == '1') //24.02.2009. WW + elem->GetNode(a)->SetBoundaryType('1'); + + // create a new tetrahedron + MeshLib::CElem* new_elem( new MeshLib::CElem() ); + new_elem->SetMark(true); + new_elem->SetElementType(MshElemType::TETRAHEDRON); + new_elem->SetPatchIndex(elem->GetPatchIndex()); + new_elem->SetBoundaryType('I'); + new_elem->SetNodesNumber(4); + + Math_Group::vec<MeshLib::CNode*> nodes(4); + nodes[0] = mesh->nod_vector[elem->nodes_index[a]]; + nodes[1] = mesh->nod_vector[elem->nodes_index[b + 3]]; + nodes[2] = mesh->nod_vector[elem->nodes_index[c + 3]]; + nodes[3] = mesh->nod_vector[elem->nodes_index[c]]; + new_elem->SetNodes(nodes, true); + + new_elem->nodes_index.resize(4); + for (size_t k = 0; k < 4; k++) + new_elem->nodes_index[k] = elem->GetNode(k)->GetIndex(); + new_elems.push_back(new_elem); + + // change prism-element to 2nd tetrahedron + elem->SetMark(true); + elem->SetElementType(MshElemType::TETRAHEDRON); + elem->SetNodesNumber(4); + + nodes[0] = mesh->nod_vector[elem->nodes_index[b]]; + nodes[1] = mesh->nod_vector[elem->nodes_index[a]]; + nodes[2] = mesh->nod_vector[elem->nodes_index[c]]; + nodes[3] = mesh->nod_vector[elem->nodes_index[b + 3]]; + elem->SetNodes(nodes, true); + + elem->nodes_index.resize(4); + for (size_t k = 0; k < 4; k++) + elem->nodes_index[k] = elem->GetNode(k)->GetIndex(); + break; + } + case 2: // two nodes of the prism are marked false, i.e. create a tetrahedron element from the remaining 4 prism nodes + { + size_t a = false_node_idx[0]; + size_t b = (a + 2) % 3; + size_t c = (a + 1) % 3; + if (false_node_idx[1] == b) + a = c; + else if(false_node_idx[1] == c) + a = b; + + elem->SetMark(true); + elem->SetElementType(MshElemType::TETRAHEDRON); + elem->SetNodesNumber(4); + + Math_Group::vec<MeshLib::CNode*> nodes(4); + nodes[0] = mesh->nod_vector[elem->nodes_index[b]]; + nodes[1] = mesh->nod_vector[elem->nodes_index[a]]; + nodes[2] = mesh->nod_vector[elem->nodes_index[c]]; + nodes[3] = mesh->nod_vector[elem->nodes_index[a + 3]]; + elem->SetNodes(nodes, true); + + elem->nodes_index.resize(4); + for (size_t k = 0; k < 4; k++) + elem->nodes_index[k] = elem->GetNode(k)->GetIndex(); + /* + //for j, l nodes if they becomes on top surface. 24.02.2009. WW + if (node_b->GetBoundaryType()=='1') + elem->nodes[0]->SetBoundaryType('1'); + if (node_t->GetBoundaryType()=='1') + elem->nodes[2]->SetBoundaryType('1'); + */ + break; + } + case 3: // three nodes of the prism is marked false, ditch the whole element + { + elem->SetMark(false); + break; + } } } // add the newly created elements to the elements vector - for(size_t i=0; i<new_elems.size(); i++) + for(size_t i = 0; i < new_elems.size(); i++) mesh->ele_vector.push_back(new_elems[i]); - // correct indeces of elements and delete false elements std::vector<MeshLib::CElem*>::iterator beg_e = mesh->ele_vector.begin( ), last_e; long counter = 0; @@ -462,14 +499,14 @@ void MshLayerMapper::CheckLayerMapping(MeshLib::CFEMesh* mesh, const size_t nLay elem->SetIndex(counter); counter++; /* KR unused variable - for (int j=0; j<elem->GetVertexNumber(); j++) - { - if (!elem->GetNode(j)->GetMark()) - { - MeshLib::CNode* node = mesh->nod_vector[elem->GetNode(j)->connected_nodes[0]]; - } - } - */ + for (int j=0; j<elem->GetVertexNumber(); j++) + { + if (!elem->GetNode(j)->GetMark()) + { + MeshLib::CNode* node = mesh->nod_vector[elem->GetNode(j)->connected_nodes[0]]; + } + } + */ } else { @@ -502,11 +539,10 @@ void MshLayerMapper::CheckLayerMapping(MeshLib::CFEMesh* mesh, const size_t nLay // correct element indeces again after deleting nodes nElems = mesh->ele_vector.size(); - for(size_t i=0; i<nElems; i++) - { - for(int j=0; j< mesh->ele_vector[i]->GetVertexNumber(); j++) - mesh->ele_vector[i]->nodes_index[j] = mesh->ele_vector[i]->GetNode(j)->GetIndex(); - } + for(size_t i = 0; i < nElems; i++) + for(int j = 0; j < mesh->ele_vector[i]->GetVertexNumber(); j++) + mesh->ele_vector[i]->nodes_index[j] = + mesh->ele_vector[i]->GetNode(j)->GetIndex(); // delete elements if two of its nodes are identical (can this actually happen?????) beg_e = mesh->ele_vector.begin(); @@ -518,17 +554,15 @@ void MshLayerMapper::CheckLayerMapping(MeshLib::CFEMesh* mesh, const size_t nLay MeshLib::CElem* elem = *last_e; //10.02.2009. WW !!!!!!!!!!!!!!!!!!!!!! - for (int j=0; j<elem->GetVertexNumber(); j++) + for (int j = 0; j < elem->GetVertexNumber(); j++) { flatf = false; - for (int k=j; k<elem->GetVertexNumber(); k++) - { - if (elem->GetNodeIndex(j)==elem->GetNodeIndex(k)) + for (int k = j; k < elem->GetVertexNumber(); k++) + if (elem->GetNodeIndex(j) == elem->GetNodeIndex(k)) { flatf = true; break; } - } } if (flatf) { @@ -537,17 +571,17 @@ void MshLayerMapper::CheckLayerMapping(MeshLib::CFEMesh* mesh, const size_t nLay } else { - elem->SetIndex(counter); - counter++; - /* KR unused variable - for (int j=0; j<elem->GetVertexNumber(); j++) - { - if (!elem->GetNode(j)->GetMark()) - { - MeshLib::CNode* node = mesh->nod_vector[elem->GetNode(j)->connected_nodes[0]]; - } - } - */ + elem->SetIndex(counter); + counter++; + /* KR unused variable + for (int j=0; j<elem->GetVertexNumber(); j++) + { + if (!elem->GetNode(j)->GetMark()) + { + MeshLib::CNode* node = mesh->nod_vector[elem->GetNode(j)->connected_nodes[0]]; + } + } + */ } } @@ -562,23 +596,22 @@ void MshLayerMapper::CheckLayerMapping(MeshLib::CFEMesh* mesh, const size_t nLay MeshLib::CNode* node = *last; if ( node->getConnectedElementIDs().empty() ) { - delete node; - node = NULL; - beg = mesh->nod_vector.erase(last); + delete node; + node = NULL; + beg = mesh->nod_vector.erase(last); } else { - node->SetIndex(counter); - counter++; + node->SetIndex(counter); + counter++; } } nElems = mesh->ele_vector.size(); - for (size_t i=0; i<nElems; i++) - { - for (int j=0; j<mesh->ele_vector[i]->GetVertexNumber(); j++) - mesh->ele_vector[i]->nodes_index[j] = mesh->ele_vector[i]->GetNode(j)->GetIndex(); - } + for (size_t i = 0; i < nElems; i++) + for (int j = 0; j < mesh->ele_vector[i]->GetVertexNumber(); j++) + mesh->ele_vector[i]->nodes_index[j] = + mesh->ele_vector[i]->GetNode(j)->GetIndex(); mesh->ConstructGrid(); } diff --git a/DataView/MshLayerMapper.h b/DataView/MshLayerMapper.h index 32c53c9f1166afb889a94fc5034b17beca37d7b6..da1efe476b5254899bf26d0f2bb08fa881174a31 100644 --- a/DataView/MshLayerMapper.h +++ b/DataView/MshLayerMapper.h @@ -12,7 +12,7 @@ class QImage; namespace MeshLib { - class CFEMesh; +class CFEMesh; } /** @@ -21,8 +21,8 @@ namespace MeshLib class MshLayerMapper { public: - MshLayerMapper() {}; - ~MshLayerMapper() {}; + MshLayerMapper() {} + ~MshLayerMapper() {} /** * Based on a triangle-or quad mesh this method creates a 3D mesh with with a given number of prism- or hex-layers @@ -31,10 +31,16 @@ public: * \param thickness The thickness of each of these newly added layers * \return A mesh with the requested number of layers of prism/hex elements */ - static MeshLib::CFEMesh* CreateLayers(const MeshLib::CFEMesh* mesh, size_t nLayers, double thickness); + static MeshLib::CFEMesh* CreateLayers(const MeshLib::CFEMesh* mesh, + size_t nLayers, + double thickness); /// Maps the z-values of nodes in the designated layer of the given mesh according to the given raster. - static MeshLib::CFEMesh* LayerMapping(const MeshLib::CFEMesh* msh, const std::string &rasterfile, const size_t nLayers, const size_t layer_id, bool removeNoDataValues = false); + static MeshLib::CFEMesh* LayerMapping(const MeshLib::CFEMesh* msh, + const std::string &rasterfile, + const size_t nLayers, + const size_t layer_id, + bool removeNoDataValues = false); /// \brief Checks for overlapping nodes between between layers and corrects these errors. /// Note: this method has not been tested yet and will probably fail miserably! Please contact KR @@ -43,9 +49,9 @@ public: private: /// Checks if the given mesh is within the dimensions given by xDim and yDim. - static bool meshFitsImage(const MeshLib::CFEMesh* msh, const std::pair<double, double> &xDim, const std::pair<double, double> &yDim); - - + static bool meshFitsImage(const MeshLib::CFEMesh* msh, + const std::pair<double, double> &xDim, + const std::pair<double, double> &yDim); }; #endif //MSHLAYERMAPPER_H diff --git a/DataView/MshModel.cpp b/DataView/MshModel.cpp index dafa81699b6054140ca51d0f0767ecd0c04d1b58..1afa1fa25614974a1f887ed64d8a5d6aebd5a3fa 100644 --- a/DataView/MshModel.cpp +++ b/DataView/MshModel.cpp @@ -7,20 +7,20 @@ */ // ** INCLUDES ** -#include "MshModel.h" #include "MshItem.h" +#include "MshModel.h" #include "StringTools.h" #include "TreeItem.h" #include "VtkMeshSource.h" #include "msh_lib.h" -#include <QString> #include <QFileInfo> +#include <QString> #include <QTime> MshModel::MshModel(ProjectData &project, QObject* parent /*= 0*/ ) -: TreeModel(parent), _project(project) + : TreeModel(parent), _project(project) { delete _rootItem; QList<QVariant> rootData; @@ -55,18 +55,19 @@ void MshModel::addMeshObject(GridAdapter* mesh, std::string &name) _rootItem->appendChild(newMesh); // display elements - const std::vector<GridAdapter::Element*> *elems = mesh->getElements(); + const std::vector<GridAdapter::Element*>* elems = mesh->getElements(); size_t nElems (elems->size()); - for (size_t i=0; i<nElems; i++) + for (size_t i = 0; i < nElems; i++) { QList<QVariant> elemData; - elemData << "Element " + QString::number(i) << QString::fromStdString(MshElemType2String((*elems)[i]->type)); + elemData << "Element " + QString::number(i) << QString::fromStdString( + MshElemType2String((*elems)[i]->type)); QString nodestxt(""); size_t nNodes((*elems)[i]->nodes.size()); - for (size_t j=0; j<nNodes; j++) + for (size_t j = 0; j < nNodes; j++) nodestxt.append(QString::number((*elems)[i]->nodes[j]) + ", "); - elemData << nodestxt.left(nodestxt.length()-2); + elemData << nodestxt.left(nodestxt.length() - 2); TreeItem* elem = new TreeItem(elemData, newMesh); newMesh->appendChild(elem); @@ -74,7 +75,7 @@ void MshModel::addMeshObject(GridAdapter* mesh, std::string &name) reset(); - emit meshAdded(this, this->index(_rootItem->childCount()-1, 0, QModelIndex())); + emit meshAdded(this, this->index(_rootItem->childCount() - 1, 0, QModelIndex())); } const GridAdapter* MshModel::getMesh(const QModelIndex &idx) const @@ -82,8 +83,10 @@ const GridAdapter* MshModel::getMesh(const QModelIndex &idx) const if (idx.isValid()) { MshItem* item = dynamic_cast<MshItem*>(this->getItem(idx)); - if (item) return item->getGrid(); - else return NULL; + if (item) + return item->getGrid(); + else + return NULL; } std::cout << "MshModel::getMesh() - Specified index does not exist." << std::endl; return NULL; @@ -91,18 +94,18 @@ const GridAdapter* MshModel::getMesh(const QModelIndex &idx) const const GridAdapter* MshModel::getMesh(const std::string &name) const { - for (int i=0; i<_rootItem->childCount(); i++) + for (int i = 0; i < _rootItem->childCount(); i++) { MshItem* item = static_cast<MshItem*>(_rootItem->child(i)); if (item->data(0).toString().toStdString().compare(name) == 0) return item->getGrid(); } - std::cout << "MshModel::getMesh() - No entry found with name \"" << name << "\"." << std::endl; + std::cout << "MshModel::getMesh() - No entry found with name \"" << name << "\"." << + std::endl; return NULL; } - bool MshModel::removeMesh(const QModelIndex &idx) { if (idx.isValid()) @@ -124,7 +127,7 @@ bool MshModel::removeMesh(const QModelIndex &idx) bool MshModel::removeMesh(const std::string &name) { - for (int i=0; i<_rootItem->childCount(); i++) + for (int i = 0; i < _rootItem->childCount(); i++) { TreeItem* item = _rootItem->child(i); if (item->data(0).toString().toStdString().compare(name) == 0) @@ -136,21 +139,21 @@ bool MshModel::removeMesh(const std::string &name) } } - std::cout << "MshModel::removeMesh() - No entry found with name \"" << name << "." << std::endl; + std::cout << "MshModel::removeMesh() - No entry found with name \"" << name << "." << + std::endl; return false; } void MshModel::updateModel() { const std::map<std::string, MeshLib::CFEMesh*> msh_vec = _project.getMeshObjects(); - for (std::map<std::string, MeshLib::CFEMesh*>::const_iterator it(msh_vec.begin()); it != msh_vec.end(); ++it) - { + for (std::map<std::string, MeshLib::CFEMesh*>::const_iterator it(msh_vec.begin()); + it != msh_vec.end(); ++it) if (this->getMesh(it->first) == NULL) // if GridAdapter does not yet exist, create one. { std::string name = it->first; addMeshObject(new GridAdapter(it->second), name); } - } } VtkMeshSource* MshModel::vtkSource(const QModelIndex &idx) const @@ -167,51 +170,51 @@ VtkMeshSource* MshModel::vtkSource(const QModelIndex &idx) const VtkMeshSource* MshModel::vtkSource(const std::string &name) const { - for (int i=0; i<_rootItem->childCount(); i++) + for (int i = 0; i < _rootItem->childCount(); i++) { MshItem* item = static_cast<MshItem*>(_rootItem->child(i)); if (item->data(0).toString().toStdString().compare(name) == 0) return item->vtkSource(); } - std::cout << "MshModel::getMesh() - No entry found with name \"" << name << "\"." << std::endl; + std::cout << "MshModel::getMesh() - No entry found with name \"" << name << "\"." << + std::endl; return NULL; } - /* -bool MshModel::isUniqueMeshName(std::string &name) -{ - int count(0); - bool isUnique(false); - std::string cpName; - - while (!isUnique) - { - isUnique = true; - cpName = name; - - count++; - // If the original name already exists we start to add numbers to name for - // as long as it takes to make the name unique. - if (count>1) cpName = cpName + "-" + number2str(count); - - for (int i=0; i<_rootItem->childCount(); i++) - { - TreeItem* item = _rootItem->child(i); - if (item->data(0).toString().toStdString().compare(cpName) == 0) isUnique = false; - } - } - - // At this point cpName is a unique name and isUnique is true. - // If cpName is not the original name, "name" is changed and isUnique is set to false, - // indicating that a vector with the original name already exists. - if (count>1) - { - isUnique = false; - name = cpName; - } - return isUnique; -} -*/ + bool MshModel::isUniqueMeshName(std::string &name) + { + int count(0); + bool isUnique(false); + std::string cpName; + + while (!isUnique) + { + isUnique = true; + cpName = name; + + count++; + // If the original name already exists we start to add numbers to name for + // as long as it takes to make the name unique. + if (count>1) cpName = cpName + "-" + number2str(count); + + for (int i=0; i<_rootItem->childCount(); i++) + { + TreeItem* item = _rootItem->child(i); + if (item->data(0).toString().toStdString().compare(cpName) == 0) isUnique = false; + } + } + + // At this point cpName is a unique name and isUnique is true. + // If cpName is not the original name, "name" is changed and isUnique is set to false, + // indicating that a vector with the original name already exists. + if (count>1) + { + isUnique = false; + name = cpName; + } + return isUnique; + } + */ diff --git a/DataView/MshModel.h b/DataView/MshModel.h index b6f8ade96d038fbc45b4f9837463e19f94ad5f13..06890a0c89a79bf3b088786fdea4925c85e612cf 100644 --- a/DataView/MshModel.h +++ b/DataView/MshModel.h @@ -5,14 +5,13 @@ * */ - #ifndef MSHMODEL_H #define MSHMODEL_H // ** INCLUDES ** -#include "TreeModel.h" -#include "ProjectData.h" #include "GridAdapter.h" +#include "ProjectData.h" +#include "TreeModel.h" class VtkMeshSource; @@ -58,7 +57,6 @@ private: signals: void meshAdded(MshModel*, const QModelIndex&); void meshRemoved(MshModel*, const QModelIndex&); - }; #endif // MSHMODEL_H diff --git a/DataView/MshQualitySelectionDialog.cpp b/DataView/MshQualitySelectionDialog.cpp index c19c545c9d53fcbc797ab5481fdcbf0916314df8..3deac76eb0bb2fd17abec324364ce632cf09d206 100644 --- a/DataView/MshQualitySelectionDialog.cpp +++ b/DataView/MshQualitySelectionDialog.cpp @@ -7,8 +7,8 @@ #include "VtkMeshSource.h" /// Constructor -MshQualitySelectionDialog::MshQualitySelectionDialog(VtkMeshSource* msh, QDialog* parent) -: QDialog(parent), _msh(msh) +MshQualitySelectionDialog::MshQualitySelectionDialog(VtkMeshSource* msh, QDialog* parent) + : QDialog(parent), _msh(msh) { setupUi(this); this->choiceEdges->toggle(); @@ -22,11 +22,16 @@ MshQualitySelectionDialog::~MshQualitySelectionDialog() void MshQualitySelectionDialog::accept() { MshQualityType::type t; - if (this->choiceEdges->isChecked()) t = MshQualityType::EDGERATIO; - else if (this->choiceArea->isChecked()) t = MshQualityType::AREA; - else if (this->choiceVolume->isChecked()) t = MshQualityType::VOLUME; - else if (this->choiceAngles->isChecked()) t = MshQualityType::EQUIANGLESKEW; - else t = MshQualityType::INVALID; + if (this->choiceEdges->isChecked()) + t = MshQualityType::EDGERATIO; + else if (this->choiceArea->isChecked()) + t = MshQualityType::AREA; + else if (this->choiceVolume->isChecked()) + t = MshQualityType::VOLUME; + else if (this->choiceAngles->isChecked()) + t = MshQualityType::EQUIANGLESKEW; + else + t = MshQualityType::INVALID; emit measureSelected(_msh, t); this->done(QDialog::Accepted); diff --git a/DataView/MshQualitySelectionDialog.h b/DataView/MshQualitySelectionDialog.h index 8441be7b1edac55df99ec3a8adcb3ec05b82f821..e10bf7b3de0f63ec1a7f2f8288f4ea00e176cfae 100644 --- a/DataView/MshQualitySelectionDialog.h +++ b/DataView/MshQualitySelectionDialog.h @@ -6,9 +6,8 @@ #ifndef MSHQUALITYSELECTIONDIALOG_H #define MSHQUALITYSELECTIONDIALOG_H - -#include "ui_MshQualitySelection.h" #include "MSHEnums.h" +#include "ui_MshQualitySelection.h" class VtkMeshSource; @@ -32,7 +31,6 @@ private slots: signals: void measureSelected(VtkMeshSource*, MshQualityType::type); - }; #endif //MSHQUALITYSELECTIONDIALOG_H diff --git a/DataView/MshTabWidget.cpp b/DataView/MshTabWidget.cpp index 897664e2f76bd600b91c5270256961cc6f2d0070..cd9ff9c46bfb0f4fbd5974eab48b3ec48c121184 100644 --- a/DataView/MshTabWidget.cpp +++ b/DataView/MshTabWidget.cpp @@ -10,59 +10,58 @@ #include "MshTabWidget.h" MshTabWidget::MshTabWidget( QWidget* parent /*= 0*/ ) -: QWidget(parent) + : QWidget(parent) { setupUi(this); connect(this->addMeshPushButton, SIGNAL(clicked()), this->treeView, SLOT(addMeshAction())); connect(this->clearAllPushButton, SIGNAL(clicked()), this->treeView, SLOT(removeAllMeshes())); - /* - mshTableView->setSelectionMode(QAbstractItemView::ExtendedSelection); - mshTableView->setSelectionBehavior(QAbstractItemView::SelectRows); - mshNodeTableView->setSelectionMode(QAbstractItemView::ExtendedSelection); - mshNodeTableView->setSelectionBehavior(QAbstractItemView::SelectRows); + mshTableView->setSelectionMode(QAbstractItemView::ExtendedSelection); + mshTableView->setSelectionBehavior(QAbstractItemView::SelectRows); + mshNodeTableView->setSelectionMode(QAbstractItemView::ExtendedSelection); + mshNodeTableView->setSelectionBehavior(QAbstractItemView::SelectRows); - connect(mshTableView, SIGNAL(itemSelectionChanged(QItemSelection, QItemSelection)), - this, SLOT(changeMshSubmodelViews(QItemSelection, QItemSelection))); -*/ + connect(mshTableView, SIGNAL(itemSelectionChanged(QItemSelection, QItemSelection)), + this, SLOT(changeMshSubmodelViews(QItemSelection, QItemSelection))); + */ } /* -void MshTabWidget::changeMshSubmodelViews( QItemSelection selected, QItemSelection deselected ) -{ + void MshTabWidget::changeMshSubmodelViews( QItemSelection selected, QItemSelection deselected ) + { - if (selected.size() > 0) - { - QModelIndex index = *(selected.begin()->indexes().begin()); - if (!index.isValid()) - return; + if (selected.size() > 0) + { + QModelIndex index = *(selected.begin()->indexes().begin()); + if (!index.isValid()) + return; - MshModel* mshModel = static_cast<MshModel*>(mshTableView->model()); + MshModel* mshModel = static_cast<MshModel*>(mshTableView->model()); - ModelItem* item = mshModel->itemFromIndex(index); + ModelItem* item = mshModel->itemFromIndex(index); - mshNodeTableView->setModel(item->models()[0]); - mshNodeTableView->resizeColumnsToContents(); - mshNodeTableView->resizeRowsToContents(); + mshNodeTableView->setModel(item->models()[0]); + mshNodeTableView->resizeColumnsToContents(); + mshNodeTableView->resizeRowsToContents(); - connect(mshNodeTableView, SIGNAL(itemSelectionChanged(const QItemSelection&,const QItemSelection&)), - item->models()[0], SLOT(setSelection(const QItemSelection&, const QItemSelection&))); + connect(mshNodeTableView, SIGNAL(itemSelectionChanged(const QItemSelection&,const QItemSelection&)), + item->models()[0], SLOT(setSelection(const QItemSelection&, const QItemSelection&))); -// connect(item->models()[0], SIGNAL(dataChanged(QModelIndex,QModelIndex)), _scene, SLOT(updateItems(QModelIndex,QModelIndex))); -// connect(item->models()[1], SIGNAL(dataChanged(QModelIndex,QModelIndex)), _scene, SLOT(updateItems(QModelIndex,QModelIndex))); + // connect(item->models()[0], SIGNAL(dataChanged(QModelIndex,QModelIndex)), _scene, SLOT(updateItems(QModelIndex,QModelIndex))); + // connect(item->models()[1], SIGNAL(dataChanged(QModelIndex,QModelIndex)), _scene, SLOT(updateItems(QModelIndex,QModelIndex))); - mshElemTableView->setModel(item->models()[1]); - mshElemTableView->resizeColumnsToContents(); - mshElemTableView->resizeRowsToContents(); + mshElemTableView->setModel(item->models()[1]); + mshElemTableView->resizeColumnsToContents(); + mshElemTableView->resizeRowsToContents(); - } - else - { - mshNodeTableView->setModel(NULL); - mshElemTableView->setModel(NULL); - } + } + else + { + mshNodeTableView->setModel(NULL); + mshElemTableView->setModel(NULL); + } -} -*/ + } + */ diff --git a/DataView/MshTabWidget.h b/DataView/MshTabWidget.h index d2e5777571dbb299cfbc86beb1c55c5c5e1733e9..40722c3d21d390f208cbec50d50205d5943e94ff 100644 --- a/DataView/MshTabWidget.h +++ b/DataView/MshTabWidget.h @@ -5,14 +5,12 @@ * */ - #ifndef MSHTABWIDGET_H #define MSHTABWIDGET_H // ** INCLUDES ** #include "ui_MshTabWidgetBase.h" - /** * \brief Widget for data views of meshes. */ @@ -22,9 +20,6 @@ class MshTabWidget : public QWidget, public Ui_MshTabWidgetBase public: MshTabWidget(QWidget* parent = 0); - - - }; #endif // MSHTABWIDGET_H diff --git a/DataView/OGSRaster.cpp b/DataView/OGSRaster.cpp index 28ad7e10064c45aa57b6fe62ba5d9d4512136de5..ed198ff2ea0ff407920212e072157a8aeefcd6fe 100644 --- a/DataView/OGSRaster.cpp +++ b/DataView/OGSRaster.cpp @@ -9,12 +9,12 @@ #include <sstream> #include <QFileInfo> -#include <QPointF> #include <QImage> +#include <QPointF> +#include "OGSError.h" #include "OGSRaster.h" #include "StringTools.h" -#include "OGSError.h" #ifdef libgeotiff_FOUND #include "geo_tiffp.h" @@ -22,40 +22,54 @@ #endif bool OGSRaster::loadImage(const QString &fileName, QImage &raster, QPointF &origin, - double &scalingFactor, bool autoscale /* = true */, bool mirrorX /* = false */) + double &scalingFactor, bool autoscale /* = true */, bool mirrorX /* = false */) { QFileInfo fileInfo(fileName); origin.setX(0); origin.setY(0); scalingFactor = 1; - if (fileInfo.suffix().toLower() == "asc") + if (fileInfo.suffix().toLower() == "asc") { - if (!loadImageFromASC(fileName, raster, origin, scalingFactor, autoscale)) return false; + if (!loadImageFromASC(fileName, raster, origin, scalingFactor, autoscale)) + return false; if (mirrorX) - raster = raster.transformed(QTransform(1, 0, 0, -1, 0, 0), Qt::FastTransformation); + raster = raster.transformed(QTransform(1, + 0, + 0, + -1, + 0, + 0), Qt::FastTransformation); } #ifdef libgeotiff_FOUND else if (fileInfo.suffix().toLower() == "tif") { - if (!loadImageFromTIFF(fileName, raster, origin, scalingFactor)) return false; + if (!loadImageFromTIFF(fileName, raster, origin, scalingFactor)) + return false; if (!mirrorX) - raster = raster.transformed(QTransform(1, 0, 0, -1, 0, 0), Qt::FastTransformation); + raster = raster.transformed(QTransform(1, + 0, + 0, + -1, + 0, + 0), Qt::FastTransformation); } #endif - else - { - if (!loadImageFromFile(fileName, raster)) return false; - } + else if (!loadImageFromFile(fileName, raster)) + return false; return true; } -bool OGSRaster::loadImageFromASC(const QString &fileName, QImage &raster, QPointF &origin, double &cellsize, bool autoscale) +bool OGSRaster::loadImageFromASC(const QString &fileName, + QImage &raster, + QPointF &origin, + double &cellsize, + bool autoscale) { std::ifstream in( fileName.toStdString().c_str() ); if (!in.is_open()) - { + { std::cout << "OGSRaster::loadImageFromASC() - Could not open file..." << std::endl; return false; } @@ -64,51 +78,62 @@ bool OGSRaster::loadImageFromASC(const QString &fileName, QImage &raster, QPoint if (readASCHeader(header, in)) { - int index=0, gVal; - double value, minVal=65536, maxVal=0; - double *pixVal (new double[header.ncols * header.nrows]); + int index = 0, gVal; + double value, minVal = 65536, maxVal = 0; + double* pixVal (new double[header.ncols * header.nrows]); QImage img(header.ncols, header.nrows, QImage::Format_ARGB32); std::string s; // read the file into a double-array - for (int j=0; j<header.nrows; j++) + for (int j = 0; j < header.nrows; j++) { - index = j*header.ncols; - for (int i=0; i<header.ncols; i++) + index = j * header.ncols; + for (int i = 0; i < header.ncols; i++) { in >> s; - pixVal[index+i] = strtod(replaceString(",", ".", s).c_str(),0); - if (pixVal[index+i] != header.noData) - { // find intensity bounds but ignore noData values - minVal = (pixVal[index+i]<minVal) ? pixVal[index+i] : minVal; - maxVal = (pixVal[index+i]>maxVal) ? pixVal[index+i] : maxVal; + pixVal[index + i] = strtod(replaceString(",", ".", s).c_str(),0); + if (pixVal[index + i] != header.noData) + { // find intensity bounds but ignore noData values + minVal = + (pixVal[index + + i] < minVal) ? pixVal[index + i] : minVal; + maxVal = + (pixVal[index + + i] > maxVal) ? pixVal[index + i] : maxVal; } } } in.close(); // calculate scaling factor for contrast stretching - double scalingFactor = 255.0/(maxVal-minVal); + double scalingFactor = 255.0 / (maxVal - minVal); // write re-calculated image intensities to QImage // the formula used for contrast adjustment is p_new = (value - minval) * (g_max-g_min)/(maxval-minval) - for (int j=0; j<header.nrows; j++) + for (int j = 0; j < header.nrows; j++) { - index = j*header.ncols; - for (int i=0; i<header.ncols; i++) - { // scale intensities and set nodata values to zero (black) - if (pixVal[index+i]!=header.noData) + index = j * header.ncols; + for (int i = 0; i < header.ncols; i++) + { // scale intensities and set nodata values to zero (black) + if (pixVal[index + i] != header.noData) { - value = (pixVal[index+i]==header.noData) ? minVal : pixVal[index+i]; - gVal = (autoscale) ? static_cast<int> (floor((value-minVal)*scalingFactor)) : static_cast<int> (value); + value = + (pixVal[index + i] == + header.noData) ? minVal : pixVal[index + i]; + gVal = + (autoscale) ? static_cast<int> (floor((value - + minVal) * + scalingFactor)) + : static_cast<int> (value); //gVal = value; // saudi arabia img.setPixel(i,j, qRgba(gVal, gVal, gVal, 255)); } - else img.setPixel(i,j, qRgba(0, 0, 0, 0)); + else + img.setPixel(i,j, qRgba(0, 0, 0, 0)); } } - delete []pixVal; + delete [] pixVal; origin.setX(header.x); origin.setY(header.y); cellsize = header.cellsize; @@ -119,43 +144,77 @@ bool OGSRaster::loadImageFromASC(const QString &fileName, QImage &raster, QPoint return false; } - bool OGSRaster::readASCHeader(ascHeader &header, std::ifstream &in) { std::string line, tag, value; in >> tag; - if (tag.compare("ncols")==0) { in >> value; header.ncols = atoi(value.c_str()); } - else return false; + if (tag.compare("ncols") == 0) + { + in >> value; + header.ncols = atoi(value.c_str()); + } + else + return false; in >> tag; - if (tag.compare("nrows")==0) { in >> value; header.nrows = atoi(value.c_str()); } - else return false; + if (tag.compare("nrows") == 0) + { + in >> value; + header.nrows = atoi(value.c_str()); + } + else + return false; in >> tag; - if (tag.compare("xllcorner")==0) { in >> value; header.x = strtod(replaceString(",", ".", value).c_str(),0); } - else return false; + if (tag.compare("xllcorner") == 0) + { + in >> value; + header.x = strtod(replaceString(",", ".", value).c_str(),0); + } + else + return false; in >> tag; - if (tag.compare("yllcorner")==0) { in >> value; header.y = strtod(replaceString(",", ".", value).c_str(),0); } - else return false; + if (tag.compare("yllcorner") == 0) + { + in >> value; + header.y = strtod(replaceString(",", ".", value).c_str(),0); + } + else + return false; in >> tag; - if (tag.compare("cellsize")==0) { in >> value; header.cellsize = strtod(replaceString(",", ".", value).c_str(),0); } - else return false; + if (tag.compare("cellsize") == 0) + { + in >> value; + header.cellsize = strtod(replaceString(",", ".", value).c_str(),0); + } + else + return false; in >> tag; - if (tag.compare("NODATA_value")==0) { in >> value; header.noData = atoi(value.c_str()); } - else return false; + if (tag.compare("NODATA_value") == 0) + { + in >> value; + header.noData = atoi(value.c_str()); + } + else + return false; // correct raster position by half a pixel for correct visualisation - header.x = header.x+(header.cellsize/2); - header.y = header.y+(header.cellsize/2); + header.x = header.x + (header.cellsize / 2); + header.y = header.y + (header.cellsize / 2); return true; } -double* OGSRaster::loadDataFromASC(const QString &fileName, double &x0, double &y0, size_t &width, size_t &height, double &delta) +double* OGSRaster::loadDataFromASC(const QString &fileName, + double &x0, + double &y0, + size_t &width, + size_t &height, + double &delta) { std::ifstream in( fileName.toStdString().c_str() ); if (!in.is_open()) - { + { std::cout << "OGSRaster::loadImageFromASC() - Could not open file..." << std::endl; return NULL; } @@ -175,13 +234,13 @@ double* OGSRaster::loadDataFromASC(const QString &fileName, double &x0, double & int index(0); std::string s(""); // read the file into a double-array - for (int j=0; j<header.nrows; j++) + for (int j = 0; j < header.nrows; j++) { - index = (header.nrows-j-1)*header.ncols; - for (int i=0; i<header.ncols; i++) + index = (header.nrows - j - 1) * header.ncols; + for (int i = 0; i < header.ncols; i++) { in >> s; - values[index+i] = strtod(replaceString(",", ".", s).c_str(),0); + values[index + i] = strtod(replaceString(",", ".", s).c_str(),0); } } @@ -192,25 +251,30 @@ double* OGSRaster::loadDataFromASC(const QString &fileName, double &x0, double & } #ifdef libgeotiff_FOUND -bool OGSRaster::loadImageFromTIFF(const QString &fileName, QImage &raster, QPointF &origin, double &cellsize) +bool OGSRaster::loadImageFromTIFF(const QString &fileName, + QImage &raster, + QPointF &origin, + double &cellsize) { TIFF* tiff = XTIFFOpen(fileName.toStdString().c_str(), "r"); if (tiff) - { + { GTIF* geoTiff = GTIFNew(tiff); if (geoTiff) { - - int imgWidth=0, imgHeight=0, nImages=0, pntCount = 0; + int imgWidth = 0, imgHeight = 0, nImages = 0, pntCount = 0; double* pnts = 0; // get actual number of images in the tiff file do { nImages++; } while (TIFFReadDirectory(tiff)); - if (nImages>1) std::cout << "OGSRaster::loadImageFromTIFF() - File contains " << nImages << " images. This method is not tested for this case." << std::endl; + if (nImages > 1) + std::cout << "OGSRaster::loadImageFromTIFF() - File contains " << + nImages << " images. This method is not tested for this case." << + std::endl; // get image size TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &imgWidth); @@ -220,7 +284,10 @@ bool OGSRaster::loadImageFromTIFF(const QString &fileName, QImage &raster, QPoin // Note: GeoTiff allows anisotropic pixels. This is not supported here and equilateral pixels are assumed. if (TIFFGetField(tiff, GTIFF_PIXELSCALE, &pntCount, &pnts)) { - if (pnts[0] != pnts[1]) std::cout << "OGSRaster::loadImageFromTIFF() - Warning: Original raster data has anisotrop pixel size!" << std::endl; + if (pnts[0] != pnts[1]) + std::cout << + "OGSRaster::loadImageFromTIFF() - Warning: Original raster data has anisotrop pixel size!" + << std::endl; cellsize = pnts[0]; } @@ -228,48 +295,57 @@ bool OGSRaster::loadImageFromTIFF(const QString &fileName, QImage &raster, QPoin if (TIFFGetField(tiff, GTIFF_TIEPOINTS, &pntCount, &pnts)) { origin.setX(pnts[3]); - origin.setY(pnts[4]-(imgHeight*cellsize)); // the origin should be the lower left corner of the img + origin.setY(pnts[4] - (imgHeight * cellsize)); // the origin should be the lower left corner of the img } // read pixel values - uint32 *pixVal = (uint32*) _TIFFmalloc(imgWidth*imgHeight * sizeof (uint32)); + uint32* pixVal = + (uint32*) _TIFFmalloc(imgWidth * imgHeight * sizeof (uint32)); if ((imgWidth > 0) && (imgHeight > 0)) - { if (!TIFFReadRGBAImage(tiff, imgWidth, imgHeight, pixVal, 0)) { - std::cout << "OGSRaster::loadImageFromTIFF() - Error reading GeoTIFF file." << std::endl; + std::cout << + "OGSRaster::loadImageFromTIFF() - Error reading GeoTIFF file." + << std::endl; _TIFFfree(pixVal); GTIFFree(geoTiff); XTIFFClose(tiff); return false; } - } // read colormap if it exists - uint16 *cmap_red=NULL, *cmap_green=NULL, *cmap_blue=NULL; - int colormap_used = TIFFGetField(tiff, TIFFTAG_COLORMAP, &cmap_red, &cmap_green, &cmap_blue); - - int lineindex=0, idx=0; + uint16* cmap_red = NULL, * cmap_green = NULL, * cmap_blue = NULL; + int colormap_used = TIFFGetField(tiff, + TIFFTAG_COLORMAP, + &cmap_red, + &cmap_green, + &cmap_blue); + + int lineindex = 0, idx = 0; QImage img(imgWidth, imgHeight, QImage::Format_ARGB32); int* pxl (new int[4]); - for (int j=0; j<imgHeight; j++) + for (int j = 0; j < imgHeight; j++) { - lineindex = j*imgWidth; - for (int i=0; i<imgWidth; i++) - { // scale intensities and set nodata values to white (i.e. the background colour) + lineindex = j * imgWidth; + for (int i = 0; i < imgWidth; i++) + { // scale intensities and set nodata values to white (i.e. the background colour) idx = TIFFGetR(pixVal[lineindex + i]); if (colormap_used) - img.setPixel(i,j, qRgba(cmap_red[idx]>>8, cmap_green[idx]>>8, cmap_blue[idx]>>8, 255)); + img.setPixel(i,j, + qRgba(cmap_red[idx] >> 8, + cmap_green[idx] >> 8, + cmap_blue[idx] >> 8, 255)); else { //img.setPixel(i,j, qRgba(TIFFGetB(pixVal[idx]), TIFFGetG(pixVal[idx]), TIFFGetR(pixVal[idx]), TIFFGetA(pixVal[idx]))); - uint32toRGBA(pixVal[lineindex+i], pxl); - img.setPixel(i,j, qRgba(pxl[0], pxl[1], pxl[2], pxl[3])); + uint32toRGBA(pixVal[lineindex + i], pxl); + img.setPixel(i,j, + qRgba(pxl[0], pxl[1], pxl[2], pxl[3])); } } } - delete []pxl; + delete [] pxl; raster = img; @@ -280,11 +356,14 @@ bool OGSRaster::loadImageFromTIFF(const QString &fileName, QImage &raster, QPoin } XTIFFClose(tiff); - std::cout << "OGSRaster::loadImageFromTIFF() - File not recognised as GeoTIFF-Image." << std::endl; + std::cout << + "OGSRaster::loadImageFromTIFF() - File not recognised as GeoTIFF-Image." << + std::endl; return false; } - std::cout << "OGSRaster::loadImageFromTIFF() - File not recognised as TIFF-Image." << std::endl; + std::cout << "OGSRaster::loadImageFromTIFF() - File not recognised as TIFF-Image." << + std::endl; return false; } #endif @@ -297,72 +376,71 @@ bool OGSRaster::loadImageFromFile(const QString &fileName, QImage &raster) void OGSRaster::convertToGreyscale(QImage &raster, const int &min, const int &max) { int value = 0; - double scalingFactor = 255.0/(max-min); + double scalingFactor = 255.0 / (max - min); - for (int i=0; i<raster.width(); i++) - { - for (int j=0; j<raster.height(); j++) + for (int i = 0; i < raster.width(); i++) + for (int j = 0; j < raster.height(); j++) { QRgb pix = raster.pixel(i,j); - value = static_cast<int>(floor(((0.3*qRed(pix)+0.6*qGreen(pix)+0.1*qBlue(pix))-min)*scalingFactor)); + value = + static_cast<int>(floor(((0.3 * qRed(pix) + 0.6 * qGreen(pix) + + 0.1 * + qBlue(pix)) - min) * scalingFactor)); raster.setPixel(i, j, qRgb(value, value, value)); } - } } - int* OGSRaster::getGreyscaleData(QImage &raster, const int &min, const int &max) { int index = 0; - double scalingFactor = 255.0/(max-min); - int *pixVal (new int[raster.height() * raster.width()]); + double scalingFactor = 255.0 / (max - min); + int* pixVal (new int[raster.height() * raster.width()]); - for (int j=0; j<raster.height(); j++) + for (int j = 0; j < raster.height(); j++) { - index = j*raster.width(); - for (int i=0; i<raster.width(); i++) + index = j * raster.width(); + for (int i = 0; i < raster.width(); i++) { QRgb pix = raster.pixel(i,j); - pixVal[index+i] = static_cast<int>(floor(((0.3*qRed(pix)+0.6*qGreen(pix)+0.1*qBlue(pix))-min)*scalingFactor)); + pixVal[index + + i] = + static_cast<int>(floor(((0.3 * qRed(pix) + 0.6 * qGreen(pix) + + 0.1 * + qBlue(pix)) - min) * scalingFactor)); } } return pixVal; } - int OGSRaster::getMaxValue(const QImage &raster) { int value, maxVal = 0; - for (int i=0; i<raster.width(); i++) - { - for (int j=0; j<raster.height(); j++) + for (int i = 0; i < raster.width(); i++) + for (int j = 0; j < raster.height(); j++) { value = qGreen(raster.pixel(i,j)); - maxVal = (value>maxVal) ? value : maxVal; + maxVal = (value > maxVal) ? value : maxVal; } - } return maxVal; } int OGSRaster::getMinValue(const QImage &raster) { int value, minVal = 65536; - for (int i=0; i<raster.width(); i++) - { - for (int j=0; j<raster.height(); j++) + for (int i = 0; i < raster.width(); i++) + for (int j = 0; j < raster.height(); j++) { value = qGreen(raster.pixel(i,j)); - minVal = (value<minVal) ? value : minVal; + minVal = (value < minVal) ? value : minVal; } - } return minVal; } void OGSRaster::uint32toRGBA(const unsigned int s, int* p) { - p[3] = s / (256*256*256); - int r = s % (256*256*256); - p[2] = r / (256*256); + p[3] = s / (256 * 256 * 256); + int r = s % (256 * 256 * 256); + p[2] = r / (256 * 256); r %= (256 * 256); p[1] = r / 256; p[0] = r % 256; diff --git a/DataView/OGSRaster.h b/DataView/OGSRaster.h index 58a1d38d0a0f9aecc26a3850290e21be7b133c45..c1fc6092d7be502f9682599d3bf7d9c663f5f5f0 100644 --- a/DataView/OGSRaster.h +++ b/DataView/OGSRaster.h @@ -31,7 +31,6 @@ class OGSRaster int noData; }; - public: /** * \brief Loads an image- or raster-file into an QImage. @@ -46,20 +45,30 @@ public: * \param mirrorX Mirror around x-axis. * \return True if the raster data was loaded correctly, false otherwise. */ - static bool loadImage(const QString &fileName, QImage &raster, QPointF &origin, double &scalingFactor, bool autoscale = true, bool mirrorX = false); - + static bool loadImage(const QString &fileName, + QImage &raster, + QPointF &origin, + double &scalingFactor, + bool autoscale = true, + bool mirrorX = false); + /** * \brief Loads an ASC file into a double array * * \param fileName Filename of the file that should be loaded. * \param x0 The x-coordinate of the origin. - * \param y0 The y-coordinate of the origin. + * \param y0 The y-coordinate of the origin. * \param width The width of the image. * \param height The height of the image * \param delta The size of each pixel in the image which is needed for re-scaling the data. * \return True if the raster data was loaded correctly, false otherwise. - */ - static double* loadDataFromASC(const QString &fileName, double& x0, double &y0, size_t &width, size_t &height, double &delta); + */ + static double* loadDataFromASC(const QString &fileName, + double& x0, + double &y0, + size_t &width, + size_t &height, + double &delta); /// Converts raster to an 8 bit greyscale image that is contrast-stretched in [min:max]. static void convertToGreyscale(QImage &raster, const int &min = 0, const int &max = 255); @@ -73,7 +82,6 @@ public: /// Returns the minimum intensity of raster. static int getMinValue(const QImage &raster); - private: /** * Loads ArcGIS asc-files to a QPixmap object and automatically does a contrast stretching to adjust values to 8 bit greyscale images. @@ -84,8 +92,11 @@ private: * \param autoscale * \return True if the raster data was loaded correctly, false otherwise. */ - static bool loadImageFromASC(const QString &fileName, QImage &raster, QPointF &origin, double &scalingFactor, bool autoscale = true); - + static bool loadImageFromASC(const QString &fileName, + QImage &raster, + QPointF &origin, + double &scalingFactor, + bool autoscale = true); /** * Loads ArcGIS asc-files to a QPixmap object and automatically does a contrast stretching to adjust values to 8 bit greyscale images. @@ -95,8 +106,11 @@ private: * \param scalingFactor * \return True if the raster data was loaded correctly, false otherwise. */ -#ifdef libgeotiff_FOUND - static bool loadImageFromTIFF(const QString &fileName, QImage &raster, QPointF &origin, double &scalingFactor); +#ifdef libgeotiff_FOUND + static bool loadImageFromTIFF(const QString &fileName, + QImage &raster, + QPointF &origin, + double &scalingFactor); #endif /** @@ -108,7 +122,7 @@ private: static bool loadImageFromFile(const QString &fileName, QImage &raster); /** - * Reads the header of an ArcGIS asc-file. + * Reads the header of an ArcGIS asc-file. * \param header The ascHeader-object into which all the information will be written. * \param in FileInputStream used for reading the data. * \return True if the header could be read correctly, false otherwise. diff --git a/DataView/QueryResultsDialog.cpp b/DataView/QueryResultsDialog.cpp index 10dbb9f6ad899ef7f6aa6a069f1f1b471905df7d..585579a03547b0f2917d59feaff99453c2b5fd3e 100644 --- a/DataView/QueryResultsDialog.cpp +++ b/DataView/QueryResultsDialog.cpp @@ -3,8 +3,8 @@ * KR Initial implementation */ -#include "QueryResultsDialog.h" #include "OGSError.h" +#include "QueryResultsDialog.h" /** * Constructor. diff --git a/DataView/QueryResultsDialog.h b/DataView/QueryResultsDialog.h index c0d4264a9892adf0d3b351eab57a390fbacbb92a..fa6dc45a947e7da325609d0ee5e6806455a6e4dc 100644 --- a/DataView/QueryResultsDialog.h +++ b/DataView/QueryResultsDialog.h @@ -6,9 +6,9 @@ #ifndef QUERYRESULTSDIALOG_H #define QUERYRESULTSDIALOG_H -#include <QtGui/QMainWindow> -#include <QSqlQueryModel> #include "ui_DatabaseResultView.h" +#include <QSqlQueryModel> +#include <QtGui/QMainWindow> /** * \brief A Dialog for displaying the results of a database query in a table. @@ -37,7 +37,6 @@ private slots: signals: void listSelected(int listID); - }; #endif //QUERYRESULTSDIALOG_H diff --git a/DataView/SHPImportDialog.cpp b/DataView/SHPImportDialog.cpp index 0e95d0bcd163e49bfa17c7d76767ff5352122a2b..fa62d79785a0ac8d95df80d48c10a6a4154d8b7f 100644 --- a/DataView/SHPImportDialog.cpp +++ b/DataView/SHPImportDialog.cpp @@ -3,29 +3,28 @@ * 25/01/2010 KR Initial implementation */ +#include "GEOModels.h" #include "OGSError.h" #include "SHPImportDialog.h" #include "SHPInterface.h" -#include "GEOModels.h" -#include <QLabel> -#include <QVBoxLayout> -#include <QFileInfo> #include <QDialogButtonBox> +#include <QFileInfo> +#include <QLabel> #include <QLineEdit> #include <QRadioButton> +#include <QVBoxLayout> - -SHPImportDialog::SHPImportDialog(std::string filename, GEOModels* geoModels, QDialog* parent) -: QDialog(parent), _buttonBox(NULL), _layout(NULL), _shpContentLabel(NULL), _nameLabel(NULL), -_listName(new QLineEdit()), _choice1(NULL), _choice2(NULL), _filename(filename), _fileType(0), -_shpInterface(new SHPInterface(geoModels)) +SHPImportDialog::SHPImportDialog(std::string filename, GEOModels* geoModels, QDialog* parent) + : QDialog(parent), _buttonBox(NULL), _layout(NULL), _shpContentLabel(NULL), _nameLabel(NULL), + _listName(new QLineEdit()), _choice1(NULL), _choice2(NULL), _filename(filename), + _fileType(0), + _shpInterface(new SHPInterface(geoModels)) { setupDialog(); show(); } - SHPImportDialog::~SHPImportDialog() { delete _shpInterface; @@ -38,7 +37,6 @@ SHPImportDialog::~SHPImportDialog() delete _layout; } - void SHPImportDialog::setupDialog() { _layout = new QGridLayout(this); @@ -49,48 +47,56 @@ void SHPImportDialog::setupDialog() if (_shpInterface->readSHPInfo(_filename, shpType, numberOfEntities)) { - if ((shpType-1)%10 == 0) type="points"; - if ((shpType-3)%10 == 0) type="polylines"; - if ((shpType-5)%10 == 0) type="polygons"; - if ((shpType-8)%10 == 0) type="multipoints"; - if (shpType == 31) type="TIN elements"; - - _shpContentLabel = new QLabel("The selected file contains " + QString::number(numberOfEntities) + " " + type, this); + if ((shpType - 1) % 10 == 0) + type = "points"; + if ((shpType - 3) % 10 == 0) + type = "polylines"; + if ((shpType - 5) % 10 == 0) + type = "polygons"; + if ((shpType - 8) % 10 == 0) + type = "multipoints"; + if (shpType == 31) + type = "TIN elements"; + + _shpContentLabel = + new QLabel("The selected file contains " + QString::number( + numberOfEntities) + " " + type, this); _nameLabel = new QLabel("List Name: ", this); QFileInfo fi(QString::fromStdString(_filename)); _listName->setText(fi.baseName()); - if ((shpType-1)%10 == 0 && shpType!=31) // Points + if ((shpType - 1) % 10 == 0 && shpType != 31) // Points { - _choice1 = new QRadioButton("Read as GLI-Points"); - _choice2 = new QRadioButton("Read as Station Points"); - _choice1->toggle(); // default choice - _layout->addWidget( _shpContentLabel ); - _layout->addWidget( _choice1 ); - _layout->addWidget( _choice2 ); - _layout->addWidget( _nameLabel ); - _layout->addWidget( _listName ); - _fileType = 1; + _choice1 = new QRadioButton("Read as GLI-Points"); + _choice2 = new QRadioButton("Read as Station Points"); + _choice1->toggle(); // default choice + _layout->addWidget( _shpContentLabel ); + _layout->addWidget( _choice1 ); + _layout->addWidget( _choice2 ); + _layout->addWidget( _nameLabel ); + _layout->addWidget( _listName ); + _fileType = 1; } - else if ((shpType-3)%10 == 0 || (shpType-5)%10 == 0) // Polylines + else if ((shpType - 3) % 10 == 0 || (shpType - 5) % 10 == 0) // Polylines { - _choice1 = new QRadioButton("Read as Polylines"); - _choice2 = new QRadioButton("Read as Polygons"); - if ((shpType-3)%10 == 0) _choice2->setDisabled(true); // disable polygon-choice if file contains only polylines - _choice1->toggle(); // default choice - _layout->addWidget( _shpContentLabel ); - _layout->addWidget( _choice1 ); - _layout->addWidget( _choice2 ); - _layout->addWidget( _nameLabel ); - _layout->addWidget( _listName ); - _fileType = 2; + _choice1 = new QRadioButton("Read as Polylines"); + _choice2 = new QRadioButton("Read as Polygons"); + if ((shpType - 3) % 10 == 0) + _choice2->setDisabled(true); // disable polygon-choice if file contains only polylines + _choice1->toggle(); // default choice + _layout->addWidget( _shpContentLabel ); + _layout->addWidget( _choice1 ); + _layout->addWidget( _choice2 ); + _layout->addWidget( _nameLabel ); + _layout->addWidget( _listName ); + _fileType = 2; } else { - _nameLabel->setText("This element type is currently not supported."); - _layout->addWidget( _shpContentLabel ); - _layout->addWidget( _nameLabel ); + _nameLabel->setText("This element type is currently not supported."); + _layout->addWidget( _shpContentLabel ); + _layout->addWidget( _nameLabel ); } _buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); @@ -101,24 +107,34 @@ void SHPImportDialog::setupDialog() setLayout(_layout); } else - { OGSError::box("Error reading shapefile!"); - } } void SHPImportDialog::accept() { - if (_listName->text().compare("")==0) + if (_listName->text().compare("") == 0) { OGSError::box("Please insert a name for the data in this file."); return; } else { - if (_fileType==1 && _choice1->isChecked()) _shpInterface->readSHPFile(_filename, SHPInterface::POINT, _listName->text().toStdString()); - if (_fileType==1 && _choice2->isChecked()) _shpInterface->readSHPFile(_filename, SHPInterface::STATION, _listName->text().toStdString()); - if (_fileType==2 && _choice1->isChecked()) _shpInterface->readSHPFile(_filename, SHPInterface::POLYLINE, _listName->text().toStdString()); - if (_fileType==2 && _choice2->isChecked()) _shpInterface->readSHPFile(_filename, SHPInterface::POLYGON, _listName->text().toStdString()); + if (_fileType == 1 && _choice1->isChecked()) + _shpInterface->readSHPFile(_filename, + SHPInterface::POINT, + _listName->text().toStdString()); + if (_fileType == 1 && _choice2->isChecked()) + _shpInterface->readSHPFile(_filename, + SHPInterface::STATION, + _listName->text().toStdString()); + if (_fileType == 2 && _choice1->isChecked()) + _shpInterface->readSHPFile(_filename, + SHPInterface::POLYLINE, + _listName->text().toStdString()); + if (_fileType == 2 && _choice2->isChecked()) + _shpInterface->readSHPFile(_filename, + SHPInterface::POLYGON, + _listName->text().toStdString()); emit shpLoaded(_listName->text()); } this->done(QDialog::Accepted); diff --git a/DataView/SHPImportDialog.h b/DataView/SHPImportDialog.h index 2383af595f4a08cd9107a04d66dcc7654bfe9ac9..82813e3dae2a39db9f95a12ed417a20ff0dd25e2 100644 --- a/DataView/SHPImportDialog.h +++ b/DataView/SHPImportDialog.h @@ -6,9 +6,8 @@ #ifndef SHPIMPORTDIALOG_H #define SHPIMPORTDIALOG_H -#include <QtGui/QMainWindow> #include <QDialog> - +#include <QtGui/QMainWindow> class SHPInterface; class GEOModels; @@ -33,8 +32,7 @@ public: SHPImportDialog(std::string filename, GEOModels* geoModels, QDialog* parent = 0); ~SHPImportDialog(); - QDialogButtonBox* _buttonBox; /// The buttons used in this dialog. - + QDialogButtonBox* _buttonBox; /// The buttons used in this dialog. private: /// Constructs a dialog window based on the information found in the selected shape file @@ -43,8 +41,8 @@ private: QGridLayout* _layout; QLabel* _shpContentLabel; QLabel* _nameLabel; - QLineEdit *_listName; - QRadioButton *_choice1, *_choice2;; + QLineEdit* _listName; + QRadioButton* _choice1, * _choice2; std::string _filename; short _fileType; SHPInterface* _shpInterface; diff --git a/DataView/StationTabWidget.cpp b/DataView/StationTabWidget.cpp index 3ff8f16e44a837fff1d9f7accdba44a8299ff142..c309fed97c8b9ac72d4da44ff0da38fe0d80d0fc 100644 --- a/DataView/StationTabWidget.cpp +++ b/DataView/StationTabWidget.cpp @@ -1,7 +1,7 @@ /** * \file StationTabWidget.cpp * 3/11/2009 LB Initial implementation - * + * * Implementation of StationTabWidget */ @@ -9,7 +9,7 @@ #include "StationTabWidget.h" StationTabWidget::StationTabWidget( QWidget* parent /*= 0*/ ) -: QWidget(parent) + : QWidget(parent) { setupUi(this); } diff --git a/DataView/StationTabWidget.h b/DataView/StationTabWidget.h index 4290240e912420a38bd787e6cc652593e5fd5add..ea7e9de9fba5886d22f3c3e4a5637d58293bdff9 100644 --- a/DataView/StationTabWidget.h +++ b/DataView/StationTabWidget.h @@ -4,7 +4,6 @@ * */ - #ifndef STATIONTABWIDGET_H #define STATIONTABWIDGET_H @@ -21,10 +20,7 @@ class StationTabWidget : public QWidget, public Ui_StationTabWidgetBase public: StationTabWidget(QWidget* parent = 0); - - private: - }; #endif // STATIONTABWIDGET_H diff --git a/DataView/StationTreeModel.cpp b/DataView/StationTreeModel.cpp index 1409a20515c38361f909ced688233653d00ebbb5..9f206c5b6e0265c2e49643e3e3e5f2d243ea1201 100644 --- a/DataView/StationTreeModel.cpp +++ b/DataView/StationTreeModel.cpp @@ -3,18 +3,18 @@ * KR Initial implementation */ -#include "StationTreeModel.h" -#include "Station.h" -#include "OGSError.h" #include "BaseItem.h" +#include "OGSError.h" +#include "Station.h" +#include "StationTreeModel.h" #include <QDebug> /** * Constructor. */ -StationTreeModel::StationTreeModel( QObject *parent ) -: TreeModel(parent) +StationTreeModel::StationTreeModel( QObject* parent ) + : TreeModel(parent) { QList<QVariant> rootData; delete _rootItem; @@ -33,19 +33,20 @@ StationTreeModel::~StationTreeModel() * \param parent The parent of the item * \return The model index of the item */ -QModelIndex StationTreeModel::index( int row, int column, const QModelIndex &parent /*= QModelIndex()*/ ) const +QModelIndex StationTreeModel::index( int row, int column, + const QModelIndex &parent /*= QModelIndex()*/ ) const { if (!hasIndex(row, column, parent)) return QModelIndex(); - ModelTreeItem *parentItem; + ModelTreeItem* parentItem; if (!parent.isValid()) parentItem = (ModelTreeItem*)(_rootItem); else parentItem = static_cast<ModelTreeItem*>(parent.internalPointer()); - ModelTreeItem *childItem = (ModelTreeItem*)(parentItem->child(row)); + ModelTreeItem* childItem = (ModelTreeItem*)(parentItem->child(row)); if (childItem) { QModelIndex newIndex = createIndex(row, column, childItem); @@ -65,18 +66,18 @@ QModelIndex StationTreeModel::index( int row, int column, const QModelIndex &par * \param index Index of the requested item * \return The BaseItem associated with the tree item * -BaseItem* StationTreeModel::itemFromIndex( const QModelIndex& index ) const -{ - if (index.isValid()) - { - ModelTreeItem* treeItem = static_cast<ModelTreeItem*>(index.internalPointer()); - BaseItem* baseItem = treeItem->getItem(); - return baseItem; - } - else - return NULL; -} -*/ + BaseItem* StationTreeModel::itemFromIndex( const QModelIndex& index ) const + { + if (index.isValid()) + { + ModelTreeItem* treeItem = static_cast<ModelTreeItem*>(index.internalPointer()); + BaseItem* baseItem = treeItem->getItem(); + return baseItem; + } + else + return NULL; + } + */ /** * Returns the Station-Object of the ModelTreeItem with the given index and the name of the list this station belongs to. @@ -84,7 +85,8 @@ BaseItem* StationTreeModel::itemFromIndex( const QModelIndex& index ) const * \param listName Here, the method will put the name of the list this station belongs to. * \return The station object associated with the tree item */ -GEOLIB::Station* StationTreeModel::stationFromIndex( const QModelIndex& index, QString &listName ) const +GEOLIB::Station* StationTreeModel::stationFromIndex( const QModelIndex& index, + QString &listName ) const { if (index.isValid()) { @@ -97,15 +99,12 @@ GEOLIB::Station* StationTreeModel::stationFromIndex( const QModelIndex& index, Q return NULL; } - vtkPolyDataAlgorithm* StationTreeModel::vtkSource(const std::string &name) const { size_t nLists = _lists.size(); - for (size_t i=0; i<nLists; i++) - { + for (size_t i = 0; i < nLists; i++) if ( name.compare( _lists[i]->data(0).toString().toStdString() ) == 0 ) return dynamic_cast<BaseItem*>(_lists[i]->getItem())->vtkSource(); - } return NULL; } @@ -114,13 +113,13 @@ vtkPolyDataAlgorithm* StationTreeModel::vtkSource(const std::string &name) const * \param listName Name of the new subtree. If no name is given a default name is assigned. * \param stations The list with stations to be added as children of that subtree */ -void StationTreeModel::addStationList(QString listName, const std::vector<GEOLIB::Point*> *stations) +void StationTreeModel::addStationList(QString listName, const std::vector<GEOLIB::Point*>* stations) { QList<QVariant> grpName; - if (listName.compare("")==0) // if no name is given a default name is assigned + if (listName.compare("") == 0) // if no name is given a default name is assigned { listName = "List"; - listName.append(QString::number(rowCount()+1)); + listName.append(QString::number(rowCount() + 1)); } grpName.push_back(QVariant(listName)); grpName.push_back(QVariant("")); @@ -132,10 +131,13 @@ void StationTreeModel::addStationList(QString listName, const std::vector<GEOLIB _rootItem->appendChild(group); int vectorSize = stations->size(); - for (int i=0; i<vectorSize; i++) + for (int i = 0; i < vectorSize; i++) { QList<QVariant> stn; - stn.push_back(QVariant(QString::fromStdString(static_cast<GEOLIB::Station*>((*stations)[i])->getName()))); + stn.push_back(QVariant(QString::fromStdString(static_cast<GEOLIB::Station*>((* + stations) + [i])-> + getName()))); stn.push_back(QVariant(QString::number((*(*stations)[i])[0],'f'))); stn.push_back(QVariant(QString::number((*(*stations)[i])[1],'f'))); stn.push_back(QVariant(QString::number((*(*stations)[i])[2],'f'))); @@ -160,8 +162,9 @@ void StationTreeModel::removeStationList(QModelIndex index) ModelTreeItem* item = static_cast<ModelTreeItem*>(getItem(index)); // also delete the lists entry in the list directory of the model - for (size_t i=0; i<_lists.size(); i++) - if (item == _lists[i]) _lists.erase(_lists.begin() + i); + for (size_t i = 0; i < _lists.size(); i++) + if (item == _lists[i]) + _lists.erase(_lists.begin() + i); removeRows(0, item->childCount(), index); removeRows(item->row(), 1, parent(index)); @@ -173,11 +176,9 @@ void StationTreeModel::removeStationList(QModelIndex index) */ void StationTreeModel::removeStationList(const std::string &name) { - for (size_t i=0; i<_lists.size(); i++) - { + for (size_t i = 0; i < _lists.size(); i++) if ( name.compare( _lists[i]->data(0).toString().toStdString() ) == 0 ) removeStationList(createIndex(_lists[i]->row(), 0, _lists[i])); - } } /* @@ -189,51 +190,52 @@ void StationTreeModel::removeStationList(const std::string &name) * \param name The name of the item that should be found * \return The QModelIndex of the desired item (or an empty index if no such item exists). * -QModelIndex StationTreeModel::getItemByName(const QModelIndex &idx, const std::string &name) const -{ - QModelIndex didx; - TreeItem* item = getItem(idx); - - int nChildren = item->childCount(); - for (int i=0; i<nChildren; i++) - { - TreeItem* child = item->child(i); - QString test = child->data(0).toString(); - - if ( name.compare(child->data(0).toString().toStdString()) != 0 ) - didx = getItemByName( index(i, 0, idx), name ); - else didx = index(i, 0, idx); - if (didx.isValid()) - return didx; - - } - - return QModelIndex(); // this is no valid QModelIndex and signifies that no item by the given name could be found. -} -*/ + QModelIndex StationTreeModel::getItemByName(const QModelIndex &idx, const std::string &name) const + { + QModelIndex didx; + TreeItem* item = getItem(idx); + + int nChildren = item->childCount(); + for (int i=0; i<nChildren; i++) + { + TreeItem* child = item->child(i); + QString test = child->data(0).toString(); + + if ( name.compare(child->data(0).toString().toStdString()) != 0 ) + didx = getItemByName( index(i, 0, idx), name ); + else didx = index(i, 0, idx); + if (didx.isValid()) + return didx; + + } + + return QModelIndex(); // this is no valid QModelIndex and signifies that no item by the given name could be found. + } + */ /** * Filters the station list based on the property boundaries given in bounds. * Technically, the complete station list is removed from the model and only those items are re-loaded that fit the description. * If no station in the list fulfills the given description an error msg is given. */ -void StationTreeModel::filterStations(const std::string &listName, const std::vector<GEOLIB::Point*> *stations, const std::vector<PropertyBounds> &bounds) +void StationTreeModel::filterStations(const std::string &listName, + const std::vector<GEOLIB::Point*>* stations, + const std::vector<PropertyBounds> &bounds) { - std::vector<GEOLIB::Point*> *filteredStations = new std::vector<GEOLIB::Point*>; + std::vector<GEOLIB::Point*>* filteredStations = new std::vector<GEOLIB::Point*>; size_t vectorSize = stations->size(); - for (size_t i=0; i<vectorSize; i++) - { + for (size_t i = 0; i < vectorSize; i++) if (static_cast<GEOLIB::Station*>((*stations)[i])->inSelection(bounds)) filteredStations->push_back((*stations)[i]); - } if (filteredStations->empty()) - OGSError::box("No object is within the given boundaries."); //The filtered list is empty. + OGSError::box("No object is within the given boundaries."); //The filtered list is empty. else { removeStationList(listName); this->addStationList(QString::fromStdString(listName), filteredStations); - std::cout << "Filter applied to List \"" << listName << "\", " << filteredStations->size() << " items added."; + std::cout << "Filter applied to List \"" << listName << "\", " << + filteredStations->size() << " items added."; } } diff --git a/DataView/StationTreeModel.h b/DataView/StationTreeModel.h index 3d3e3cec04ff575c81dbb75fd78057c7e87d397d..4d0c5fe82d6619f22c301b303bb2a19c072ea31a 100644 --- a/DataView/StationTreeModel.h +++ b/DataView/StationTreeModel.h @@ -6,17 +6,17 @@ #ifndef QSTATIONTREEMODEL_H #define QSTATIONTREEMODEL_H - #include <vector> +#include "ModelTreeItem.h" #include "Point.h" #include "TreeModel.h" -#include "ModelTreeItem.h" #include <vtkPolyDataAlgorithm.h> -namespace GEOLIB { - class Station; - class StationBorehole; +namespace GEOLIB +{ +class Station; +class StationBorehole; } class QString; @@ -25,7 +25,7 @@ class PropertyBounds; /** * \brief A model for the StationTreeView implementing a tree as a double-linked list. - * + * * A model for the StationTreeView implementing a tree as a double-linked list. * In addition to a simple TreeModel each item also contains a 2D / 3D GraphicsItem for visualization. * \sa TreeModel, StationTreeView, TreeItem, ModelTreeItem @@ -38,8 +38,10 @@ public: StationTreeModel(QObject* parent = 0); ~StationTreeModel(); - void addStationList(QString listName, const std::vector<GEOLIB::Point*> *stations); - void filterStations(const std::string &name, const std::vector<GEOLIB::Point*> *stations, const std::vector<PropertyBounds> &bounds); + void addStationList(QString listName, const std::vector<GEOLIB::Point*>* stations); + void filterStations(const std::string &name, + const std::vector<GEOLIB::Point*>* stations, + const std::vector<PropertyBounds> &bounds); const std::vector<ModelTreeItem*> &getLists() { return _lists; } QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; //BaseItem* itemFromIndex( const QModelIndex& index ) const; @@ -50,7 +52,6 @@ public: private: std::vector<ModelTreeItem*> _lists; - }; #endif //QSTATIONTREEMODEL_H diff --git a/DataView/StationTreeView.cpp b/DataView/StationTreeView.cpp index ec3b8568c770076e0026c9b05f3eedecfaf94e6e..400765c85d4865b658d88134ccc2941732a0cb43 100644 --- a/DataView/StationTreeView.cpp +++ b/DataView/StationTreeView.cpp @@ -3,22 +3,20 @@ * KR Initial implementation */ -#include <iostream> #include <QFileDialog> #include <QMenu> +#include <iostream> +#include "GMSInterface.h" #include "Station.h" #include "StationIO.h" -#include "GMSInterface.h" -#include "StationTreeView.h" -#include "StationTreeModel.h" -#include "ModelTreeItem.h" -#include "StratWindow.h" #include "DiagramPrefsDialog.h" +#include "ModelTreeItem.h" #include "OGSError.h" - - +#include "StationTreeModel.h" +#include "StationTreeView.h" +#include "StratWindow.h" StationTreeView::StationTreeView(QWidget* parent) : QTreeView(parent) { @@ -39,13 +37,15 @@ void StationTreeView::on_Clicked(QModelIndex idx) qDebug("%d, %d",idx.parent().row(), idx.row()); } -void StationTreeView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) +void StationTreeView::selectionChanged( const QItemSelection &selected, + const QItemSelection &deselected ) { emit itemSelectionChanged(selected, deselected); return QTreeView::selectionChanged(selected, deselected); } -void StationTreeView::selectionChangedFromOutside( const QItemSelection &selected, const QItemSelection &deselected ) +void StationTreeView::selectionChangedFromOutside( const QItemSelection &selected, + const QItemSelection &deselected ) { QItemSelectionModel* selModel = this->selectionModel(); @@ -63,7 +63,7 @@ void StationTreeView::contextMenuEvent( QContextMenuEvent* event ) ModelTreeItem* item = static_cast<ModelTreeItem*>(index.internalPointer()); // The current index refers to a parent item (e.g. a listname) - if (item->childCount()>0) + if (item->childCount() > 0) { QMenu menu; QAction* propertyAction = menu.addAction("Display list properties..."); @@ -84,7 +84,9 @@ void StationTreeView::contextMenuEvent( QContextMenuEvent* event ) QString temp_name; QMenu menu; - if (static_cast<StationTreeModel*>(model())->stationFromIndex(index, temp_name)->type() == GEOLIB::Station::BOREHOLE) + if (static_cast<StationTreeModel*>(model())->stationFromIndex(index, + temp_name)->type() == + GEOLIB::Station::BOREHOLE) { QAction* stratAction = menu.addAction("Display Stratigraphy..."); QAction* exportAction = menu.addAction("Export to GMS..."); @@ -96,7 +98,8 @@ void StationTreeView::contextMenuEvent( QContextMenuEvent* event ) { menu.addAction("View Information..."); QAction* showDiagramAction = menu.addAction("View Diagram..."); - connect(showDiagramAction, SIGNAL(triggered()), this, SLOT(showDiagramPrefsDialog())); + connect(showDiagramAction, SIGNAL(triggered()), this, + SLOT(showDiagramPrefsDialog())); menu.exec(event->globalPos()); } } @@ -108,23 +111,33 @@ void StationTreeView::displayStratigraphy() QString temp_name; // get list name - static_cast<StationTreeModel*>(model())->stationFromIndex(this->selectionModel()->currentIndex(), temp_name); + static_cast<StationTreeModel*>(model())->stationFromIndex( + this->selectionModel()->currentIndex(), temp_name); // get color table (horrible way to do it but there you go ...) - std::map<std::string, GEOLIB::Color*> colorLookupTable = static_cast<VtkStationSource*>(static_cast<StationTreeModel*>(model())->vtkSource(temp_name.toStdString()))->getColorLookupTable(); - StratWindow* stratView = new StratWindow(static_cast<GEOLIB::StationBorehole*>(static_cast<StationTreeModel*>(model())->stationFromIndex(index, temp_name)), &colorLookupTable); + std::map<std::string, + GEOLIB::Color*> colorLookupTable = + static_cast<VtkStationSource*>(static_cast<StationTreeModel*>(model())->vtkSource( + temp_name. + toStdString())) + ->getColorLookupTable(); + StratWindow* stratView = + new StratWindow(static_cast<GEOLIB::StationBorehole*>(static_cast<StationTreeModel*>( + model()) + ->stationFromIndex(index, + temp_name)), + &colorLookupTable); stratView->setAttribute(Qt::WA_DeleteOnClose); // this fixes the memory leak shown by cppcheck stratView->show(); } - void StationTreeView::saveList() { - TreeItem* item = static_cast<StationTreeModel*>(model())->getItem(this->selectionModel()->currentIndex()); + TreeItem* item = static_cast<StationTreeModel*>(model())->getItem( + this->selectionModel()->currentIndex()); QString listName = item->data(0).toString(); QString fileName = QFileDialog::getSaveFileName(this, "Save station list", "","*.stn"); - if (!fileName.isEmpty()) { + if (!fileName.isEmpty()) emit stationListSaved(listName, fileName); - } } void StationTreeView::exportList() @@ -133,29 +146,42 @@ void StationTreeView::exportList() //QString Name = static_cast<StationTreeModel*>(model())->getItem(this->selectionModel()->currentIndex())->data(0).toString(); //writeStratigraphiesAsImages(Name); - TreeItem* item = static_cast<StationTreeModel*>(model())->getItem(this->selectionModel()->currentIndex()); + TreeItem* item = static_cast<StationTreeModel*>(model())->getItem( + this->selectionModel()->currentIndex()); std::string listName = item->data(0).toString().toStdString(); - QString fileName = QFileDialog::getSaveFileName(this, "Export Boreholes to GMS-Format", "","*.txt"); - if (!fileName.isEmpty()) { + QString fileName = QFileDialog::getSaveFileName(this, + "Export Boreholes to GMS-Format", + "", + "*.txt"); + if (!fileName.isEmpty()) emit stationListExportRequested(listName, fileName.toStdString()); - } } void StationTreeView::exportStation() { QModelIndex index = this->selectionModel()->currentIndex(); - QString fileName = QFileDialog::getSaveFileName(this, "Export Borehole to GMS-Format", "","*.txt"); - if (!fileName.isEmpty()) { - QString temp_name; + QString fileName = QFileDialog::getSaveFileName(this, + "Export Borehole to GMS-Format", + "", + "*.txt"); + if (!fileName.isEmpty()) + { + QString temp_name; std::vector<std::string> temp_soil_names; temp_soil_names.push_back(""); // soil name vector needs to be initialised - GMSInterface::writeBoreholeToGMS(static_cast<GEOLIB::StationBorehole*>(static_cast<StationTreeModel*>(model())->stationFromIndex(index, temp_name)), fileName.toStdString(), temp_soil_names); - } + GMSInterface::writeBoreholeToGMS(static_cast<GEOLIB::StationBorehole*>(static_cast< + StationTreeModel + *>( + model())->stationFromIndex(index, + temp_name)), + fileName.toStdString(), temp_soil_names); + } } void StationTreeView::removeStationList() { - TreeItem* item = static_cast<StationTreeModel*>(model())->getItem(this->selectionModel()->currentIndex()); + TreeItem* item = static_cast<StationTreeModel*>(model())->getItem( + this->selectionModel()->currentIndex()); emit stationListRemoved((item->data(0).toString()).toStdString()); } @@ -174,23 +200,38 @@ void StationTreeView::showDiagramPrefsDialog() void StationTreeView::writeStratigraphiesAsImages(QString listName) { - std::map<std::string, GEOLIB::Color*> colorLookupTable = static_cast<VtkStationSource*>(static_cast<StationTreeModel*>(model())->vtkSource(listName.toStdString()))->getColorLookupTable(); + std::map<std::string, + GEOLIB::Color*> colorLookupTable = + static_cast<VtkStationSource*>(static_cast<StationTreeModel*>(model())->vtkSource( + listName. + toStdString())) + ->getColorLookupTable(); std::vector<ModelTreeItem*> lists = static_cast<StationTreeModel*>(model())->getLists(); size_t nLists = lists.size(); - for (size_t i=0; i<nLists; i++) - { - if ( listName.toStdString().compare( lists[i]->data(0).toString().toStdString() ) == 0 ) + for (size_t i = 0; i < nLists; i++) + if ( listName.toStdString().compare( lists[i]->data(0).toString().toStdString() ) + == 0 ) { - const std::vector<GEOLIB::Point*> *stations = dynamic_cast<BaseItem*>(lists[i]->getItem())->getStations(); + const std::vector<GEOLIB::Point*>* stations = + dynamic_cast<BaseItem*>(lists[i]->getItem())->getStations(); - for (size_t i=0; i<stations->size(); i++) + for (size_t i = 0; i < stations->size(); i++) { - StratWindow* stratView = new StratWindow(static_cast<GEOLIB::StationBorehole*>((*stations)[i]), &colorLookupTable); + StratWindow* stratView = + new StratWindow(static_cast<GEOLIB::StationBorehole*>((* + stations) + [i]), + &colorLookupTable); stratView->setAttribute(Qt::WA_DeleteOnClose); // this fixes the memory leak shown by cppcheck stratView->show(); - stratView->stationView->saveAsImage("c:/project/" + QString::fromStdString(static_cast<GEOLIB::StationBorehole*>((*stations)[i])->getName()) + ".jpg"); + stratView->stationView->saveAsImage( + "c:/project/" + + QString::fromStdString(static_cast<GEOLIB::StationBorehole*>(( + * + stations) + [ + i])->getName()) + ".jpg"); stratView->close(); } } - } } diff --git a/DataView/StationTreeView.h b/DataView/StationTreeView.h index 9532c579cbcfce1a2a4e4b02b283d371c5184cbb..273c8a24c4758408f4b81f4d642a235ee8f6bd88 100644 --- a/DataView/StationTreeView.h +++ b/DataView/StationTreeView.h @@ -6,9 +6,9 @@ #ifndef QSTATIONTREEVIEW_H #define QSTATIONTREEVIEW_H -#include <QTreeView> -#include <QContextMenuEvent> #include "PropertyBounds.h" +#include <QContextMenuEvent> +#include <QTreeView> #include "Station.h" @@ -35,12 +35,13 @@ protected slots: void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); /// Instructions if the selection of items in the view has changed by events outside the view (i.e. by actions made in the visualisation). - void selectionChangedFromOutside(const QItemSelection &selected, const QItemSelection &deselected); + void selectionChangedFromOutside(const QItemSelection &selected, + const QItemSelection &deselected); private: /// Actions to be taken after a right mouse click is performed in the station view. void contextMenuEvent( QContextMenuEvent* e ); - + /// Create image files from all stratigraphies in a borehole vector void writeStratigraphiesAsImages(QString listName); @@ -55,7 +56,8 @@ private slots: void showDiagramPrefsDialog(); signals: - void itemSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected); + void itemSelectionChanged(const QItemSelection & selected, + const QItemSelection & deselected); void propertiesDialogRequested(std::string name); void stationListExportRequested(std::string listName, std::string fileName); void stationListRemoved(std::string name); diff --git a/DataView/StratView/StratBar.cpp b/DataView/StratView/StratBar.cpp index 46a7981381a65e9bf11d344509dcc7f94315d5aa..a49cfca9cedb8c98503ce47d42b82ec3e6206920 100644 --- a/DataView/StratView/StratBar.cpp +++ b/DataView/StratView/StratBar.cpp @@ -3,17 +3,18 @@ * 2010/03/16 - KR Initial implementation */ -#include <QPainter> #include "StratBar.h" +#include <QPainter> - -StratBar::StratBar(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors, QGraphicsItem* parent) : - QGraphicsItem(parent), _station(station) +StratBar::StratBar(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors, + QGraphicsItem* parent) : + QGraphicsItem(parent), _station(station) { - if (stratColors) _stratColors = *stratColors; + if (stratColors) + _stratColors = *stratColors; } - StratBar::~StratBar() { // std::map<std::string, GEOLIB::Color*>::iterator it; @@ -24,15 +25,15 @@ StratBar::~StratBar() QRectF StratBar::boundingRect() const { - return QRectF(0, 0, BARWIDTH+10, totalLogHeight()); + return QRectF(0, 0, BARWIDTH + 10, totalLogHeight()); } -void StratBar::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +void StratBar::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { Q_UNUSED (option) Q_UNUSED (widget) - double top=0, height=0; + double top = 0, height = 0; QPen pen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin); pen.setCosmetic(true); @@ -44,34 +45,33 @@ void StratBar::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, std::vector<std::string> soilNames = _station->getSoilNames(); size_t nLayers = profile.size(); - painter->drawLine(0, 0, BARWIDTH+5 , 0); + painter->drawLine(0, 0, BARWIDTH + 5, 0); - for (size_t i = 1; i < nLayers ; i++) + for (size_t i = 1; i < nLayers; i++) { top += height; - height = logHeight(((*(profile[i-1]))[2]-(*(profile[i]))[2])); + height = logHeight(((*(profile[i - 1]))[2] - (*(profile[i]))[2])); QRectF layer(0, top, BARWIDTH, height); - const GEOLIB::Color *c (GEOLIB::getColor(soilNames[i], _stratColors)); - QBrush brush(QColor((int)(*c)[0], (int)(*c)[1], (int)(*c)[2], 127), Qt::SolidPattern); + const GEOLIB::Color* c (GEOLIB::getColor(soilNames[i], _stratColors)); + QBrush brush(QColor((int)(*c)[0], + (int)(*c)[1], + (int)(*c)[2], + 127), Qt::SolidPattern); painter->setBrush(brush); painter->drawRect(layer); - painter->drawLine(0, (int)layer.bottom(), BARWIDTH+5 , (int)layer.bottom()); + painter->drawLine(0, (int)layer.bottom(), BARWIDTH + 5, (int)layer.bottom()); //painter->drawText(BARWIDTH+10, layer.bottom(), QString::number((*(profile[i]))[2])); - } + } } - double StratBar::totalLogHeight() const { - double height=0; + double height = 0; std::vector<GEOLIB::Point*> profile = _station->getProfile(); - for (size_t i=1; i<profile.size(); i++) - { - height += ( log((*(profile[i-1]))[2]-(*(profile[i]))[2]+1)*100 ); - } + for (size_t i = 1; i < profile.size(); i++) + height += ( log((*(profile[i - 1]))[2] - (*(profile[i]))[2] + 1) * 100 ); return height; - } diff --git a/DataView/StratView/StratBar.h b/DataView/StratView/StratBar.h index 354344cd470baaf95f5326370d27b50513ad80d1..2bff5e45659ff3d8495d2b098c20da347b4e8e5a 100644 --- a/DataView/StratView/StratBar.h +++ b/DataView/StratView/StratBar.h @@ -6,9 +6,9 @@ #ifndef STRATBAR_H #define STRATBAR_H -#include <cmath> -#include <QGraphicsItem> #include "Station.h" +#include <QGraphicsItem> +#include <cmath> /** * \brief A 2D bar visualisation of a borehole stratigraphy. @@ -24,23 +24,25 @@ public: * \param stratColors A color map. * \param parent The parent QGraphicsItem. */ - StratBar(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors = NULL, QGraphicsItem* parent = 0); + StratBar(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors = NULL, + QGraphicsItem* parent = 0); ~StratBar(); /// Returns the bounding rectangle of the bar. QRectF boundingRect() const; /// Paints the bar. - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); private: /** * \brief Calculates the height for a soil layer by "log(d+1)*100". * \param h The original thickness of the soil layer. - */ - double logHeight(double h) const { return log(h+1)*100; } + */ + double logHeight(double h) const { return log(h + 1) * 100; } - /// Calculates the total height of the bar by calculating and adding the log-height for all layers in the borehole + /// Calculates the total height of the bar by calculating and adding the log-height for all layers in the borehole double totalLogHeight() const; /// The default width of the bar @@ -48,7 +50,6 @@ private: GEOLIB::StationBorehole* _station; std::map<std::string, GEOLIB::Color*> _stratColors; - }; #endif //STRATBAR_H diff --git a/DataView/StratView/StratScene.cpp b/DataView/StratView/StratScene.cpp index 1c5ac5a3b6d745a26dead17b57ab9ba387eaf083..c4bbe6477f73818eec7d8bd76555c951aeebab4f 100644 --- a/DataView/StratView/StratScene.cpp +++ b/DataView/StratView/StratScene.cpp @@ -8,34 +8,38 @@ #include <QGraphicsTextItem> -#include "StratScene.h" -#include "StratBar.h" -#include "QNonScalableGraphicsTextItem.h" #include "DateTools.h" +#include "QNonScalableGraphicsTextItem.h" +#include "StratBar.h" +#include "StratScene.h" - -StratScene::StratScene(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors, QObject* parent) : QGraphicsScene(parent) +StratScene::StratScene(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors, + QObject* parent) : QGraphicsScene(parent) { QRectF textBounds; int stratBarOffset = 250; - QFont font( "Arial" , 15, QFont::DemiBold, false); + QFont font( "Arial", 15, QFont::DemiBold, false); QNonScalableGraphicsTextItem* boreholeTag = addNonScalableText("Borehole", font); - QNonScalableGraphicsTextItem* boreholeName = addNonScalableText("\"" + QString::fromStdString(station->getName()) + "\"", font); + QNonScalableGraphicsTextItem* boreholeName = addNonScalableText( + "\"" + QString::fromStdString(station->getName()) + "\"", + font); textBounds = boreholeTag->boundingRect(); - boreholeTag->setPos((textBounds.width()/2.0), 80); + boreholeTag->setPos((textBounds.width() / 2.0), 80); textBounds = boreholeName->boundingRect(); - boreholeName->setPos((textBounds.width()/2.0), 200); + boreholeName->setPos((textBounds.width() / 2.0), 200); - QNonScalableGraphicsTextItem* totalDepth = addNonScalableText("Depth: " + QString::number(station->getDepth()) + " m"); + QNonScalableGraphicsTextItem* totalDepth = + addNonScalableText("Depth: " + QString::number(station->getDepth()) + " m"); textBounds = totalDepth->boundingRect(); - totalDepth->setPos((textBounds.width()/2.0), 350); + totalDepth->setPos((textBounds.width() / 2.0), 350); /* - QNonScalableGraphicsTextItem* dateText = addNonScalableText("Date: " + QString::fromStdString(date2string(station->getDate()))); - textBounds = dateText->boundingRect(); - dateText->setPos(this->MARGIN + (textBounds.width()/2.0), 350); -*/ + QNonScalableGraphicsTextItem* dateText = addNonScalableText("Date: " + QString::fromStdString(date2string(station->getDate()))); + textBounds = dateText->boundingRect(); + dateText->setPos(this->MARGIN + (textBounds.width()/2.0), 350); + */ QNonScalableGraphicsTextItem* dot = addNonScalableText(" "); dot->setPos(0, 0); @@ -45,9 +49,9 @@ StratScene::StratScene(GEOLIB::StationBorehole* station, std::map<std::string, G addDepthLabels(station->getProfile(), stratBarOffset + stratBarBounds.width()); - if (station->getSoilNames().size()>0) - addSoilNameLabels(station->getSoilNames(), station->getProfile(), stratBarOffset + (stratBarBounds.width()/2)); - + if (station->getSoilNames().size() > 0) + addSoilNameLabels(station->getSoilNames(), station->getProfile(), stratBarOffset + + (stratBarBounds.width() / 2)); } StratScene::~StratScene() @@ -61,26 +65,28 @@ void StratScene::addDepthLabels(std::vector<GEOLIB::Point*> profile, double offs std::vector<QNonScalableGraphicsTextItem*> depthText; depthText.push_back(addNonScalableText(QString::number((*(profile[0]))[2]))); textBounds = depthText[0]->boundingRect(); - depthText[0]->setPos(offset + textBounds.width()/2, vertPos); + depthText[0]->setPos(offset + textBounds.width() / 2, vertPos); - for (size_t i=1; i<profile.size(); i++) + for (size_t i = 1; i < profile.size(); i++) { depthText.push_back(addNonScalableText(QString::number((*(profile[i]))[2]))); - vertPos += log((*(profile[i-1]))[2]-(*(profile[i]))[2]+1)*100; + vertPos += log((*(profile[i - 1]))[2] - (*(profile[i]))[2] + 1) * 100; textBounds = depthText[i]->boundingRect(); - depthText[i]->setPos(offset + textBounds.width()/2, vertPos); + depthText[i]->setPos(offset + textBounds.width() / 2, vertPos); } } QNonScalableGraphicsTextItem* StratScene::addNonScalableText(const QString &text, const QFont &font) { - QNonScalableGraphicsTextItem *item = new QNonScalableGraphicsTextItem(text); - item->setFont(font); - addItem(item); - return item; + QNonScalableGraphicsTextItem* item = new QNonScalableGraphicsTextItem(text); + item->setFont(font); + addItem(item); + return item; } -void StratScene::addSoilNameLabels(std::vector<std::string> soilNames, std::vector<GEOLIB::Point*> profile, double offset) +void StratScene::addSoilNameLabels(std::vector<std::string> soilNames, + std::vector<GEOLIB::Point*> profile, + double offset) { //QRectF textBounds; double vertPos = MARGIN, halfHeight = 0; @@ -89,17 +95,18 @@ void StratScene::addSoilNameLabels(std::vector<std::string> soilNames, std::vect //textBounds = soilText[0]->boundingRect(); soilText[0]->setPos(offset /* - textBounds.width() */, vertPos); - for (size_t i=1; i<soilNames.size(); i++) + for (size_t i = 1; i < soilNames.size(); i++) { soilText.push_back(addNonScalableText(QString::fromStdString(soilNames[i]))); - halfHeight = log((*(profile[i-1]))[2]-(*(profile[i]))[2]+1)*100 / 2; + halfHeight = log((*(profile[i - 1]))[2] - (*(profile[i]))[2] + 1) * 100 / 2; //textBounds = soilText[i]->boundingRect(); soilText[i]->setPos(offset /* - textBounds.width() */, vertPos + halfHeight); vertPos += ( 2 * halfHeight ); } } -StratBar* StratScene::addStratBar(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors) +StratBar* StratScene::addStratBar(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors) { StratBar* b = new StratBar(station, stratColors); addItem(b); diff --git a/DataView/StratView/StratScene.h b/DataView/StratView/StratScene.h index 028d0f5da1ec73ab94f465ced34bf67fad9de1f8..1dd2b192e2b340dcf0fc6fbed59dd3eb5276354b 100644 --- a/DataView/StratView/StratScene.h +++ b/DataView/StratView/StratScene.h @@ -6,8 +6,8 @@ #ifndef STRATSCENE_H #define STRATSCENE_H -#include <QGraphicsScene> #include "Station.h" +#include <QGraphicsScene> class StratBar; class QNonScalableGraphicsTextItem; @@ -19,25 +19,30 @@ class StratScene : public QGraphicsScene { public: /// Constructor - StratScene(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors = NULL, QObject* parent = 0); + StratScene(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors = NULL, + QObject* parent = 0); ~StratScene(); /// The margin between the boundary of the scene and the bounding box of all items within the scene - static const int MARGIN=50; + static const int MARGIN = 50; private: /// Adds text labels indicating the depth at the beginning and end of each soil layer void addDepthLabels(std::vector<GEOLIB::Point*> profile, double offset); /// Add a non-scalable text item to the scene. - QNonScalableGraphicsTextItem* addNonScalableText(const QString &text, const QFont &font = QFont()); + QNonScalableGraphicsTextItem* addNonScalableText(const QString &text, + const QFont &font = QFont()); /// Adds text labels indicating the name of each soil layer - void addSoilNameLabels(std::vector<std::string> soilNames, std::vector<GEOLIB::Point*> profile, double offset); + void addSoilNameLabels(std::vector<std::string> soilNames, + std::vector<GEOLIB::Point*> profile, + double offset); /// Add a stratigraphy-bar to the scene. - StratBar* addStratBar(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors = NULL); - + StratBar* addStratBar(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors = NULL); }; #endif //STRATSCENE_H diff --git a/DataView/StratView/StratView.cpp b/DataView/StratView/StratView.cpp index 1b15ada33dd68d1f3704451aa21c7a438c6dedf6..a3442d64196dbcd2f58af2067b82099d5c2ed728 100644 --- a/DataView/StratView/StratView.cpp +++ b/DataView/StratView/StratView.cpp @@ -3,17 +3,17 @@ * 2010/03/16 - KR Initial implementation */ -#include <math.h> -#include "StratView.h" #include "Station.h" - +#include "StratView.h" +#include <math.h> StratView::~StratView() { delete _scene; } -void StratView::setStation(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors) +void StratView::setStation(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors) { _scene = new StratScene(station, stratColors); setScene(_scene); @@ -38,7 +38,9 @@ void StratView::update() { QRectF viewRect = _scene->itemsBoundingRect(); _scene->setSceneRect(viewRect); - QRectF sceneInView(_scene->MARGIN,_scene->MARGIN,viewRect.width()+2*_scene->MARGIN,viewRect.height()+2*_scene->MARGIN); + QRectF sceneInView(_scene->MARGIN,_scene->MARGIN, + viewRect.width() + 2 * _scene->MARGIN, + viewRect.height() + 2 * _scene->MARGIN); fitInView(sceneInView, Qt::IgnoreAspectRatio); } @@ -47,7 +49,8 @@ void StratView::saveAsImage(QString fileName) this->update(); QRectF viewRect = _scene->itemsBoundingRect(); - QImage img(static_cast<int>(viewRect.width())+2*_scene->MARGIN, 600, QImage::Format_ARGB32); + QImage img( + static_cast<int>(viewRect.width()) + 2 * _scene->MARGIN, 600, QImage::Format_ARGB32); QPainter painter(&img); this->render(&painter); diff --git a/DataView/StratView/StratView.h b/DataView/StratView/StratView.h index 4ad8539c356b216876f3f520d6c6de1e29e64afb..634a5da7f730fcd66bb9cbc1c0c5b2fd33e5b7db 100644 --- a/DataView/StratView/StratView.h +++ b/DataView/StratView/StratView.h @@ -6,13 +6,13 @@ #ifndef STRATVIEW_H #define STRATVIEW_H -#include <QtGui/QWidget> -#include <QGraphicsView> #include "StratScene.h" +#include <QGraphicsView> +#include <QtGui/QWidget> namespace GEOLIB { - class StationBorehole; +class StationBorehole; } /** @@ -25,11 +25,12 @@ public: /** * Creates an empty view. */ - StratView(QWidget* parent = 0) : _scene(NULL) {Q_UNUSED(parent);} + StratView(QWidget* parent = 0) : _scene(NULL) {Q_UNUSED(parent); } ~StratView(); /// Sets the Borehole whose data should be visualised. - void setStation(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors = NULL); + void setStation(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors = NULL); /// Returns the height of the bounding rectangle of all objects within the scene. int getHeight() { return static_cast<int>((_scene->itemsBoundingRect()).height()); } @@ -44,14 +45,14 @@ protected: void resizeEvent(QResizeEvent* event); private: - /// Initialises the view. + /// Initialises the view. void initialize(); /// The minimum size of the window. - QSize minimumSizeHint() const { return QSize(3*_scene->MARGIN,2*_scene->MARGIN); } + QSize minimumSizeHint() const { return QSize(3 * _scene->MARGIN,2 * _scene->MARGIN); } /// The default size of the window. - QSize sizeHint() const { return QSize(6*_scene->MARGIN, 4*_scene->MARGIN); } + QSize sizeHint() const { return QSize(6 * _scene->MARGIN, 4 * _scene->MARGIN); } /// Updates the view automatically when a Borehole is added or when the window containing the view changes its state. void update(); diff --git a/DataView/StratView/StratWindow.cpp b/DataView/StratView/StratWindow.cpp index 7588d18e2b0ce790f48f592980d8d4e15280e62f..51facd10aa212fd56f837dd7965c20b0a80f0551 100644 --- a/DataView/StratView/StratWindow.cpp +++ b/DataView/StratView/StratWindow.cpp @@ -3,11 +3,12 @@ * 2010/03/16 - KR Initial implementation */ -#include "StratWindow.h" #include "Station.h" +#include "StratWindow.h" - -StratWindow::StratWindow(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors, QWidget* parent) : QWidget(parent) +StratWindow::StratWindow(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors, + QWidget* parent) : QWidget(parent) { setupUi(this); stationView->setRenderHints( QPainter::Antialiasing ); @@ -20,10 +21,9 @@ void StratWindow::on_closeButton_clicked() this->close(); } - void StratWindow::resizeWindow() { - int width = (stationView->getWidth()>800) ? 800 : stationView->getWidth(); - int height = (stationView->getHeight()>600) ? 600 : stationView->getHeight(); + int width = (stationView->getWidth() > 800) ? 800 : stationView->getWidth(); + int height = (stationView->getHeight() > 600) ? 600 : stationView->getHeight(); resize(width, height); } diff --git a/DataView/StratView/StratWindow.h b/DataView/StratView/StratWindow.h index 28a03afbeb1dd00d21387fc4d1be73958361d87e..e51c1ef48d502962b27a6fd3f229123bffe1646d 100644 --- a/DataView/StratView/StratWindow.h +++ b/DataView/StratView/StratWindow.h @@ -6,12 +6,12 @@ #ifndef STRATWINDOW_H #define STRATWINDOW_H -#include <QWidget> #include "ui_StratWindow.h" +#include <QWidget> namespace GEOLIB { - class StationBorehole; +class StationBorehole; } /** @@ -28,8 +28,10 @@ public: * \param stratColors A color map. * \param parent The parent QWidget. */ - StratWindow(GEOLIB::StationBorehole* station, std::map<std::string, GEOLIB::Color*> *stratColors = NULL, QWidget* parent = 0); - ~StratWindow(void) { this->destroy(); }; + StratWindow(GEOLIB::StationBorehole* station, + std::map<std::string, GEOLIB::Color*>* stratColors = NULL, + QWidget* parent = 0); + ~StratWindow(void) { this->destroy(); } private: /// Automatically resize window based on the measurements of the borehole. diff --git a/Gui/main.cpp b/Gui/main.cpp index 08110b276445a80ef78af9a9f65fdae8a886068e..37de4122690bd0a8d2a2c5b7266aa779f28d52b5 100644 --- a/Gui/main.cpp +++ b/Gui/main.cpp @@ -1,11 +1,11 @@ #include "Configure.h" -#include <QtGui/QApplication> #include "mainwindow.h" +#include <QtGui/QApplication> #ifdef OGS_USE_OPENSG #include <OpenSG/OSGBaseFunctions.h> #endif -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { #ifdef OGS_USE_OPENSG OSG::osgInit(argc, argv); diff --git a/Gui/mainwindow.cpp b/Gui/mainwindow.cpp index e6ed70bad77fcd36519ca6ec433fcad12b204ba6..c7dca3b5073398d0398c70c83f95812dbbc57270 100644 --- a/Gui/mainwindow.cpp +++ b/Gui/mainwindow.cpp @@ -7,12 +7,12 @@ #include "mainwindow.h" // models +#include "ConditionModel.h" +#include "ElementTreeModel.h" #include "GEOModels.h" #include "GeoTreeModel.h" -#include "StationTreeModel.h" #include "MshModel.h" -#include "ElementTreeModel.h" -#include "ConditionModel.h" +#include "StationTreeModel.h" //dialogs #include "DBConnectionDialog.h" @@ -21,46 +21,46 @@ #include "LineEditDialog.h" #include "ListPropertiesDialog.h" #include "MshQualitySelectionDialog.h" -#include "VtkAddFilterDialog.h" #include "VisPrefsDialog.h" +#include "VtkAddFilterDialog.h" #ifdef Shapelib_FOUND #include "SHPImportDialog.h" #endif -#include "OGSRaster.h" +#include "DatabaseConnection.h" #include "OGSError.h" -#include "VtkVisPipeline.h" -#include "VtkVisPipelineItem.h" +#include "OGSRaster.h" #include "RecentFiles.h" #include "TreeModelIterator.h" -#include "VtkGeoImageSource.h" #include "VtkBGImageSource.h" -#include "DatabaseConnection.h" +#include "VtkGeoImageSource.h" +#include "VtkVisPipeline.h" +#include "VtkVisPipelineItem.h" //test #include "BoundaryCondition.h" #include "InitialCondition.h" +#include "MathIO/CRSIO.h" +#include "Raster.h" #include "SourceTerm.h" #include "rf_bc_new.h" -#include "rf_st_new.h" #include "rf_ic_new.h" +#include "rf_st_new.h" #include "wait.h" -#include "MathIO/CRSIO.h" -#include "Raster.h" // FileIO includes -#include "OGSIOVer4.h" -#include "StationIO.h" -#include "PetrelInterface.h" -#include "GocadInterface.h" -#include "XMLInterface.h" -#include "MeshIO/GMSHInterface.h" +#include "FEFLOWInterface.h" #include "GMSInterface.h" -#include "NetCDFInterface.h" //YW 07.2010 #include "GeoIO/Gmsh2GeoIO.h" -#include "FEFLOWInterface.h" +#include "GocadInterface.h" +#include "MeshIO/GMSHInterface.h" #include "MeshIO/TetGenInterface.h" +#include "NetCDFInterface.h" //YW 07.2010 +#include "OGSIOVer4.h" +#include "PetrelInterface.h" +#include "StationIO.h" +#include "XMLInterface.h" #include "StringTools.h" @@ -71,21 +71,21 @@ #include "ExtractMeshNodes.h" // Qt includes +#include <QDesktopWidget> #include <QFileDialog> #include <QMessageBox> #include <QSettings> -#include <QDesktopWidget> // VTK includes -#include <vtkVRMLExporter.h> #include <vtkOBJExporter.h> #include <vtkRenderer.h> +#include <vtkVRMLExporter.h> #ifdef OGS_USE_OPENSG -#include <OpenSG/OSGSceneFileHandler.h> +#include "vtkOsgConverter.h" #include <OpenSG/OSGCoredNodePtr.h> #include <OpenSG/OSGGroup.h> -#include "vtkOsgConverter.h" +#include <OpenSG/OSGSceneFileHandler.h> #endif #ifdef OGS_USE_VRPN @@ -95,14 +95,14 @@ /// FEM. 11.03.2010. WW #include "problem.h" -Problem *aproblem = NULL; +Problem* aproblem = NULL; using namespace FileIO; -MainWindow::MainWindow(QWidget *parent /* = 0*/) -: QMainWindow(parent), _db (NULL), _project() +MainWindow::MainWindow(QWidget* parent /* = 0*/) + : QMainWindow(parent), _db (NULL), _project() { - setupUi(this); + setupUi(this); // Setup various models _geoModels = new GEOModels(); @@ -122,116 +122,118 @@ MainWindow::MainWindow(QWidget *parent /* = 0*/) // station model connects connect(stationTabWidget->treeView, - SIGNAL(stationListExportRequested(std::string, std::string)), - this, SLOT(exportBoreholesToGMS(std::string, std::string))); // export Stationlist to GMS + SIGNAL(stationListExportRequested(std::string, std::string)), + this, SLOT(exportBoreholesToGMS(std::string, std::string))); // export Stationlist to GMS connect(stationTabWidget->treeView, - SIGNAL(stationListRemoved(std::string)), _geoModels, - SLOT(removeStationVec(std::string))); // update model when stations are removed + SIGNAL(stationListRemoved(std::string)), _geoModels, + SLOT(removeStationVec(std::string))); // update model when stations are removed connect(stationTabWidget->treeView, - SIGNAL(stationListSaved(QString, QString)), this, - SLOT(writeStationListToFile(QString, QString))); // save Stationlist to File + SIGNAL(stationListSaved(QString, QString)), this, + SLOT(writeStationListToFile(QString, QString))); // save Stationlist to File connect(_geoModels, - SIGNAL(stationVectorRemoved(StationTreeModel*, std::string)), - this, SLOT(updateDataViews())); // update data view when stations are removed - connect(stationTabWidget->treeView, SIGNAL(diagramRequested(QModelIndex&)), - this, SLOT(showDiagramPrefsDialog(QModelIndex&))); // connect treeview to diagramview + SIGNAL(stationVectorRemoved(StationTreeModel *, std::string)), + this, SLOT(updateDataViews())); // update data view when stations are removed + connect(stationTabWidget->treeView, SIGNAL(diagramRequested(QModelIndex &)), + this, SLOT(showDiagramPrefsDialog(QModelIndex &))); // connect treeview to diagramview // geo model connects connect(geoTabWidget->treeView, SIGNAL(listRemoved(std::string, GEOLIB::GEOTYPE)), - _geoModels, SLOT(removeGeometry(std::string, GEOLIB::GEOTYPE))); - connect(geoTabWidget->treeView, SIGNAL(saveToFileRequested(QString, QString)), - this, SLOT(writeGeometryToFile(QString, QString))); // save geometry to file - connect(geoTabWidget->treeView, SIGNAL(requestLineEditDialog(const std::string&)), - this, SLOT(showLineEditDialog(const std::string&))); // open line edit dialog - connect(geoTabWidget->treeView, SIGNAL(loadFEMCondFileRequested(std::string)), - this, SLOT(loadFEMConditionsFromFile(std::string))); // add FEM Conditions - connect(_geoModels, SIGNAL(geoDataAdded(GeoTreeModel*, std::string, GEOLIB::GEOTYPE)), - this, SLOT(updateDataViews())); - connect(_geoModels, SIGNAL(geoDataRemoved(GeoTreeModel*, std::string, GEOLIB::GEOTYPE)), - this, SLOT(updateDataViews())); + _geoModels, SLOT(removeGeometry(std::string, GEOLIB::GEOTYPE))); + connect(geoTabWidget->treeView, SIGNAL(saveToFileRequested(QString, QString)), + this, SLOT(writeGeometryToFile(QString, QString))); // save geometry to file + connect(geoTabWidget->treeView, SIGNAL(requestLineEditDialog(const std::string &)), + this, SLOT(showLineEditDialog(const std::string &))); // open line edit dialog + connect(geoTabWidget->treeView, SIGNAL(loadFEMCondFileRequested(std::string)), + this, SLOT(loadFEMConditionsFromFile(std::string))); // add FEM Conditions + connect(_geoModels, SIGNAL(geoDataAdded(GeoTreeModel *, std::string, GEOLIB::GEOTYPE)), + this, SLOT(updateDataViews())); + connect(_geoModels, SIGNAL(geoDataRemoved(GeoTreeModel *, std::string, GEOLIB::GEOTYPE)), + this, SLOT(updateDataViews())); //connect(_geoModels, SIGNAL(geoDataRemoved(GeoTreeModel*, std::string, GEOLIB::GEOTYPE)), // _conditionModel, SLOT(removeFEMConditions(std::string, GEOLIB::GEOTYPE))); - // Setup connections for mesh models to GUI - connect(mshTabWidget->treeView, SIGNAL(requestMeshRemoval(const QModelIndex&)), - _meshModels, SLOT(removeMesh(const QModelIndex&))); - connect(mshTabWidget->treeView, SIGNAL(requestMeshRemoval(const QModelIndex&)), - _elementModel, SLOT(clearView())); + connect(mshTabWidget->treeView, SIGNAL(requestMeshRemoval(const QModelIndex &)), + _meshModels, SLOT(removeMesh(const QModelIndex &))); + connect(mshTabWidget->treeView, SIGNAL(requestMeshRemoval(const QModelIndex &)), + _elementModel, SLOT(clearView())); connect(mshTabWidget->treeView, SIGNAL(qualityCheckRequested(VtkMeshSource*)), - this, SLOT(showMshQualitySelectionDialog(VtkMeshSource*))); - connect(mshTabWidget->treeView, SIGNAL(requestDIRECTSourceTerms(const std::vector<GEOLIB::Point*>*)), - this, SLOT(loadDIRECTSourceTerms(const std::vector<GEOLIB::Point*>*))); - - + this, SLOT(showMshQualitySelectionDialog(VtkMeshSource*))); + connect(mshTabWidget->treeView, + SIGNAL(requestDIRECTSourceTerms(const std::vector<GEOLIB::Point*>*)), + this, SLOT(loadDIRECTSourceTerms(const std::vector<GEOLIB::Point*>*))); // Setup connections for condition model to GUI - connect(conditionTabWidget->treeView, SIGNAL(conditionsRemoved(QString, FEMCondition::CondType)), - _conditionModel, SLOT(removeFEMConditions(QString, FEMCondition::CondType))); + connect(conditionTabWidget->treeView, + SIGNAL(conditionsRemoved(QString, FEMCondition::CondType)), + _conditionModel, SLOT(removeFEMConditions(QString, FEMCondition::CondType))); // VisPipeline Connects - connect(_geoModels, SIGNAL(geoDataAdded(GeoTreeModel*, std::string, GEOLIB::GEOTYPE)), - _vtkVisPipeline, SLOT(addPipelineItem(GeoTreeModel*, std::string, GEOLIB::GEOTYPE))); - connect(_geoModels, SIGNAL(geoDataRemoved(GeoTreeModel*, std::string, GEOLIB::GEOTYPE)), - _vtkVisPipeline, SLOT(removeSourceItem(GeoTreeModel*, std::string, GEOLIB::GEOTYPE))); - - connect(_conditionModel, SIGNAL(conditionAdded(ConditionModel*, std::string, FEMCondition::CondType)), - _vtkVisPipeline, SLOT(addPipelineItem(ConditionModel*, std::string, FEMCondition::CondType))); - connect(_conditionModel, SIGNAL(conditionsRemoved(ConditionModel*, std::string, FEMCondition::CondType)), - _vtkVisPipeline, SLOT(removeSourceItem(ConditionModel*, std::string, FEMCondition::CondType))); - - connect(_geoModels, SIGNAL(stationVectorAdded(StationTreeModel*, std::string)), - _vtkVisPipeline, SLOT(addPipelineItem(StationTreeModel*, std::string))); - connect(_geoModels, SIGNAL(stationVectorRemoved(StationTreeModel*, std::string)), - _vtkVisPipeline, SLOT(removeSourceItem(StationTreeModel*, std::string))); - - connect(_meshModels, SIGNAL(meshAdded(MshModel*, QModelIndex)), - _vtkVisPipeline, SLOT(addPipelineItem(MshModel*,QModelIndex))); - connect(_meshModels, SIGNAL(meshRemoved(MshModel*, QModelIndex)), - _vtkVisPipeline, SLOT(removeSourceItem(MshModel*, QModelIndex))); + connect(_geoModels, SIGNAL(geoDataAdded(GeoTreeModel *, std::string, GEOLIB::GEOTYPE)), + _vtkVisPipeline, SLOT(addPipelineItem(GeoTreeModel *, std::string, GEOLIB::GEOTYPE))); + connect(_geoModels, SIGNAL(geoDataRemoved(GeoTreeModel *, std::string, GEOLIB::GEOTYPE)), + _vtkVisPipeline, SLOT(removeSourceItem(GeoTreeModel *, std::string, GEOLIB::GEOTYPE))); + + connect(_conditionModel, + SIGNAL(conditionAdded(ConditionModel *, std::string, FEMCondition::CondType)), + _vtkVisPipeline, + SLOT(addPipelineItem(ConditionModel *, std::string, FEMCondition::CondType))); + connect(_conditionModel, + SIGNAL(conditionsRemoved(ConditionModel *, std::string, FEMCondition::CondType)), + _vtkVisPipeline, + SLOT(removeSourceItem(ConditionModel *, std::string, FEMCondition::CondType))); + + connect(_geoModels, SIGNAL(stationVectorAdded(StationTreeModel *, std::string)), + _vtkVisPipeline, SLOT(addPipelineItem(StationTreeModel *, std::string))); + connect(_geoModels, SIGNAL(stationVectorRemoved(StationTreeModel *, std::string)), + _vtkVisPipeline, SLOT(removeSourceItem(StationTreeModel *, std::string))); + + connect(_meshModels, SIGNAL(meshAdded(MshModel *, QModelIndex)), + _vtkVisPipeline, SLOT(addPipelineItem(MshModel *,QModelIndex))); + connect(_meshModels, SIGNAL(meshRemoved(MshModel *, QModelIndex)), + _vtkVisPipeline, SLOT(removeSourceItem(MshModel *, QModelIndex))); connect(_vtkVisPipeline, SIGNAL(vtkVisPipelineChanged()), - visualizationWidget->vtkWidget, SLOT(update())); + visualizationWidget->vtkWidget, SLOT(update())); connect(_vtkVisPipeline, SIGNAL(vtkVisPipelineChanged()), - vtkVisTabWidget->vtkVisPipelineView, SLOT(expandAll())); + vtkVisTabWidget->vtkVisPipelineView, SLOT(expandAll())); vtkVisTabWidget->vtkVisPipelineView->setModel(_vtkVisPipeline); connect(vtkVisTabWidget->vtkVisPipelineView, - SIGNAL(requestRemovePipelineItem(QModelIndex)), _vtkVisPipeline, - SLOT(removePipelineItem(QModelIndex))); + SIGNAL(requestRemovePipelineItem(QModelIndex)), _vtkVisPipeline, + SLOT(removePipelineItem(QModelIndex))); connect(vtkVisTabWidget->vtkVisPipelineView, - SIGNAL(requestAddPipelineFilterItem(QModelIndex)), this, - SLOT(showAddPipelineFilterItemDialog(QModelIndex))); + SIGNAL(requestAddPipelineFilterItem(QModelIndex)), this, + SLOT(showAddPipelineFilterItemDialog(QModelIndex))); connect(vtkVisTabWidget, SIGNAL(requestViewUpdate()), visualizationWidget, - SLOT(updateView())); + SLOT(updateView())); connect(vtkVisTabWidget->vtkVisPipelineView, - SIGNAL(actorSelected(vtkProp3D*)), - (QObject*) (visualizationWidget->interactorStyle()), - SLOT(highlightActor(vtkProp3D*))); + SIGNAL(actorSelected(vtkProp3D*)), + (QObject*) (visualizationWidget->interactorStyle()), + SLOT(highlightActor(vtkProp3D*))); connect((QObject*) (visualizationWidget->interactorStyle()), - SIGNAL(requestViewUpdate()), - visualizationWidget, SLOT(updateView())); + SIGNAL(requestViewUpdate()), + visualizationWidget, SLOT(updateView())); // Propagates selected vtk object in the pipeline to the pick interactor connect(vtkVisTabWidget->vtkVisPipelineView, - SIGNAL(dataObjectSelected(vtkDataObject*)), - (QObject*) (visualizationWidget->interactorStyle()), - SLOT(pickableDataObject(vtkDataObject*))); + SIGNAL(dataObjectSelected(vtkDataObject*)), + (QObject*) (visualizationWidget->interactorStyle()), + SLOT(pickableDataObject(vtkDataObject*))); connect((QObject*) (visualizationWidget->vtkPickCallback()), - SIGNAL(actorPicked(vtkProp3D*)), - vtkVisTabWidget->vtkVisPipelineView, SLOT(selectItem(vtkProp3D*))); + SIGNAL(actorPicked(vtkProp3D*)), + vtkVisTabWidget->vtkVisPipelineView, SLOT(selectItem(vtkProp3D*))); connect((QObject*) (visualizationWidget->interactorStyle()), - SIGNAL(elementPicked(const GridAdapter*, const size_t)), - this->_elementModel, SLOT(setElement(const GridAdapter*, const size_t))); + SIGNAL(elementPicked(const GridAdapter *, const size_t)), + this->_elementModel, SLOT(setElement(const GridAdapter *, const size_t))); connect((QObject*) (visualizationWidget->interactorStyle()), - SIGNAL(elementPicked(const GridAdapter*, const size_t)), - mshTabWidget->elementView, SLOT(updateView())); - + SIGNAL(elementPicked(const GridAdapter *, const size_t)), + mshTabWidget->elementView, SLOT(updateView())); connect(vtkVisTabWidget->vtkVisPipelineView, - SIGNAL(meshAdded(MeshLib::CFEMesh*, std::string&)), - _meshModels, SLOT(addMesh(MeshLib::CFEMesh*, std::string&))); + SIGNAL(meshAdded(MeshLib::CFEMesh *, std::string &)), + _meshModels, SLOT(addMesh(MeshLib::CFEMesh *, std::string &))); // Stack the data dock widgets together tabifyDockWidget(geoDock, mshDock); @@ -257,62 +259,62 @@ MainWindow::MainWindow(QWidget *parent /* = 0*/) // Setup recent files menu RecentFiles* recentFiles = new RecentFiles(this, SLOT(openRecentFile()), - "recentFileList", "OpenGeoSys-5"); + "recentFileList", "OpenGeoSys-5"); connect(this, SIGNAL(fileUsed(QString)), recentFiles, - SLOT(setCurrentFile(QString))); + SLOT(setCurrentFile(QString))); menu_File->insertMenu(action_Exit, recentFiles->menu()); // Setup Windows menu QAction* showGeoDockAction = geoDock->toggleViewAction(); showGeoDockAction->setStatusTip(tr("Shows / hides the geometry view")); connect(showGeoDockAction, SIGNAL(triggered(bool)), this, - SLOT(showGeoDockWidget(bool))); + SLOT(showGeoDockWidget(bool))); menuWindows->addAction(showGeoDockAction); QAction* showStationDockAction = stationDock->toggleViewAction(); showStationDockAction->setStatusTip(tr("Shows / hides the station view")); connect(showStationDockAction, SIGNAL(triggered(bool)), this, - SLOT(showStationDockWidget(bool))); + SLOT(showStationDockWidget(bool))); menuWindows->addAction(showStationDockAction); QAction* showMshDockAction = mshDock->toggleViewAction(); showMshDockAction->setStatusTip(tr("Shows / hides the mesh view")); connect(showMshDockAction, SIGNAL(triggered(bool)), this, - SLOT(showMshDockWidget(bool))); + SLOT(showMshDockWidget(bool))); menuWindows->addAction(showMshDockAction); QAction* showCondDockAction = conditionDock->toggleViewAction(); showCondDockAction->setStatusTip(tr("Shows / hides the FEM conditions view")); connect(showCondDockAction, SIGNAL(triggered(bool)), this, - SLOT(showMshDockWidget(bool))); + SLOT(showMshDockWidget(bool))); menuWindows->addAction(showMshDockAction); QAction* showVisDockAction = vtkVisDock->toggleViewAction(); showVisDockAction->setStatusTip(tr("Shows / hides the VTK Pipeline view")); connect(showVisDockAction, SIGNAL(triggered(bool)), this, - SLOT(showVisDockWidget(bool))); + SLOT(showVisDockWidget(bool))); menuWindows->addAction(showVisDockAction); // Presentation mode QMenu* presentationMenu = new QMenu(); presentationMenu->setTitle("Presentation on"); connect(presentationMenu, SIGNAL(aboutToShow()), this, - SLOT(createPresentationMenu())); + SLOT(createPresentationMenu())); menuWindows->insertMenu(showVisDockAction, presentationMenu); _fileFinder.addDirectory("."); _fileFinder.addDirectory(std::string(SOURCEPATH).append("/FileIO")); - #ifdef OGS_USE_VRPN - VtkTrackedCamera* cam = static_cast<VtkTrackedCamera*> - (visualizationWidget->renderer()->GetActiveCamera()); - _trackingSettingsWidget = new TrackingSettingsWidget(cam, visualizationWidget, Qt::Window); - #endif // OGS_USE_VRPN +#ifdef OGS_USE_VRPN + VtkTrackedCamera* cam = static_cast<VtkTrackedCamera*> + (visualizationWidget->renderer()->GetActiveCamera()); + _trackingSettingsWidget = new TrackingSettingsWidget(cam, visualizationWidget, Qt::Window); +#endif // OGS_USE_VRPN // connects for station model connect(stationTabWidget->treeView, - SIGNAL(propertiesDialogRequested(std::string)), this, - SLOT(showPropertiesDialog(std::string))); + SIGNAL(propertiesDialogRequested(std::string)), this, + SLOT(showPropertiesDialog(std::string))); _visPrefsDialog = new VisPrefsDialog(_vtkVisPipeline, visualizationWidget); @@ -407,9 +409,12 @@ void MainWindow::open() { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName( this, "Select data file to open", - settings.value("lastOpenedFileDirectory").toString(), - "Geosys files (*.gsp *.gli *.gml *.msh *.stn);;Project files (*.gsp);;GLI files (*.gli);;MSH files (*.msh);;STN files (*.stn);;All files (* *.*)"); - if (!fileName.isEmpty()) { + settings.value( + "lastOpenedFileDirectory"). + toString(), + "Geosys files (*.gsp *.gli *.gml *.msh *.stn);;Project files (*.gsp);;GLI files (*.gli);;MSH files (*.msh);;STN files (*.stn);;All files (* *.*)"); + if (!fileName.isEmpty()) + { QDir dir = QDir(fileName); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); loadFile(fileName); @@ -418,12 +423,14 @@ void MainWindow::open() void MainWindow::openDatabase() { - if (_db == NULL) { + if (_db == NULL) + { _db = new DatabaseConnection(_geoModels); _db->dbConnect(); } - if (_db != NULL && _db->isConnected()) { + if (_db != NULL && _db->isConnected()) + { _db->getListSelection(); updateDataViews(); } @@ -431,43 +438,52 @@ void MainWindow::openDatabase() void MainWindow::openDatabaseConnection() { - if (_db == NULL) _db = new DatabaseConnection(_geoModels); + if (_db == NULL) + _db = new DatabaseConnection(_geoModels); DBConnectionDialog* dbConn = new DBConnectionDialog(); connect( - dbConn, - SIGNAL(connectionRequested(QString, QString, QString, QString, QString)), - _db, - SLOT(setConnection(QString, QString, QString, QString, QString))); + dbConn, + SIGNAL(connectionRequested(QString, QString, QString, QString, QString)), + _db, + SLOT(setConnection(QString, QString, QString, QString, QString))); dbConn->show(); } void MainWindow::openRecentFile() { QAction* action = qobject_cast<QAction*> (sender()); - if (action) loadFile(action->data().toString()); + if (action) + loadFile(action->data().toString()); } void MainWindow::save() { QString dir_str = this->getLastUsedDir(); - QString fileName = QFileDialog::getSaveFileName(this, "Save data as", dir_str, - "GeoSys project (*.gsp);;GeoSys4 geometry files (*.gli);;GMSH geometry files (*.geo)"); + QString fileName = QFileDialog::getSaveFileName( + this, + "Save data as", + dir_str, + "GeoSys project (*.gsp);;GeoSys4 geometry files (*.gli);;GMSH geometry files (*.geo)"); - if (!fileName.isEmpty()) { + if (!fileName.isEmpty()) + { QFileInfo fi(fileName); - if (fi.suffix().toLower() == "gsp") { + if (fi.suffix().toLower() == "gsp") + { std::string schemaName(_fileFinder.getPath("OpenGeoSysProject.xsd")); XMLInterface xml(&_project, schemaName); xml.writeProjectFile(fileName); - /* - } else if (fi.suffix().toLower() == "gml") { - std::string schemaName(_fileFinder.getPath("OpenGeoSysGLI.xsd")); - XMLInterface xml(_geoModels, schemaName); - xml.writeGLIFile(fileName, gliName); - */ - } else if (fi.suffix().toLower() == "geo") { + /* + } else if (fi.suffix().toLower() == "gml") { + std::string schemaName(_fileFinder.getPath("OpenGeoSysGLI.xsd")); + XMLInterface xml(_geoModels, schemaName); + xml.writeGLIFile(fileName, gliName); + */ + } + else if (fi.suffix().toLower() == "geo") + { // it works like this (none of it is particularily fast or optimised or anything): // 1. merge all geometries that are currently loaded, all of these will be integrated into the mesh // 2. if "useStationsAsConstraints"-parameter is true, GMSH-Interface will also integrate all stations that are currently loaded @@ -477,63 +493,70 @@ void MainWindow::save() this->_project.getGEOObjects()->getGeometryNames(names); std::string merge_name("MergedGeometry"); _geoModels->mergeGeometries (names, merge_name); - gmsh_io.writeGMSHInputFile(merge_name, *(this->_project.getGEOObjects()), true); + gmsh_io.writeGMSHInputFile(merge_name, + *(this->_project.getGEOObjects()), true); this->_project.getGEOObjects()->removeSurfaceVec(merge_name); this->_project.getGEOObjects()->removePolylineVec(merge_name); this->_project.getGEOObjects()->removePointVec(merge_name); - } else if (fi.suffix().toLower() == "gli") { + } + else if (fi.suffix().toLower() == "gli") // writeGLIFileV4 (fileName.toStdString(), gliName.toStdString(), *_geoModels); writeAllDataToGLIFileV4(fileName.toStdString(), *_geoModels); - } } } void MainWindow::loadFile(const QString &fileName) { QFile file(fileName); - if (!file.open(QFile::ReadOnly)) { + if (!file.open(QFile::ReadOnly)) + { QMessageBox::warning(this, tr("Application"), tr( - "Cannot read file %1:\n%2.") .arg(fileName) .arg( - file.errorString())); + "Cannot read file %1:\n%2.").arg(fileName).arg( + file.errorString())); return; } QApplication::setOverrideCursor(Qt::WaitCursor); QFileInfo fi(fileName); std::string - base = - fi.absoluteDir().absoluteFilePath(fi.completeBaseName()).toStdString(); - if (fi.suffix().toLower() == "gli") { + base = + fi.absoluteDir().absoluteFilePath(fi.completeBaseName()).toStdString(); + if (fi.suffix().toLower() == "gli") + { #ifndef NDEBUG QTime myTimer0; myTimer0.start(); #endif - // FileIO::readGLIFileV4 (fileName.toStdString(), _geoModels); + // FileIO::readGLIFileV4 (fileName.toStdString(), _geoModels); readGLIFileV4(fileName.toStdString(), _geoModels); #ifndef NDEBUG std::cout << myTimer0.elapsed() << " ms" << std::endl; #endif // //#ifndef NDEBUG - // QTime myTimer; - // myTimer.start(); - // std::cout << "GEOLIB_Read_GeoLib ... " << std::flush; + // QTime myTimer; + // myTimer.start(); + // std::cout << "GEOLIB_Read_GeoLib ... " << std::flush; //#endif - // GEOLIB_Read_GeoLib(base); //fileName.toStdString()); + // GEOLIB_Read_GeoLib(base); //fileName.toStdString()); // cout << "Nr. Points: " << gli_points_vector.size() << endl; // cout << "Nr. Lines: " << polyline_vector.size() << endl; // cout << "Nr. Surfaces: " << surface_vector.size() << endl; //#ifndef NDEBUG - // std::cout << myTimer.elapsed() << " ms" << std::endl; + // std::cout << myTimer.elapsed() << " ms" << std::endl; //#endif - // GEOCalcPointMinMaxCoordinates(); - } else if (fi.suffix().toLower() == "gsp") { + // GEOCalcPointMinMaxCoordinates(); + } + else if (fi.suffix().toLower() == "gsp") + { std::string schemaName(_fileFinder.getPath("OpenGeoSysProject.xsd")); XMLInterface xml(&_project, schemaName); xml.readProjectFile(fileName); std::cout << "Adding missing meshes to GUI..." << std::endl; _meshModels->updateModel(); - } else if (fi.suffix().toLower() == "gml") { + } + else if (fi.suffix().toLower() == "gml") + { #ifndef NDEBUG QTime myTimer0; myTimer0.start(); @@ -546,13 +569,15 @@ void MainWindow::loadFile(const QString &fileName) #endif } // OpenGeoSys observation station files (incl. boreholes) - else if (fi.suffix().toLower() == "stn") { + else if (fi.suffix().toLower() == "stn") + { std::string schemaName(_fileFinder.getPath("OpenGeoSysSTN.xsd")); XMLInterface xml(&_project, schemaName); xml.readSTNFile(fileName); } // OpenGeoSys mesh files - else if (fi.suffix().toLower() == "msh") { + else if (fi.suffix().toLower() == "msh") + { std::string name = fileName.toStdString(); MeshLib::CFEMesh* msh = FileIO::OGSMeshIO::loadMeshFromFile(name); if (msh) @@ -562,23 +587,28 @@ void MainWindow::loadFile(const QString &fileName) } // GMS borehole files - else if (fi.suffix().toLower() == "txt") { - std::vector<GEOLIB::Point*> *boreholes = - new std::vector<GEOLIB::Point*>(); + else if (fi.suffix().toLower() == "txt") + { + std::vector<GEOLIB::Point*>* boreholes = + new std::vector<GEOLIB::Point*>(); std::string name = fi.baseName().toStdString(); if (GMSInterface::readBoreholesFromGMS(boreholes, fileName.toStdString())) _geoModels->addStationVec(boreholes, name, GEOLIB::getRandomColor()); - else OGSError::box("Error reading GMS file."); + else + OGSError::box("Error reading GMS file."); } // GMS mesh files - else if (fi.suffix().toLower() == "3dm") { + else if (fi.suffix().toLower() == "3dm") + { std::string name = fileName.toStdString(); MeshLib::CFEMesh* mesh = GMSInterface::readGMS3DMMesh(name); - if (mesh) _meshModels->addMesh(mesh, name); + if (mesh) + _meshModels->addMesh(mesh, name); } // goCAD files - else if (fi.suffix().toLower() == "ts") { + else if (fi.suffix().toLower() == "ts") + { #ifndef NDEBUG QTime myTimer; myTimer.start(); @@ -592,21 +622,23 @@ void MainWindow::loadFile(const QString &fileName) // NetCDF files // YW 07.2010 - else if (fi.suffix().toLower() == "nc") { + else if (fi.suffix().toLower() == "nc") + { #ifndef NDEBUG QTime myTimer; myTimer.start(); std::cout << "NetCDF Read ...\n" << std::flush; #endif std::string name = fileName.toStdString(); - std::vector<GEOLIB::Point*> *pnt_vec = - new std::vector<GEOLIB::Point*>(); + std::vector<GEOLIB::Point*>* pnt_vec = + new std::vector<GEOLIB::Point*>(); /* Data dimensions. */ size_t len_rlat, len_rlon; FileIO::NetCDFInterface::readNetCDFData(name, pnt_vec, _geoModels, - len_rlat, len_rlon); + len_rlat, len_rlon); MeshLib::CFEMesh* mesh = FileIO::NetCDFInterface::createMeshFromPoints(pnt_vec, - len_rlat, len_rlon); + len_rlat, + len_rlon); //GridAdapter* grid = new GridAdapter(mesh); _meshModels->addMesh(mesh, name); #ifndef NDEBUG @@ -619,18 +651,20 @@ void MainWindow::loadFile(const QString &fileName) } void MainWindow::loadPetrelFiles(const QStringList &sfc_file_names, - const QStringList &well_path_file_names) + const QStringList &well_path_file_names) { QStringList::const_iterator it = sfc_file_names.begin(); std::list<std::string> sfc_files; - while (it != sfc_file_names.end()) { + while (it != sfc_file_names.end()) + { sfc_files.push_back((*it).toStdString()); ++it; } it = well_path_file_names.begin(); std::list<std::string> well_path_files; - while (it != well_path_file_names.end()) { + while (it != well_path_file_names.end()) + { well_path_files.push_back((*it).toStdString()); ++it; } @@ -643,9 +677,9 @@ void MainWindow::loadPetrelFiles(const QStringList &sfc_file_names, void MainWindow::updateDataViews() { visualizationWidget->updateViewOnLoad(); - geoTabWidget-> treeView->updateView(); - stationTabWidget-> treeView->updateView(); - mshTabWidget-> treeView->updateView(); + geoTabWidget->treeView->updateView(); + stationTabWidget->treeView->updateView(); + mshTabWidget->treeView->updateView(); QApplication::restoreOverrideCursor(); } @@ -670,15 +704,15 @@ void MainWindow::about() { QString ogsVersion = QString(OGS_VERSION); QMessageBox::about(this, tr("About OpenGeoSys-5"), tr( - "Built on %1\nOGS Version: %2"). arg( - QDate::currentDate().toString()).arg(ogsVersion)); + "Built on %1\nOGS Version: %2").arg( + QDate::currentDate().toString()).arg(ogsVersion)); } QMenu* MainWindow::createImportFilesMenu() { QMenu* importFiles = new QMenu("&Import Files"); - QAction* feflowFiles = importFiles->addAction("&FEFLOW Files..."); - connect(feflowFiles, SIGNAL(triggered()), this, SLOT(importFeflow())); + QAction* feflowFiles = importFiles->addAction("&FEFLOW Files..."); + connect(feflowFiles, SIGNAL(triggered()), this, SLOT(importFeflow())); QAction* gmsFiles = importFiles->addAction("G&MS Files..."); connect(gmsFiles, SIGNAL(triggered()), this, SLOT(importGMS())); QAction* gocadFiles = importFiles->addAction("&Gocad Files..."); @@ -707,10 +741,11 @@ void MainWindow::importGMS() { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName(this, - "Select GMS file to import", settings.value( - "lastOpenedFileDirectory").toString(), - "GMS files (*.txt *.3dm)"); - if (!fileName.isEmpty()) { + "Select GMS file to import", settings.value( + "lastOpenedFileDirectory").toString(), + "GMS files (*.txt *.3dm)"); + if (!fileName.isEmpty()) + { loadFile(fileName); QDir dir = QDir(fileName); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); @@ -721,10 +756,12 @@ void MainWindow::importGoCad() { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName(this, - "Select data file to import", settings.value( - "lastOpenedFileDirectory").toString(), - "Gocad files (*.ts);;Gocad lines (*.tline)"); - if (!fileName.isEmpty()) { + "Select data file to import", + settings.value( + "lastOpenedFileDirectory").toString(), + "Gocad files (*.ts);;Gocad lines (*.tline)"); + if (!fileName.isEmpty()) + { loadFile(fileName); QDir dir = QDir(fileName); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); @@ -734,15 +771,18 @@ void MainWindow::importGoCad() void MainWindow::importRaster() { QSettings settings("UFZ", "OpenGeoSys-5"); - #ifdef libgeotiff_FOUND - QString geotiffExtension(" *.tif"); - #else - QString geotiffExtension(""); - #endif +#ifdef libgeotiff_FOUND + QString geotiffExtension(" *.tif"); +#else + QString geotiffExtension(""); +#endif QString fileName = QFileDialog::getOpenFileName(this, - "Select raster file to import", settings.value( - "lastOpenedFileDirectory").toString(), - QString("Raster files (*.asc *.bmp *.jpg *.png%1);;").arg(geotiffExtension)); + "Select raster file to import", + settings.value( + "lastOpenedFileDirectory").toString(), + QString( + "Raster files (*.asc *.bmp *.jpg *.png%1);;") + .arg(geotiffExtension)); if (!fileName.isEmpty()) { @@ -758,15 +798,18 @@ void MainWindow::importRaster() void MainWindow::importRasterAsPoly() { QSettings settings("UFZ", "OpenGeoSys-5"); - #ifdef libgeotiff_FOUND - QString geotiffExtension(" *.tif"); - #else - QString geotiffExtension(""); - #endif +#ifdef libgeotiff_FOUND + QString geotiffExtension(" *.tif"); +#else + QString geotiffExtension(""); +#endif QString fileName = QFileDialog::getOpenFileName(this, - "Select raster file to import", settings.value( - "lastOpenedFileDirectory").toString(), - QString("Raster files (*.asc *.bmp *.jpg *.png%1);;").arg(geotiffExtension)); + "Select raster file to import", + settings.value( + "lastOpenedFileDirectory").toString(), + QString( + "Raster files (*.asc *.bmp *.jpg *.png%1);;") + .arg(geotiffExtension)); if (!fileName.isEmpty()) { @@ -793,12 +836,14 @@ void MainWindow::importShape() { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName(this, - "Select shape file to import", settings.value( - "lastOpenedFileDirectory").toString(), - "ESRI Shape files (*.shp );;"); + "Select shape file to import", + settings.value( + "lastOpenedFileDirectory").toString(), + "ESRI Shape files (*.shp );;"); QFileInfo fi(fileName); - if (fi.suffix().toLower() == "shp" || fi.suffix().toLower() == "dbf") { + if (fi.suffix().toLower() == "shp" || fi.suffix().toLower() == "dbf") + { SHPImportDialog dlg((fileName.toUtf8()).constData(), _geoModels); dlg.exec(); @@ -811,11 +856,18 @@ void MainWindow::importShape() void MainWindow::importPetrel() { QSettings settings("UFZ", "OpenGeoSys-5"); - QStringList sfc_file_names = QFileDialog::getOpenFileNames(this, - "Select surface data file(s) to import", "", "Petrel files (*)"); - QStringList well_path_file_names = QFileDialog::getOpenFileNames(this, - "Select well path data file(s) to import", "", "Petrel files (*)"); - if (sfc_file_names.size() != 0 || well_path_file_names.size() != 0) { + QStringList sfc_file_names = QFileDialog::getOpenFileNames( + this, + "Select surface data file(s) to import", + "", + "Petrel files (*)"); + QStringList well_path_file_names = QFileDialog::getOpenFileNames( + this, + "Select well path data file(s) to import", + "", + "Petrel files (*)"); + if (sfc_file_names.size() != 0 || well_path_file_names.size() != 0) + { loadPetrelFiles(sfc_file_names, well_path_file_names); QDir dir = QDir(sfc_file_names.at(0)); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); @@ -827,10 +879,12 @@ void MainWindow::importNetcdf() { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName(this, - "Select NetCDF file to import", settings.value( - "lastOpenedFileDirectory").toString(), - "NetCDF files (*.nc);;"); - if (!fileName.isEmpty()) { + "Select NetCDF file to import", + settings.value( + "lastOpenedFileDirectory").toString(), + "NetCDF files (*.nc);;"); + if (!fileName.isEmpty()) + { loadFile(fileName); QDir dir = QDir(fileName); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); @@ -841,11 +895,14 @@ void MainWindow::importVtk() { QSettings settings("UFZ", "OpenGeoSys-5"); QStringList fileNames = QFileDialog::getOpenFileNames(this, - "Select VTK file(s) to import", settings.value( - "lastOpenedFileDirectory").toString(), - "VTK files (*.vtk *.vti *.vtr *.vts *.vtp *.vtu);;"); + "Select VTK file(s) to import", + settings.value( + "lastOpenedFileDirectory"). + toString(), + "VTK files (*.vtk *.vti *.vtr *.vts *.vtp *.vtu);;"); foreach(QString fileName, fileNames) { - if (!fileName.isEmpty()) { + if (!fileName.isEmpty()) + { _vtkVisPipeline->loadFromFile(fileName); QDir dir = QDir(fileName); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); @@ -855,36 +912,39 @@ void MainWindow::importVtk() void MainWindow::importFeflow() { - QSettings settings("UFZ", "OpenGeoSys-5"); - QString fileName = QFileDialog::getOpenFileName(this, - "Select FEFLOW file(s) to import", settings.value( - "lastOpenedFileDirectory").toString(), - "FEFLOW files (*.fem);;"); - if (!fileName.isEmpty()) { - FEFLOWInterface feflowIO(_geoModels); - MeshLib::CFEMesh *msh = feflowIO.readFEFLOWModelFile(fileName.toStdString()); - if (msh) { - std::string str = fileName.toStdString(); - _meshModels->addMesh(msh, str); - QDir dir = QDir(fileName); - settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); - //_geoModels->modified("Feflow"); - updateDataViews(); - } else { - OGSError::box("Failed to load a FEFLOW file."); - } - } - emit fileUsed(fileName); + QSettings settings("UFZ", "OpenGeoSys-5"); + QString fileName = QFileDialog::getOpenFileName(this, + "Select FEFLOW file(s) to import", + settings.value( + "lastOpenedFileDirectory").toString(), + "FEFLOW files (*.fem);;"); + if (!fileName.isEmpty()) + { + FEFLOWInterface feflowIO(_geoModels); + MeshLib::CFEMesh* msh = feflowIO.readFEFLOWModelFile(fileName.toStdString()); + if (msh) + { + std::string str = fileName.toStdString(); + _meshModels->addMesh(msh, str); + QDir dir = QDir(fileName); + settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); + //_geoModels->modified("Feflow"); + updateDataViews(); + } + else + OGSError::box("Failed to load a FEFLOW file."); + } + emit fileUsed(fileName); } void MainWindow::showPropertiesDialog(std::string const& name) { ListPropertiesDialog dlg(name, _geoModels); connect( - &dlg, - SIGNAL(propertyBoundariesChanged(std::string, std::vector<PropertyBounds>)), - _geoModels, - SLOT(filterStationVec(std::string, std::vector<PropertyBounds>))); + &dlg, + SIGNAL(propertyBoundariesChanged(std::string, std::vector<PropertyBounds>)), + _geoModels, + SLOT(filterStationVec(std::string, std::vector<PropertyBounds>))); dlg.exec(); } @@ -898,8 +958,10 @@ void MainWindow::loadFEMConditionsFromFile(std::string geoName) { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName( this, "Select data file to open", - settings.value("lastOpenedFileDirectory").toString(), - "Geosys FEM condition files (*.cnd *.bc *.ic *.st);;All files (* *.*)"); + settings.value( + "lastOpenedFileDirectory"). + toString(), + "Geosys FEM condition files (*.cnd *.bc *.ic *.st);;All files (* *.*)"); if (!fileName.isEmpty()) { QFileInfo fi(fileName); @@ -908,7 +970,8 @@ void MainWindow::loadFEMConditionsFromFile(std::string geoName) std::vector<FEMCondition*> conditions; - if (fi.suffix().toLower() == "cnd") { + if (fi.suffix().toLower() == "cnd") + { std::string schemaName(_fileFinder.getPath("OpenGeoSysCond.xsd")); XMLInterface xml(&_project, schemaName); xml.readFEMCondFile(conditions, fileName, QString::fromStdString(geoName)); @@ -917,7 +980,8 @@ void MainWindow::loadFEMConditionsFromFile(std::string geoName) { QString name = fi.path() + "/"; BCRead((name.append(fi.baseName())).toStdString(), *_geoModels, geoName); - for (std::list<CBoundaryCondition*>::iterator it = bc_list.begin(); it != bc_list.end(); ++it) + for (std::list<CBoundaryCondition*>::iterator it = bc_list.begin(); + it != bc_list.end(); ++it) { BoundaryCondition* bc = new BoundaryCondition(*(*it), geoName); conditions.push_back(bc); @@ -927,7 +991,8 @@ void MainWindow::loadFEMConditionsFromFile(std::string geoName) { QString name = fi.path() + "/"; ICRead((name.append(fi.baseName())).toStdString(), *_geoModels, geoName); - for (std::vector<CInitialCondition*>::iterator it = ic_vector.begin(); it != ic_vector.end(); ++it) + for (std::vector<CInitialCondition*>::iterator it = ic_vector.begin(); + it != ic_vector.end(); ++it) { InitialCondition* ic = new InitialCondition(*(*it), geoName); conditions.push_back(ic); @@ -937,7 +1002,8 @@ void MainWindow::loadFEMConditionsFromFile(std::string geoName) { QString name = fi.path() + "/"; STRead((name.append(fi.baseName())).toStdString(), *_geoModels, geoName); - for (std::vector<CSourceTerm*>::iterator it = st_vector.begin(); it != st_vector.end(); ++it) + for (std::vector<CSourceTerm*>::iterator it = st_vector.begin(); + it != st_vector.end(); ++it) { SourceTerm* st = new SourceTerm(*(*it), geoName); conditions.push_back(st); @@ -948,11 +1014,15 @@ void MainWindow::loadFEMConditionsFromFile(std::string geoName) { this->_conditionModel->addConditions(conditions); - for (std::list<CBoundaryCondition*>::iterator it=bc_list.begin(); it!=bc_list.end(); ++it) delete *it; + for (std::list<CBoundaryCondition*>::iterator it = bc_list.begin(); + it != bc_list.end(); ++it) + delete *it; bc_list.clear(); - for (size_t i=0; i<ic_vector.size(); i++) delete ic_vector[i]; + for (size_t i = 0; i < ic_vector.size(); i++) + delete ic_vector[i]; ic_vector.clear(); - for (size_t i=0; i<st_vector.size(); i++) delete st_vector[i]; + for (size_t i = 0; i < st_vector.size(); i++) + delete st_vector[i]; st_vector.clear(); } } @@ -973,26 +1043,29 @@ void MainWindow::writeStationListToFile(QString listName, QString fileName) } void MainWindow::exportBoreholesToGMS(std::string listName, - std::string fileName) + std::string fileName) { - const std::vector<GEOLIB::Point*> *stations(_geoModels->getStationVec( - listName)); + const std::vector<GEOLIB::Point*>* stations(_geoModels->getStationVec( + listName)); GMSInterface::writeBoreholesToGMS(stations, fileName); } void MainWindow::callGMSH(std::vector<std::string> const & selectedGeometries, - size_t param1, double param2, double param3, double param4, - bool delete_geo_file) + size_t param1, double param2, double param3, double param4, + bool delete_geo_file) { - if (!selectedGeometries.empty()) { + if (!selectedGeometries.empty()) + { std::cout << "Start meshing..." << std::endl; QString fileName(""); QString dir_str = this->getLastUsedDir(); if (!delete_geo_file) - fileName = QFileDialog::getSaveFileName(this, "Save GMSH-file as", - dir_str, "GMSH geometry files (*.geo)"); + fileName = QFileDialog::getSaveFileName(this, + "Save GMSH-file as", + dir_str, + "GMSH geometry files (*.geo)"); else fileName = "tmp_gmsh.geo"; @@ -1000,15 +1073,18 @@ void MainWindow::callGMSH(std::vector<std::string> const & selectedGeometries, { GMSHInterface gmsh_io(fileName.toStdString()); - if (param4 == -1) { // adaptive meshing selected + if (param4 == -1) // adaptive meshing selected gmsh_io.writeAllDataToGMSHInputFile(*_geoModels, - selectedGeometries, param1, param2, param3); - } else { // homogeneous meshing selected + selectedGeometries, + param1, + param2, + param3); + else // homogeneous meshing selected gmsh_io.writeAllDataToGMSHInputFile(*_geoModels, - selectedGeometries, param4); - } + selectedGeometries, param4); - if (system(NULL) != 0) { // command processor available + if (system(NULL) != 0) // command processor available + { std::string gmsh_command("gmsh -2 "); std::string fname (fileName.toStdString()); gmsh_command += fname; @@ -1017,16 +1093,19 @@ void MainWindow::callGMSH(std::vector<std::string> const & selectedGeometries, fname = fname.substr (0, pos); gmsh_command += " -o " + fname + ".msh"; system(gmsh_command.c_str()); - this->loadFile(fileName.left(fileName.length()-3).append("msh")); - } else { - OGSError::box("Error executing command gmsh - no command processor available", "Error"); + this->loadFile(fileName.left(fileName.length() - 3).append("msh")); } + else + OGSError::box( + "Error executing command gmsh - no command processor available", + "Error"); - if (delete_geo_file) { // delete file + if (delete_geo_file) // delete file + { std::string remove_command ("rm "); - #ifdef _WIN32 +#ifdef _WIN32 remove_command = "del "; - #endif +#endif remove_command += fileName.toStdString(); std::cout << "remove command: " << remove_command << std::endl; system(remove_command.c_str()); @@ -1044,23 +1123,27 @@ void MainWindow::showDiagramPrefsDialog(QModelIndex &index) { QString listName; GEOLIB::Station* stn = _geoModels->getStationModel()->stationFromIndex( - index, listName); + index, listName); - if (stn->type() == GEOLIB::Station::STATION) { + if (stn->type() == GEOLIB::Station::STATION) + { DiagramPrefsDialog* prefs = new DiagramPrefsDialog(stn, listName, _db); prefs->setAttribute(Qt::WA_DeleteOnClose); prefs->show(); } - if (stn->type() == GEOLIB::Station::BOREHOLE) OGSError::box( - "No time series data available for borehole."); + if (stn->type() == GEOLIB::Station::BOREHOLE) + OGSError::box( + "No time series data available for borehole."); } void MainWindow::showDiagramPrefsDialog() { QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName( this, "Select data file to open", - settings.value("lastOpenedFileDirectory").toString(), - "Text files (*.txt);;All files (* *.*)"); + settings.value( + "lastOpenedFileDirectory"). + toString(), + "Text files (*.txt);;All files (* *.*)"); if (!fileName.isEmpty()) { QDir dir = QDir(fileName); @@ -1074,8 +1157,14 @@ void MainWindow::showDiagramPrefsDialog() void MainWindow::showLineEditDialog(const std::string &geoName) { LineEditDialog lineEdit(*(_geoModels->getPolylineVecObj(geoName))); - connect(&lineEdit, SIGNAL(connectPolylines(const std::string&, std::vector<size_t>, double, std::string, bool, bool)), - _geoModels, SLOT(connectPolylineSegments(const std::string&, std::vector<size_t>, double, std::string, bool, bool))); + connect(&lineEdit, + SIGNAL(connectPolylines(const std::string &, std::vector<size_t>, double, + std::string, bool, + bool)), + _geoModels, + SLOT(connectPolylineSegments(const std::string &, std::vector<size_t>, double, + std::string, + bool, bool))); lineEdit.exec(); } @@ -1083,16 +1172,20 @@ void MainWindow::showGMSHPrefsDialog() { GMSHPrefsDialog dlg(_geoModels); connect( - &dlg, SIGNAL(requestMeshing(std::vector<std::string> const &, size_t, double, double, double, bool)), - this, SLOT(callGMSH(std::vector<std::string> const &, size_t, double, double, double, bool))); + &dlg, + SIGNAL(requestMeshing(std::vector<std::string> const &, size_t, double, double, + double, bool)), + this, + SLOT(callGMSH(std::vector<std::string> const &, size_t, double, double, double, + bool))); dlg.exec(); } void MainWindow::showMshQualitySelectionDialog(VtkMeshSource* mshSource) { MshQualitySelectionDialog dlg(mshSource); - connect(&dlg, SIGNAL(measureSelected(VtkMeshSource*, MshQualityType::type)), - _vtkVisPipeline, SLOT(checkMeshQuality(VtkMeshSource*, MshQualityType::type))); + connect(&dlg, SIGNAL(measureSelected(VtkMeshSource *, MshQualityType::type)), + _vtkVisPipeline, SLOT(checkMeshQuality(VtkMeshSource *, MshQualityType::type))); dlg.exec(); } @@ -1106,11 +1199,11 @@ void MainWindow::FEMTestStart() // *** begin test TetGen read mesh const std::string path ("/home/fischeth/Desktop/data/Ketzin/PSglobal/Tom/MSH/"); std::string mesh_name ("ClosedSurface"); - std::string fname_nodes(path+mesh_name+".1.node"); - std::string fname_elements(path+mesh_name+".1.ele"); + std::string fname_nodes(path + mesh_name + ".1.node"); + std::string fname_elements(path + mesh_name + ".1.ele"); FileIO::TetGenInterface tetgen; - MeshLib::CFEMesh *mesh (tetgen.readTetGenMesh (fname_nodes, fname_elements)); + MeshLib::CFEMesh* mesh (tetgen.readTetGenMesh (fname_nodes, fname_elements)); if (mesh) _meshModels->addMesh(mesh, mesh_name); @@ -1457,7 +1550,7 @@ void MainWindow::showTrackingSettingsDialog() _trackingSettingsWidget->show(); #else // OGS_USE_VRPN QMessageBox::warning(this, "Functionality not implemented", - "Sorry but this progam was not compiled with VRPN support."); + "Sorry but this progam was not compiled with VRPN support."); #endif // OGS_USE_VRPN } @@ -1477,10 +1570,13 @@ void MainWindow::on_actionExportVTK_triggered(bool checked /*= false*/) QSettings settings("UFZ", "OpenGeoSys-5"); int count = 0; QString filename = QFileDialog::getSaveFileName(this, - "Export object to vtk-files", settings.value( - "lastExportedFileDirectory").toString(), - "VTK files (*.vtp *.vtu)"); - if (!filename.isEmpty()) { + "Export object to vtk-files", + settings.value( + "lastExportedFileDirectory"). + toString(), + "VTK files (*.vtp *.vtu)"); + if (!filename.isEmpty()) + { QDir dir = QDir(filename); settings.setValue("lastExportedFileDirectory", dir.absolutePath()); @@ -1488,10 +1584,11 @@ void MainWindow::on_actionExportVTK_triggered(bool checked /*= false*/) basename.append("/" + QFileInfo(filename).baseName().toStdString()); TreeModelIterator it(_vtkVisPipeline); ++it; - while (*it) { + while (*it) + { count++; static_cast<VtkVisPipelineItem*> (*it)->writeToFile(basename - + number2str(count)); + + number2str(count)); ++it; } } @@ -1502,17 +1599,19 @@ void MainWindow::on_actionExportVRML2_triggered(bool checked /*= false*/) Q_UNUSED(checked) QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getSaveFileName(this, - "Save scene to VRML file", settings.value( - "lastExportedFileDirectory").toString(), - "VRML files (*.wrl);;"); - if (!fileName.isEmpty()) { + "Save scene to VRML file", settings.value( + "lastExportedFileDirectory"). + toString(), + "VRML files (*.wrl);;"); + if (!fileName.isEmpty()) + { QDir dir = QDir(fileName); settings.setValue("lastExportedFileDirectory", dir.absolutePath()); vtkVRMLExporter* exporter = vtkVRMLExporter::New(); exporter->SetFileName(fileName.toStdString().c_str()); exporter->SetRenderWindow( - visualizationWidget->vtkWidget->GetRenderWindow()); + visualizationWidget->vtkWidget->GetRenderWindow()); exporter->Write(); exporter->Delete(); } @@ -1523,16 +1622,20 @@ void MainWindow::on_actionExportObj_triggered(bool checked /*= false*/) Q_UNUSED(checked) QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getSaveFileName(this, - "Save scene to Wavefront OBJ files", settings.value( - "lastExportedFileDirectory").toString(), ";;"); - if (!fileName.isEmpty()) { + "Save scene to Wavefront OBJ files", + settings.value( + "lastExportedFileDirectory"). + toString(), + ";;"); + if (!fileName.isEmpty()) + { QDir dir = QDir(fileName); settings.setValue("lastExportedFileDirectory", dir.absolutePath()); vtkOBJExporter* exporter = vtkOBJExporter::New(); exporter->SetFilePrefix(fileName.toStdString().c_str()); exporter->SetRenderWindow( - visualizationWidget->vtkWidget->GetRenderWindow()); + visualizationWidget->vtkWidget->GetRenderWindow()); exporter->Write(); exporter->Delete(); } @@ -1544,8 +1647,8 @@ void MainWindow::on_actionExportOpenSG_triggered(bool checked /*= false*/) #ifdef OGS_USE_OPENSG QSettings settings("UFZ", "OpenGeoSys-5"); QString filename = QFileDialog::getSaveFileName( - this, "Export scene to OpenSG binary file", settings.value( - "lastExportedFileDirectory").toString(), "OpenSG files (*.osb);;"); + this, "Export scene to OpenSG binary file", settings.value( + "lastExportedFileDirectory").toString(), "OpenSG files (*.osb);;"); if (!filename.isEmpty()) { QDir dir = QDir(filename); @@ -1569,9 +1672,9 @@ void MainWindow::on_actionExportOpenSG_triggered(bool checked /*= false*/) OSG::SceneFileHandler::the().write(root, filename.toStdString().c_str()); } -#else +#else // ifdef OGS_USE_OPENSG QMessageBox::warning(this, "Functionality not implemented", - "Sorry but this progam was not compiled with OpenSG support."); + "Sorry but this progam was not compiled with OpenSG support."); #endif } @@ -1579,27 +1682,31 @@ void MainWindow::createPresentationMenu() { QMenu* menu = static_cast<QMenu*> (QObject::sender()); menu->clear(); - if (!_vtkWidget->parent()) { + if (!_vtkWidget->parent()) + { QAction* action = new QAction("Quit presentation mode", menu); connect(action, SIGNAL(triggered()), this, SLOT(quitPresentationMode())); action->setShortcutContext(Qt::WidgetShortcut); action->setShortcut(QKeySequence(Qt::Key_Escape)); menu->addAction(action); - } else { + } + else + { int count = 0; const int currentScreen = QApplication::desktop()->screenNumber( - visualizationWidget); + visualizationWidget); foreach (QRect screenGeo, _screenGeometries) - { - Q_UNUSED(screenGeo); - QAction* action = new QAction( - QString("On screen %1").arg(count), menu); - connect(action, SIGNAL(triggered()), this, - SLOT(startPresentationMode())); - if (count == currentScreen) action->setEnabled(false); - menu->addAction(action); - ++count; - } + { + Q_UNUSED(screenGeo); + QAction* action = new QAction( + QString("On screen %1").arg(count), menu); + connect(action, SIGNAL(triggered()), this, + SLOT(startPresentationMode())); + if (count == currentScreen) + action->setEnabled(false); + menu->addAction(action); + ++count; + } } } @@ -1616,7 +1723,7 @@ void MainWindow::startPresentationMode() // Real fullscreen hides the menu _vtkWidget->setParent(NULL, Qt::Window); _vtkWidget->move(QPoint(_screenGeometries[screen].x(), - _screenGeometries[screen].y())); + _screenGeometries[screen].y())); //_vtkWidget->showFullScreen(); _vtkWidget->showMaximized(); @@ -1659,26 +1766,30 @@ QString MainWindow::getLastUsedDir() return QDir::homePath(); } -void MainWindow::loadDIRECTSourceTerms(const std::vector<GEOLIB::Point*> *points) +void MainWindow::loadDIRECTSourceTerms(const std::vector<GEOLIB::Point*>* points) { std::string geo_name("mshNodes"); QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName( this, "Select data file to open", - settings.value("lastOpenedFileDirectory").toString(), - "Geosys FEM condition files (*.st);;All files (* *.*)"); + settings.value( + "lastOpenedFileDirectory"). + toString(), + "Geosys FEM condition files (*.st);;All files (* *.*)"); QFileInfo fi(fileName); QString name = fi.path() + "/"; if (!fileName.isEmpty()) { // create new geometry points vector by copying mesh nodes vector - std::vector<GEOLIB::Point*> *new_points = new std::vector<GEOLIB::Point*>; - std::map<std::string, size_t> *name_pnt_id_map = new std::map<std::string, size_t>; + std::vector<GEOLIB::Point*>* new_points = new std::vector<GEOLIB::Point*>; + std::map<std::string, size_t>* name_pnt_id_map = new std::map<std::string, size_t>; - for (size_t i=0; i<points->size(); i++) + for (size_t i = 0; i < points->size(); i++) { - GEOLIB::Point* pnt = new GEOLIB::Point((*(*points)[i])[0],(*(*points)[i])[1],(*(*points)[i])[2]); + GEOLIB::Point* pnt = new GEOLIB::Point((*(*points)[i])[0], + (*(*points)[i])[1], + (*(*points)[i])[2]); new_points->push_back(pnt); std::stringstream out; out << i; @@ -1687,16 +1798,18 @@ void MainWindow::loadDIRECTSourceTerms(const std::vector<GEOLIB::Point*> *points this->_geoModels->addPointVec(new_points, geo_name, name_pnt_id_map); STRead((name.append(fi.baseName())).toStdString(), *_geoModels, geo_name); - std::vector<FEMCondition*> conditions = SourceTerm::createDirectSourceTerms(st_vector, geo_name); + std::vector<FEMCondition*> conditions = SourceTerm::createDirectSourceTerms( + st_vector, + geo_name); // add boundary conditions to model if (!conditions.empty()) { this->_conditionModel->addConditions(conditions); - for (size_t i=0; i<st_vector.size(); i++) delete st_vector[i]; + for (size_t i = 0; i < st_vector.size(); i++) + delete st_vector[i]; st_vector.clear(); } } } - diff --git a/Gui/mainwindow.h b/Gui/mainwindow.h index bc5573a50ba6e8932398cbe3c2ecf0a77110fce3..04cba75d6f0094791f789795f1b9fbb862543d56 100644 --- a/Gui/mainwindow.h +++ b/Gui/mainwindow.h @@ -1,15 +1,15 @@ /** -* \file mainwindow.h -* 4/11/2009 LB Initial implementation -* -*/ + * \file mainwindow.h + * 4/11/2009 LB Initial implementation + * + */ #ifndef MAINWINDOW_H #define MAINWINDOW_H -#include "ui_mainwindow.h" #include "FileFinder.h" #include "ProjectData.h" +#include "ui_mainwindow.h" class GEOModels; class MshModel; @@ -21,20 +21,19 @@ class DatabaseConnection; class VisPrefsDialog; #ifdef OGS_USE_VRPN - class TrackingSettingsWidget; +class TrackingSettingsWidget; #endif // OGS_USE_VRPN - /** * Main program window for the graphical user interface of OpenGeoSys. */ class MainWindow : public QMainWindow, public Ui_MainWindowClass { - Q_OBJECT + Q_OBJECT public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); + MainWindow(QWidget* parent = 0); + ~MainWindow(); void ShowWindow(); void HideWindow(); @@ -50,16 +49,21 @@ protected slots: void showVisDockWidget( bool show ); /// Function calls for opening files. - void open(); + void open(); /// Function calls for saving files. void save(); /// Function calls for generating GMSH files from the GUI - void callGMSH(std::vector<std::string> const & selectedGeometries, size_t param1, double param2, double param3, double param4, bool delete_geo_file); + void callGMSH(std::vector<std::string> const & selectedGeometries, + size_t param1, + double param2, + double param3, + double param4, + bool delete_geo_file); /// Function calls for GMS export. void exportBoreholesToGMS(std::string listName, std::string fileName); /// Testing functionality for connection to FEM lib void FEMTestStart(); - void importGMS(); + void importGMS(); void importGoCad(); void importRaster(); void importRasterAsPoly(); @@ -67,9 +71,9 @@ protected slots: void importShape(); #endif void importPetrel(); - void importNetcdf(); //YW 07.2010 + void importNetcdf(); //YW 07.2010 void importVtk(); - void importFeflow(); + void importFeflow(); void loadFEMConditionsFromFile(std::string); void openDatabase(); void openDatabaseConnection(); @@ -99,19 +103,19 @@ protected slots: void startPresentationMode(); void quitPresentationMode(); - void loadDIRECTSourceTerms(const std::vector<GEOLIB::Point*> *points); //TODO put this in a better place - + void loadDIRECTSourceTerms(const std::vector<GEOLIB::Point*>* points); //TODO put this in a better place private: QMenu* createImportFilesMenu(); - void loadFile(const QString &fileName); - void loadPetrelFiles(const QStringList &sfc_file_names, const QStringList &well_path_file_names); + void loadFile(const QString &fileName); + void loadPetrelFiles(const QStringList &sfc_file_names, + const QStringList &well_path_file_names); void readSettings(); void writeSettings(); QString getLastUsedDir(); - QString curFile; + QString curFile; DatabaseConnection* _db; FileFinder _fileFinder; @@ -124,12 +128,11 @@ private: QList<QRect> _screenGeometries; QWidget* _vtkWidget; QByteArray _windowState; - #ifdef OGS_USE_VRPN - TrackingSettingsWidget* _trackingSettingsWidget; - #endif // OGS_USE_VRPN +#ifdef OGS_USE_VRPN + TrackingSettingsWidget* _trackingSettingsWidget; +#endif // OGS_USE_VRPN VisPrefsDialog* _visPrefsDialog; - signals: void fileUsed( QString filename ); }; diff --git a/Gui/pymainwindow.cpp b/Gui/pymainwindow.cpp index cca6fc289764e212c9a5a1a3d0f77624b5c2dbb0..b761cb2134e5bb42af366970959f164a239e22e4 100644 --- a/Gui/pymainwindow.cpp +++ b/Gui/pymainwindow.cpp @@ -1,7 +1,7 @@ /** * \file pymainwindow.cpp * 2/6/2010 LB Initial implementation - * + * * Implementation of pymainwindow */ @@ -16,21 +16,21 @@ namespace python = boost::python; BOOST_PYTHON_MODULE(ogsgui) { class_<MainWindow, boost::noncopyable>("ogsgui", init<>()) - .def("ShowWindow", &MainWindow::ShowWindow) - .def("HideWindow", &MainWindow::HideWindow) + .def("ShowWindow", &MainWindow::ShowWindow) + .def("HideWindow", &MainWindow::HideWindow) ; class_<StartQt4, boost::noncopyable>("StartQt4", init<>()); } /** -TODO -vtkWidget entfernen, sonst Konflikt zwischen VRED Renderfenster und vtkWidget + TODO + vtkWidget entfernen, sonst Konflikt zwischen VRED Renderfenster und vtkWidget -Weiteres Problem: vred Prozess läuft nach Beenden von VRED weiter + Weiteres Problem: vred Prozess läuft nach Beenden von VRED weiter -import imp -ogsmodule = imp.load_dynamic('ogsgui', 'E:/bilke/geosys/branch/sources/Build/lib/Release/ogs-gui-vred.dll') -qt = ogsmodule.StartQt4() -ogs = ogsmodule.ogsgui() -ogs.ShowWindow() + import imp + ogsmodule = imp.load_dynamic('ogsgui', 'E:/bilke/geosys/branch/sources/Build/lib/Release/ogs-gui-vred.dll') + qt = ogsmodule.StartQt4() + ogs = ogsmodule.ogsgui() + ogs.ShowWindow() */ \ No newline at end of file diff --git a/OpenSG/vtkOsgConverter.cpp b/OpenSG/vtkOsgConverter.cpp index f1ecf9867178018ca9162cb0ae12af52f75e4510..c35c76e2217589210a2c83bc4f70efb90f36d00a 100644 --- a/OpenSG/vtkOsgConverter.cpp +++ b/OpenSG/vtkOsgConverter.cpp @@ -1,7 +1,7 @@ /** * \file vtkOsgConverter.cpp * 27/07/2011 LB Initial implementation - * + * * Implementation of vtkOsgConverter class */ @@ -9,851 +9,932 @@ #include "vtkOsgConverter.h" #include <vtkActor.h> -#include <vtkTexture.h> +#include <vtkCellArray.h> +#include <vtkCellData.h> +#include <vtkCompositeDataGeometryFilter.h> #include <vtkDataArray.h> -#include <vtkUnsignedCharArray.h> +#include <vtkDataSet.h> +#include <vtkDataSetMapper.h> +#include <vtkGeometryFilter.h> +#include <vtkImageData.h> +#include <vtkMapper.h> +#include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> -#include <vtkPointData.h> -#include <vtkCellData.h> -#include <vtkCellArray.h> -#include <vtkImageData.h> -#include <vtkMapper.h> -#include <vtkDataSet.h> -#include <vtkDataSetMapper.h> #include <vtkSmartPointer.h> -#include <vtkCompositeDataGeometryFilter.h> -#include <vtkGeometryFilter.h> +#include <vtkTexture.h> +#include <vtkUnsignedCharArray.h> -#include <OpenSG/OSGPolygonChunk.h> -#include <OpenSG/OSGPointChunk.h> +#include <OpenSG/OSGGeoFunctions.h> +#include <OpenSG/OSGGroup.h> +#include <OpenSG/OSGImage.h> #include <OpenSG/OSGLineChunk.h> +#include <OpenSG/OSGMaterialChunk.h> #include <OpenSG/OSGMatrix.h> +#include <OpenSG/OSGPointChunk.h> +#include <OpenSG/OSGPolygonChunk.h> #include <OpenSG/OSGSimpleGeometry.h> -#include <OpenSG/OSGMaterialChunk.h> -#include <OpenSG/OSGGeoFunctions.h> -#include <OpenSG/OSGGroup.h> #include <OpenSG/OSGTwoSidedLightingChunk.h> -#include <OpenSG/OSGImage.h> OSG_USING_NAMESPACE vtkOsgConverter::vtkOsgConverter(vtkActor* actor) : - _actor(actor), - _verbose(false), - _osgRoot(NullFC), - _osgTransform(NullFC) + _actor(actor), + _verbose(false), + _osgRoot(NullFC), + _osgTransform(NullFC) { - TransformPtr tptr; - _osgRoot = makeCoredNode<osg::Transform>(&tptr); - _osgTransform = tptr; - _mapper = _actor->GetMapper(); + TransformPtr tptr; + _osgRoot = makeCoredNode<osg::Transform>(&tptr); + _osgTransform = tptr; + _mapper = _actor->GetMapper(); } vtkOsgConverter::~vtkOsgConverter(void) { - _osgRoot = NullFC; + _osgRoot = NullFC; } bool vtkOsgConverter::WriteAnActor() { - - - // see if the actor has a mapper. it could be an assembly - if (_actor->GetMapper() == NULL) - return false; - // dont export when not visible - if (_actor->GetVisibility() == 0) - return false; - - vtkDataObject* inputDO = _actor->GetMapper()->GetInputDataObject(0, 0); - if (inputDO == NULL) - return false; - - // Get PolyData. Convert if necessary becasue we only want polydata - vtkSmartPointer<vtkPolyData> pd; - if(inputDO->IsA("vtkCompositeDataSet")) - { - vtkCompositeDataGeometryFilter* gf = vtkCompositeDataGeometryFilter::New(); - gf->SetInput(inputDO); - gf->Update(); - pd = gf->GetOutput(); - gf->Delete(); - } - else if(inputDO->GetDataObjectType() != VTK_POLY_DATA) - { - vtkGeometryFilter *gf = vtkGeometryFilter::New(); - gf->SetInput(inputDO); - gf->Update(); - pd = gf->GetOutput(); - gf->Delete(); - } - else - pd = static_cast<vtkPolyData *>(inputDO); - - // Copy mapper to a new one - vtkPolyDataMapper* pm = vtkPolyDataMapper::New(); - pm->SetInput(pd); - pm->SetScalarRange(_actor->GetMapper()->GetScalarRange()); - pm->SetScalarVisibility(_actor->GetMapper()->GetScalarVisibility()); - pm->SetLookupTable(_actor->GetMapper()->GetLookupTable()); - pm->SetScalarMode(_actor->GetMapper()->GetScalarMode()); - - if(pm->GetScalarMode() == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA || - pm->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA ) - { - if(_actor->GetMapper()->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID ) - pm->ColorByArrayComponent(_actor->GetMapper()->GetArrayId(), - _actor->GetMapper()->GetArrayComponent()); - else - pm->ColorByArrayComponent(_actor->GetMapper()->GetArrayName(), - _actor->GetMapper()->GetArrayComponent()); - } - - _mapper = pm; - // vtkPoints* points = pd->GetPoints(); - vtkPointData* pntData = pd->GetPointData(); - bool hasTexCoords = false; - vtkUnsignedCharArray* vtkColors = pm->MapScalars(1.0); - - // ARRAY SIZES - vtkIdType m_iNumPoints = pd->GetNumberOfPoints(); - if (m_iNumPoints == 0) - return false; - vtkIdType m_iNumGLPoints = pd->GetVerts()->GetNumberOfCells(); - vtkIdType m_iNumGLLineStrips = pd->GetLines()->GetNumberOfCells(); - vtkIdType m_iNumGLPolygons = pd->GetPolys()->GetNumberOfCells(); - vtkIdType m_iNumGLTriStrips = pd->GetStrips()->GetNumberOfCells(); - vtkIdType m_iNumGLPrimitives = m_iNumGLPoints + m_iNumGLLineStrips + m_iNumGLPolygons + m_iNumGLTriStrips; - bool lit = !(m_iNumGLPolygons == 0 && m_iNumGLTriStrips == 0); - - if (_verbose) - { - std::cout << "Array sizes:" << std::endl; - std::cout << " number of vertices: " << m_iNumPoints << std::endl; - std::cout << " number of GL_POINTS: " << m_iNumGLPoints << std::endl; - std::cout << " number of GL_LINE_STRIPS: " << m_iNumGLLineStrips << std::endl; - std::cout << " number of GL_POLYGON's: " << m_iNumGLPolygons << std::endl; - std::cout << " number of GL_TRIANGLE_STRIPS: " << m_iNumGLTriStrips << std::endl; - std::cout << " number of primitives: " << m_iNumGLPrimitives << std::endl; - } - - _mapper->Update(); - - // NORMALS - vtkDataArray *vtkNormals = NULL; - int m_iNormalType = NOT_GIVEN; - if (_actor->GetProperty()->GetInterpolation() == VTK_FLAT) - { - vtkNormals = pd->GetCellData()->GetNormals(); - if (vtkNormals != NULL) m_iNormalType = PER_CELL; - } - else - { - vtkNormals = pntData->GetNormals(); - if (vtkNormals != NULL) m_iNormalType = PER_VERTEX; - } - if (_verbose) - { - std::cout << "Normals:" << std::endl; - if (m_iNormalType != NOT_GIVEN) - { - std::cout << " number of normals: " << vtkNormals->GetNumberOfTuples() << std::endl; - std::cout << " normals are given: "; - std::cout << ((m_iNormalType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl; - } - else - std::cout << " no normals are given" << std::endl; - } - - // COLORS - int m_iColorType = NOT_GIVEN; - if(pm->GetScalarVisibility()) - { - int iScalarMode = pm->GetScalarMode(); - if(vtkColors == NULL) - { - m_iColorType = NOT_GIVEN; - std::cout << "WARNING: MapScalars(1.0) did not return array!" << std::endl; - } - else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA) - m_iColorType = PER_CELL; - else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA) - m_iColorType = PER_VERTEX; - else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA) - { - std::cout << "WARNING TO BE REMOVED: Can not process colours with scalar mode using cell field data!" << std::endl; - m_iColorType = PER_CELL; - } - else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) - { - std::cout << "WARNING TO BE REMOVED: Can not process colours with scalar mode using point field data!" << std::endl; - m_iColorType = PER_VERTEX; - } - else if(iScalarMode == VTK_SCALAR_MODE_DEFAULT) - { - //Bummer, we do not know what it is. may be we can make a guess - int numColors = vtkColors->GetNumberOfTuples(); - if (numColors == 0) - { - m_iColorType = NOT_GIVEN; - std::cout << "WARNING: No colors found!" << std::endl; - } - else if (numColors == m_iNumPoints) - m_iColorType = PER_VERTEX; - else if (numColors == m_iNumGLPrimitives) - m_iColorType = PER_CELL; - else - { - m_iColorType = NOT_GIVEN; - std::cout << "WARNING: Number of colors do not match number of points / cells!" << std::endl; - } - } - } - if (_verbose) - { - std::cout << "Colors:" << std::endl; - if (m_iColorType != NOT_GIVEN){ - std::cout << " number of colors: " << vtkColors->GetNumberOfTuples() << std::endl; - std::cout << " colors are given: " << ((m_iColorType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl; - }else{ - std::cout << " no colors are given" << std::endl; - } - } - - // TEXCOORDS - vtkDataArray* vtkTexCoords = pntData->GetTCoords(); - if (_verbose) - { - std::cout << "Tex-coords:" << std::endl; - if (vtkTexCoords) - { - std::cout << " Number of tex-coords: " << vtkTexCoords->GetNumberOfTuples() << std::endl; - hasTexCoords = true; - } - else - std::cout << " No tex-coords where given" << std::endl; - } - - // TRANSFORMATION - double scaling[3]; - double translation[3]; - // double rotation[3]; - - _actor->GetPosition(translation); - _actor->GetScale(scaling); - //_actor->GetRotation(rotation[0], rotation[1], rotation[2]); - - if (_verbose) - std::cout << "set scaling: " << scaling[0] << " " << scaling[1] << " " << scaling[2] << std::endl; - - osg::Matrix m; - m.setIdentity(); - m.setTranslate(translation[0], translation[1], translation[2]); - m.setScale(scaling[0], scaling[1], scaling[2]); - // TODO QUATERNION m.setRotate(rotation[0], rotation[1], rotation[2]) - beginEditCP(_osgTransform); - _osgTransform->setMatrix(m); - endEditCP(_osgTransform); - - _mapper->Update(); - - // Get the converted OpenSG node - NodePtr osgGeomNode = Node::create(); - GeometryPtr osgGeometry = Geometry::create(); - beginEditCP(osgGeomNode); - osgGeomNode->setCore(osgGeometry); - endEditCP(osgGeomNode); - - bool osgConversionSuccess = false; - - GeoPTypesPtr osgTypes = GeoPTypesUI8::create(); - GeoPLengthsPtr osgLengths = GeoPLengthsUI32::create(); - GeoIndicesUI32Ptr osgIndices = GeoIndicesUI32::create(); - GeoPositions3fPtr osgPoints = GeoPositions3f::create(); - GeoNormals3fPtr osgNormals = GeoNormals3f::create(); - GeoColors3fPtr osgColors = GeoColors3f::create(); - GeoTexCoords2dPtr osgTexCoords = GeoTexCoords2d::create(); - - //Rendering with OpenSG simple indexed geometry - if (((m_iNormalType == PER_VERTEX) || (m_iNormalType == NOT_GIVEN)) && - ((m_iColorType == PER_VERTEX) || (m_iColorType == NOT_GIVEN))) - { - if (_verbose) - std::cout << "Start ProcessGeometryNormalsAndColorsPerVertex()" << std::endl; - - //getting the vertices: - beginEditCP(osgPoints);{ - for (int i=0; i<m_iNumPoints; i++) - { - double *aVertex = pd->GetPoint(i); - osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2])); - } - }endEditCP(osgPoints); - - //possibly getting the normals - if (m_iNormalType == PER_VERTEX) - { - vtkIdType iNumNormals = vtkNormals->GetNumberOfTuples(); - beginEditCP(osgNormals);{ - double *aNormal; - for (int i=0; i<iNumNormals; i++) - { - aNormal = vtkNormals->GetTuple(i); - osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2])); - } - }endEditCP(osgNormals); - if (iNumNormals != m_iNumPoints) - { - std::cout << "WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of normals" << std::endl; - std::cout << "should equal the number of vertices (points)!" << std::endl << std::endl; - } - } - - //possibly getting the colors - if (m_iColorType == PER_VERTEX) - { - vtkIdType iNumColors = vtkColors->GetNumberOfTuples(); - beginEditCP(osgColors);{ - unsigned char aColor[4]; - for (int i=0; i<iNumColors; i++) - { - vtkColors->GetTupleValue(i, aColor); - float r = ((float) aColor[0]) / 255.0f; - float g = ((float) aColor[1]) / 255.0f; - float b = ((float) aColor[2]) / 255.0f; - osgColors->addValue(Color3f(r, g, b)); - } - }endEditCP(osgColors); - if (iNumColors != m_iNumPoints) - { - std::cout << "WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of colors" << std::endl; - std::cout << "should equal the number of vertices (points)!" << std::endl << std::endl; - } - } - - //possibly getting the texture coordinates. These are alwary per vertex - if (vtkTexCoords != NULL) - { - int numTuples = vtkTexCoords->GetNumberOfTuples(); - for (int i=0; i<numTuples; i++) - { - double texCoords[3]; - vtkTexCoords->GetTuple(i, texCoords); - osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1])); - } - } - - //getting the cells - beginEditCP(osgTypes); - beginEditCP(osgLengths); - beginEditCP(osgIndices);{ - vtkCellArray *pCells; - vtkIdType npts, *pts; - int prim; - - prim = 0; - pCells = pd->GetVerts(); - if (pCells->GetNumberOfCells() > 0) - { - for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++) - { - osgLengths->addValue(npts); - osgTypes->addValue(GL_POINTS); - for (int i=0; i<npts; i++) - osgIndices->addValue(pts[i]); - } - } - - prim = 0; - pCells = pd->GetLines(); - if (pCells->GetNumberOfCells() > 0) - { - for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++) - { - osgLengths->addValue(npts); - osgTypes->addValue(GL_LINE_STRIP); - for (int i=0; i<npts; i++) - osgIndices->addValue(pts[i]); - } - } - - prim = 0; - pCells = pd->GetPolys(); - if (pCells->GetNumberOfCells() > 0) - { - for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++) - { - osgLengths->addValue(npts); - osgTypes->addValue(GL_POLYGON); - for (int i=0; i<npts; i++) - osgIndices->addValue(pts[i]); - } - } - - prim = 0; - pCells = pd->GetStrips(); - if (pCells->GetNumberOfCells() > 0) - { - for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++) - { - osgLengths->addValue(npts); - osgTypes->addValue(GL_TRIANGLE_STRIP); - for (int i=0; i<npts; i++) - osgIndices->addValue(pts[i]); - } - } - }endEditCP(osgIndices); - endEditCP(osgLengths); - endEditCP(osgTypes); - - ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords); - beginEditCP(osgGeometry);{ - osgGeometry->setPositions(osgPoints); - osgGeometry->setTypes(osgTypes); - osgGeometry->setLengths(osgLengths); - osgGeometry->setIndices(osgIndices); - osgGeometry->setMaterial(material); - - if (m_iNormalType == PER_VERTEX) osgGeometry->setNormals(osgNormals); - if (m_iColorType == PER_VERTEX) osgGeometry->setColors(osgColors); - if (osgTexCoords->getSize() > 0) osgGeometry->setTexCoords(osgTexCoords); - };endEditCP(osgGeometry); - - osgConversionSuccess = true; - - if (_verbose) - std::cout << " End ProcessGeometryNormalsAndColorsPerVertex()" << std::endl; - } - else - { - //Rendering with OpenSG non indexed geometry by copying a lot of attribute data - if (_verbose) - std::cout << "Start ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" << std::endl; - int gl_primitive_type = -1; - if(m_iNumGLPolygons > 0) - { - if(m_iNumGLPolygons != m_iNumGLPrimitives) - std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl; - gl_primitive_type = GL_POLYGON; - //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POLYGON, pd, osgGeometry); - } - else if(m_iNumGLLineStrips > 0) - { - if (m_iNumGLLineStrips != m_iNumGLPrimitives) - std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl; - gl_primitive_type = GL_LINE_STRIP; - //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_LINE_STRIP, pd osgGeometry); - } - else if(m_iNumGLTriStrips > 0) - { - if (m_iNumGLTriStrips != m_iNumGLPrimitives) - std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl; - gl_primitive_type = GL_TRIANGLE_STRIP; - //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_TRIANGLE_STRIP, pd osgGeometry); - } - else if (m_iNumGLPoints > 0) - { - if (m_iNumGLPoints != m_iNumGLPrimitives) - std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl; - gl_primitive_type = GL_POINTS; - //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POINTS, pd osgGeometry); - } - if(gl_primitive_type != -1) - { - vtkCellArray *pCells; - if (gl_primitive_type == GL_POINTS) - pCells = pd->GetVerts(); - else if (gl_primitive_type == GL_LINE_STRIP) - pCells = pd->GetLines(); - else if (gl_primitive_type == GL_POLYGON) - pCells = pd->GetPolys(); - else if (gl_primitive_type == GL_TRIANGLE_STRIP) - pCells = pd->GetStrips(); - else - { - std::cout << "CVtkActorToOpenSG::ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" << std::endl; - std::cout << " was called with non implemented gl_primitive_type!" << std::endl; - } - - beginEditCP(osgTypes); - beginEditCP(osgLengths); - beginEditCP(osgPoints); - beginEditCP(osgColors); - beginEditCP(osgNormals);{ - int prim = 0; - if (pCells->GetNumberOfCells() > 0) - { - vtkIdType npts, *pts; - for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++) - { - osgLengths->addValue(npts); - osgTypes->addValue(GL_POLYGON); - for (int i=0; i<npts; i++) - { - double *aVertex; - double *aNormal; - unsigned char aColor[4]; - - aVertex = pd->GetPoint(pts[i]); - osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2])); - - if (m_iNormalType == PER_VERTEX) - { - aNormal = vtkNormals->GetTuple(pts[i]); - osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2])); - } - else if (m_iNormalType == PER_CELL) - { - aNormal = vtkNormals->GetTuple(prim); - osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2])); - } - - if (m_iColorType == PER_VERTEX) - { - vtkColors->GetTupleValue(pts[i], aColor); - float r = ((float) aColor[0]) / 255.0f; - float g = ((float) aColor[1]) / 255.0f; - float b = ((float) aColor[2]) / 255.0f; - osgColors->addValue(Color3f(r, g, b)); - } - else if (m_iColorType == PER_CELL) - { - vtkColors->GetTupleValue(prim, aColor); - float r = ((float) aColor[0]) / 255.0f; - float g = ((float) aColor[1]) / 255.0f; - float b = ((float) aColor[2]) / 255.0f; - osgColors->addValue(Color3f(r, g, b)); - } - } - } - } - };endEditCP(osgTypes); - endEditCP(osgLengths); - endEditCP(osgPoints); - endEditCP(osgColors); - endEditCP(osgNormals); - - //possibly getting the texture coordinates. These are always per vertex - vtkPoints *points = pd->GetPoints(); - if ((vtkTexCoords != NULL) && (points != NULL)) - { - int numPoints = points->GetNumberOfPoints(); - int numTexCoords = vtkTexCoords->GetNumberOfTuples(); - if (numPoints == numTexCoords){ - beginEditCP(osgTexCoords);{ - int numTuples = vtkTexCoords->GetNumberOfTuples(); - for (int i=0; i<numTuples; i++) - { - double texCoords[3]; - vtkTexCoords->GetTuple(i, texCoords); - osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1])); - } - };endEditCP(osgTexCoords); - } - } - - ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords); - //GeometryPtr geo = Geometry::create(); - beginEditCP(osgGeometry);{ - osgGeometry->setPositions(osgPoints); - osgGeometry->setTypes(osgTypes); - osgGeometry->setLengths(osgLengths); - osgGeometry->setMaterial(material); - - if (m_iNormalType != NOT_GIVEN) osgGeometry->setNormals(osgNormals); - if (m_iColorType != NOT_GIVEN) osgGeometry->setColors(osgColors); - if (osgTexCoords->getSize() > 0) osgGeometry->setTexCoords(osgTexCoords); - //geo->setMaterial(getDefaultMaterial()); - }endEditCP(osgGeometry); - - osgConversionSuccess = true; - } - if (_verbose) - std::cout << " End ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" << std::endl; - } - - if(!osgConversionSuccess) - { - std::cout << "OpenSG converter was not able to convert this actor." << std::endl; - return false; - } - - if(m_iNormalType == NOT_GIVEN) - { - //GeometryPtr newGeometryPtr = GeometryPtr::dcast(newNodePtr->getCore()); - if((osgGeometry != NullFC) && (m_iColorType == PER_VERTEX)) - { - std::cout << "WARNING: Normals are missing in the vtk layer, calculating normals per vertex!" << std::endl; - calcVertexNormals(osgGeometry); - } - else if ((osgGeometry != NullFC) && (m_iColorType == PER_CELL)) - { - std::cout << "WARNING: Normals are missing in the vtk layer, calculating normals per face!" << std::endl; - calcFaceNormals(osgGeometry); - } - else if (osgGeometry != NullFC) - { - std::cout << "WARNING: Normals are missing in the vtk layer, calculating normals per vertex!" << std::endl; - calcVertexNormals(osgGeometry); - } - } - - std::cout << "Conversion finished." << std::endl; - - // Add node to root - beginEditCP(_osgRoot); - _osgRoot->addChild(osgGeomNode); - endEditCP(_osgRoot); - - return true; + // see if the actor has a mapper. it could be an assembly + if (_actor->GetMapper() == NULL) + return false; + // dont export when not visible + if (_actor->GetVisibility() == 0) + return false; + + vtkDataObject* inputDO = _actor->GetMapper()->GetInputDataObject(0, 0); + if (inputDO == NULL) + return false; + + // Get PolyData. Convert if necessary becasue we only want polydata + vtkSmartPointer<vtkPolyData> pd; + if(inputDO->IsA("vtkCompositeDataSet")) + { + vtkCompositeDataGeometryFilter* gf = vtkCompositeDataGeometryFilter::New(); + gf->SetInput(inputDO); + gf->Update(); + pd = gf->GetOutput(); + gf->Delete(); + } + else if(inputDO->GetDataObjectType() != VTK_POLY_DATA) + { + vtkGeometryFilter* gf = vtkGeometryFilter::New(); + gf->SetInput(inputDO); + gf->Update(); + pd = gf->GetOutput(); + gf->Delete(); + } + else + pd = static_cast<vtkPolyData*>(inputDO); + + // Copy mapper to a new one + vtkPolyDataMapper* pm = vtkPolyDataMapper::New(); + pm->SetInput(pd); + pm->SetScalarRange(_actor->GetMapper()->GetScalarRange()); + pm->SetScalarVisibility(_actor->GetMapper()->GetScalarVisibility()); + pm->SetLookupTable(_actor->GetMapper()->GetLookupTable()); + pm->SetScalarMode(_actor->GetMapper()->GetScalarMode()); + + if(pm->GetScalarMode() == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA || + pm->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA ) + { + if(_actor->GetMapper()->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID ) + pm->ColorByArrayComponent(_actor->GetMapper()->GetArrayId(), + _actor->GetMapper()->GetArrayComponent()); + else + pm->ColorByArrayComponent(_actor->GetMapper()->GetArrayName(), + _actor->GetMapper()->GetArrayComponent()); + } + + _mapper = pm; + // vtkPoints* points = pd->GetPoints(); + vtkPointData* pntData = pd->GetPointData(); + bool hasTexCoords = false; + vtkUnsignedCharArray* vtkColors = pm->MapScalars(1.0); + + // ARRAY SIZES + vtkIdType m_iNumPoints = pd->GetNumberOfPoints(); + if (m_iNumPoints == 0) + return false; + vtkIdType m_iNumGLPoints = pd->GetVerts()->GetNumberOfCells(); + vtkIdType m_iNumGLLineStrips = pd->GetLines()->GetNumberOfCells(); + vtkIdType m_iNumGLPolygons = pd->GetPolys()->GetNumberOfCells(); + vtkIdType m_iNumGLTriStrips = pd->GetStrips()->GetNumberOfCells(); + vtkIdType m_iNumGLPrimitives = m_iNumGLPoints + m_iNumGLLineStrips + m_iNumGLPolygons + + m_iNumGLTriStrips; + bool lit = !(m_iNumGLPolygons == 0 && m_iNumGLTriStrips == 0); + + if (_verbose) + { + std::cout << "Array sizes:" << std::endl; + std::cout << " number of vertices: " << m_iNumPoints << std::endl; + std::cout << " number of GL_POINTS: " << m_iNumGLPoints << std::endl; + std::cout << " number of GL_LINE_STRIPS: " << m_iNumGLLineStrips << std::endl; + std::cout << " number of GL_POLYGON's: " << m_iNumGLPolygons << std::endl; + std::cout << " number of GL_TRIANGLE_STRIPS: " << m_iNumGLTriStrips << std::endl; + std::cout << " number of primitives: " << m_iNumGLPrimitives << std::endl; + } + + _mapper->Update(); + + // NORMALS + vtkDataArray* vtkNormals = NULL; + int m_iNormalType = NOT_GIVEN; + if (_actor->GetProperty()->GetInterpolation() == VTK_FLAT) + { + vtkNormals = pd->GetCellData()->GetNormals(); + if (vtkNormals != NULL) + m_iNormalType = PER_CELL; + } + else + { + vtkNormals = pntData->GetNormals(); + if (vtkNormals != NULL) + m_iNormalType = PER_VERTEX; + } + if (_verbose) + { + std::cout << "Normals:" << std::endl; + if (m_iNormalType != NOT_GIVEN) + { + std::cout << " number of normals: " << vtkNormals->GetNumberOfTuples() << + std::endl; + std::cout << " normals are given: "; + std::cout << + ((m_iNormalType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl; + } + else + std::cout << " no normals are given" << std::endl; + } + + // COLORS + int m_iColorType = NOT_GIVEN; + if(pm->GetScalarVisibility()) + { + int iScalarMode = pm->GetScalarMode(); + if(vtkColors == NULL) + { + m_iColorType = NOT_GIVEN; + std::cout << "WARNING: MapScalars(1.0) did not return array!" << std::endl; + } + else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA) + m_iColorType = PER_CELL; + else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA) + m_iColorType = PER_VERTEX; + else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA) + { + std::cout << + "WARNING TO BE REMOVED: Can not process colours with scalar mode using cell field data!" + << std::endl; + m_iColorType = PER_CELL; + } + else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) + { + std::cout << + "WARNING TO BE REMOVED: Can not process colours with scalar mode using point field data!" + << std::endl; + m_iColorType = PER_VERTEX; + } + else if(iScalarMode == VTK_SCALAR_MODE_DEFAULT) + { + //Bummer, we do not know what it is. may be we can make a guess + int numColors = vtkColors->GetNumberOfTuples(); + if (numColors == 0) + { + m_iColorType = NOT_GIVEN; + std::cout << "WARNING: No colors found!" << std::endl; + } + else if (numColors == m_iNumPoints) + m_iColorType = PER_VERTEX; + else if (numColors == m_iNumGLPrimitives) + m_iColorType = PER_CELL; + else + { + m_iColorType = NOT_GIVEN; + std::cout << + "WARNING: Number of colors do not match number of points / cells!" + << std::endl; + } + } + } + if (_verbose) + { + std::cout << "Colors:" << std::endl; + if (m_iColorType != NOT_GIVEN) + { + std::cout << " number of colors: " << vtkColors->GetNumberOfTuples() << + std::endl; + std::cout << " colors are given: " << + ((m_iColorType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl; + } + else + std::cout << " no colors are given" << std::endl; + } + + // TEXCOORDS + vtkDataArray* vtkTexCoords = pntData->GetTCoords(); + if (_verbose) + { + std::cout << "Tex-coords:" << std::endl; + if (vtkTexCoords) + { + std::cout << " Number of tex-coords: " << + vtkTexCoords->GetNumberOfTuples() << std::endl; + hasTexCoords = true; + } + else + std::cout << " No tex-coords where given" << std::endl; + } + + // TRANSFORMATION + double scaling[3]; + double translation[3]; + // double rotation[3]; + + _actor->GetPosition(translation); + _actor->GetScale(scaling); + //_actor->GetRotation(rotation[0], rotation[1], rotation[2]); + + if (_verbose) + std::cout << "set scaling: " << scaling[0] << " " << scaling[1] << " " << + scaling[2] << std::endl; + + osg::Matrix m; + m.setIdentity(); + m.setTranslate(translation[0], translation[1], translation[2]); + m.setScale(scaling[0], scaling[1], scaling[2]); + // TODO QUATERNION m.setRotate(rotation[0], rotation[1], rotation[2]) + beginEditCP(_osgTransform); + _osgTransform->setMatrix(m); + endEditCP(_osgTransform); + + _mapper->Update(); + + // Get the converted OpenSG node + NodePtr osgGeomNode = Node::create(); + GeometryPtr osgGeometry = Geometry::create(); + beginEditCP(osgGeomNode); + osgGeomNode->setCore(osgGeometry); + endEditCP(osgGeomNode); + + bool osgConversionSuccess = false; + + GeoPTypesPtr osgTypes = GeoPTypesUI8::create(); + GeoPLengthsPtr osgLengths = GeoPLengthsUI32::create(); + GeoIndicesUI32Ptr osgIndices = GeoIndicesUI32::create(); + GeoPositions3fPtr osgPoints = GeoPositions3f::create(); + GeoNormals3fPtr osgNormals = GeoNormals3f::create(); + GeoColors3fPtr osgColors = GeoColors3f::create(); + GeoTexCoords2dPtr osgTexCoords = GeoTexCoords2d::create(); + + //Rendering with OpenSG simple indexed geometry + if (((m_iNormalType == PER_VERTEX) || (m_iNormalType == NOT_GIVEN)) && + ((m_iColorType == PER_VERTEX) || (m_iColorType == NOT_GIVEN))) + { + if (_verbose) + std::cout << "Start ProcessGeometryNormalsAndColorsPerVertex()" << + std::endl; + + //getting the vertices: + beginEditCP(osgPoints); + { + for (int i = 0; i < m_iNumPoints; i++) + { + double* aVertex = pd->GetPoint(i); + osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2])); + } + } endEditCP(osgPoints); + + //possibly getting the normals + if (m_iNormalType == PER_VERTEX) + { + vtkIdType iNumNormals = vtkNormals->GetNumberOfTuples(); + beginEditCP(osgNormals); + { + double* aNormal; + for (int i = 0; i < iNumNormals; i++) + { + aNormal = vtkNormals->GetTuple(i); + osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], + aNormal[2])); + } + } endEditCP(osgNormals); + if (iNumNormals != m_iNumPoints) + { + std::cout << + "WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of normals" + << std::endl; + std::cout << "should equal the number of vertices (points)!" << + std::endl << std::endl; + } + } + + //possibly getting the colors + if (m_iColorType == PER_VERTEX) + { + vtkIdType iNumColors = vtkColors->GetNumberOfTuples(); + beginEditCP(osgColors); + { + unsigned char aColor[4]; + for (int i = 0; i < iNumColors; i++) + { + vtkColors->GetTupleValue(i, aColor); + float r = ((float) aColor[0]) / 255.0f; + float g = ((float) aColor[1]) / 255.0f; + float b = ((float) aColor[2]) / 255.0f; + osgColors->addValue(Color3f(r, g, b)); + } + } endEditCP(osgColors); + if (iNumColors != m_iNumPoints) + { + std::cout << + "WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of colors" + << std::endl; + std::cout << "should equal the number of vertices (points)!" << + std::endl << std::endl; + } + } + + //possibly getting the texture coordinates. These are alwary per vertex + if (vtkTexCoords != NULL) + { + int numTuples = vtkTexCoords->GetNumberOfTuples(); + for (int i = 0; i < numTuples; i++) + { + double texCoords[3]; + vtkTexCoords->GetTuple(i, texCoords); + osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1])); + } + } + + //getting the cells + beginEditCP(osgTypes); + beginEditCP(osgLengths); + beginEditCP(osgIndices); + { + vtkCellArray* pCells; + vtkIdType npts, * pts; + int prim; + + prim = 0; + pCells = pd->GetVerts(); + if (pCells->GetNumberOfCells() > 0) + for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); + prim++) + { + osgLengths->addValue(npts); + osgTypes->addValue(GL_POINTS); + for (int i = 0; i < npts; i++) + osgIndices->addValue(pts[i]); + } + + prim = 0; + pCells = pd->GetLines(); + if (pCells->GetNumberOfCells() > 0) + for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); + prim++) + { + osgLengths->addValue(npts); + osgTypes->addValue(GL_LINE_STRIP); + for (int i = 0; i < npts; i++) + osgIndices->addValue(pts[i]); + } + + prim = 0; + pCells = pd->GetPolys(); + if (pCells->GetNumberOfCells() > 0) + for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); + prim++) + { + osgLengths->addValue(npts); + osgTypes->addValue(GL_POLYGON); + for (int i = 0; i < npts; i++) + osgIndices->addValue(pts[i]); + } + + prim = 0; + pCells = pd->GetStrips(); + if (pCells->GetNumberOfCells() > 0) + for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); + prim++) + { + osgLengths->addValue(npts); + osgTypes->addValue(GL_TRIANGLE_STRIP); + for (int i = 0; i < npts; i++) + osgIndices->addValue(pts[i]); + } + } endEditCP(osgIndices); + endEditCP(osgLengths); + endEditCP(osgTypes); + + ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords); + beginEditCP(osgGeometry); + { + osgGeometry->setPositions(osgPoints); + osgGeometry->setTypes(osgTypes); + osgGeometry->setLengths(osgLengths); + osgGeometry->setIndices(osgIndices); + osgGeometry->setMaterial(material); + + if (m_iNormalType == PER_VERTEX) + osgGeometry->setNormals(osgNormals); + if (m_iColorType == PER_VERTEX) + osgGeometry->setColors(osgColors); + if (osgTexCoords->getSize() > 0) + osgGeometry->setTexCoords(osgTexCoords); + } endEditCP(osgGeometry); + + osgConversionSuccess = true; + + if (_verbose) + std::cout << " End ProcessGeometryNormalsAndColorsPerVertex()" << + std::endl; + } + else + { + //Rendering with OpenSG non indexed geometry by copying a lot of attribute data + if (_verbose) + std::cout << + "Start ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" << + std::endl; + int gl_primitive_type = -1; + if(m_iNumGLPolygons > 0) + { + if(m_iNumGLPolygons != m_iNumGLPrimitives) + std::cout << + "WARNING: vtkActor contains different kind of primitives" << + std::endl; + gl_primitive_type = GL_POLYGON; + //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POLYGON, pd, osgGeometry); + } + else if(m_iNumGLLineStrips > 0) + { + if (m_iNumGLLineStrips != m_iNumGLPrimitives) + std::cout << + "WARNING: vtkActor contains different kind of primitives" << + std::endl; + gl_primitive_type = GL_LINE_STRIP; + //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_LINE_STRIP, pd osgGeometry); + } + else if(m_iNumGLTriStrips > 0) + { + if (m_iNumGLTriStrips != m_iNumGLPrimitives) + std::cout << + "WARNING: vtkActor contains different kind of primitives" << + std::endl; + gl_primitive_type = GL_TRIANGLE_STRIP; + //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_TRIANGLE_STRIP, pd osgGeometry); + } + else if (m_iNumGLPoints > 0) + { + if (m_iNumGLPoints != m_iNumGLPrimitives) + std::cout << + "WARNING: vtkActor contains different kind of primitives" << + std::endl; + gl_primitive_type = GL_POINTS; + //osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POINTS, pd osgGeometry); + } + if(gl_primitive_type != -1) + { + vtkCellArray* pCells; + if (gl_primitive_type == GL_POINTS) + pCells = pd->GetVerts(); + else if (gl_primitive_type == GL_LINE_STRIP) + pCells = pd->GetLines(); + else if (gl_primitive_type == GL_POLYGON) + pCells = pd->GetPolys(); + else if (gl_primitive_type == GL_TRIANGLE_STRIP) + pCells = pd->GetStrips(); + else + { + std::cout << + "CVtkActorToOpenSG::ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" + << std::endl; + std::cout << + " was called with non implemented gl_primitive_type!" << std::endl; + } + + beginEditCP(osgTypes); + beginEditCP(osgLengths); + beginEditCP(osgPoints); + beginEditCP(osgColors); + beginEditCP(osgNormals); + { + int prim = 0; + if (pCells->GetNumberOfCells() > 0) + { + vtkIdType npts, * pts; + for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); + prim++) + { + osgLengths->addValue(npts); + osgTypes->addValue(GL_POLYGON); + for (int i = 0; i < npts; i++) + { + double* aVertex; + double* aNormal; + unsigned char aColor[4]; + + aVertex = pd->GetPoint(pts[i]); + osgPoints->addValue(Vec3f(aVertex[0], + aVertex[1], + aVertex[2])); + + if (m_iNormalType == PER_VERTEX) + { + aNormal = + vtkNormals->GetTuple(pts[i]); + osgNormals->addValue(Vec3f(aNormal[ + 0 + ], + aNormal[1], aNormal[2])); + } + else if (m_iNormalType == PER_CELL) + { + aNormal = vtkNormals->GetTuple(prim); + osgNormals->addValue(Vec3f(aNormal[ + 0 + ], + aNormal[1], aNormal[2])); + } + + if (m_iColorType == PER_VERTEX) + { + vtkColors->GetTupleValue(pts[i], + aColor); + float r = ((float) aColor[0]) / + 255.0f; + float g = ((float) aColor[1]) / + 255.0f; + float b = ((float) aColor[2]) / + 255.0f; + osgColors->addValue(Color3f(r, g, b)); + } + else if (m_iColorType == PER_CELL) + { + vtkColors->GetTupleValue(prim, + aColor); + float r = ((float) aColor[0]) / + 255.0f; + float g = ((float) aColor[1]) / + 255.0f; + float b = ((float) aColor[2]) / + 255.0f; + osgColors->addValue(Color3f(r, g, b)); + } + } + } + } + } endEditCP(osgTypes); + endEditCP(osgLengths); + endEditCP(osgPoints); + endEditCP(osgColors); + endEditCP(osgNormals); + + //possibly getting the texture coordinates. These are always per vertex + vtkPoints* points = pd->GetPoints(); + if ((vtkTexCoords != NULL) && (points != NULL)) + { + int numPoints = points->GetNumberOfPoints(); + int numTexCoords = vtkTexCoords->GetNumberOfTuples(); + if (numPoints == numTexCoords) + { + beginEditCP(osgTexCoords); + { + int numTuples = vtkTexCoords->GetNumberOfTuples(); + for (int i = 0; i < numTuples; i++) + { + double texCoords[3]; + vtkTexCoords->GetTuple(i, texCoords); + osgTexCoords->addValue(Vec2f(texCoords[0], + texCoords[1])); + } + } endEditCP(osgTexCoords); + } + } + + ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords); + //GeometryPtr geo = Geometry::create(); + beginEditCP(osgGeometry); + { + osgGeometry->setPositions(osgPoints); + osgGeometry->setTypes(osgTypes); + osgGeometry->setLengths(osgLengths); + osgGeometry->setMaterial(material); + + if (m_iNormalType != NOT_GIVEN) + osgGeometry->setNormals(osgNormals); + if (m_iColorType != NOT_GIVEN) + osgGeometry->setColors(osgColors); + if (osgTexCoords->getSize() > 0) + osgGeometry->setTexCoords(osgTexCoords); + //geo->setMaterial(getDefaultMaterial()); + } endEditCP(osgGeometry); + + osgConversionSuccess = true; + } + if (_verbose) + std::cout << + " End ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" << + std::endl; + } + + if(!osgConversionSuccess) + { + std::cout << "OpenSG converter was not able to convert this actor." << std::endl; + return false; + } + + if(m_iNormalType == NOT_GIVEN) + { + //GeometryPtr newGeometryPtr = GeometryPtr::dcast(newNodePtr->getCore()); + if((osgGeometry != NullFC) && (m_iColorType == PER_VERTEX)) + { + std::cout << + "WARNING: Normals are missing in the vtk layer, calculating normals per vertex!" + << std::endl; + calcVertexNormals(osgGeometry); + } + else if ((osgGeometry != NullFC) && (m_iColorType == PER_CELL)) + { + std::cout << + "WARNING: Normals are missing in the vtk layer, calculating normals per face!" + << std::endl; + calcFaceNormals(osgGeometry); + } + else if (osgGeometry != NullFC) + { + std::cout << + "WARNING: Normals are missing in the vtk layer, calculating normals per vertex!" + << std::endl; + calcVertexNormals(osgGeometry); + } + } + + std::cout << "Conversion finished." << std::endl; + + // Add node to root + beginEditCP(_osgRoot); + _osgRoot->addChild(osgGeomNode); + endEditCP(_osgRoot); + + return true; } void vtkOsgConverter::SetVerbose(bool value) { - _verbose = value; + _verbose = value; } NodePtr vtkOsgConverter::GetOsgNode() { - return _osgRoot; + return _osgRoot; } TextureChunkPtr vtkOsgConverter::CreateTexture(vtkTexture* vtkTexture) { - if(_verbose) - std::cout << "Calling CreateTexture()" << std::endl; - - // if(! m_bTextureHasChanged) - // { - // if (_verbose) - // { - // std::cout << " ... nothing to do" << std::endl; - // std::cout << " End CreateTexture()" << std::endl; - // } - // //can we check if the actual image has been updated, even if the texture is the same? - // return; - // } - // else if(m_pvtkTexture == NULL) - // { - // if (_verbose) - // { - // std::cout << " ... texture is (still ?) NULL" << std::endl; - // std::cout << " EndCreateTexture()" << std::endl; - // } - // //the texture has changed but it is NULL now. We should remove the texture from the material - // return; - // } - // m_bTextureHasChanged = false; - - vtkImageData *imgData = vtkTexture->GetInput(); - int iImgDims[3]; - imgData->GetDimensions(iImgDims); - - vtkPointData *imgPointData = imgData->GetPointData(); - vtkCellData *imgCellData = imgData->GetCellData(); - - vtkDataArray *data = NULL; - - if (imgPointData != NULL) - { - if (NULL != imgPointData->GetScalars()) - { - data = imgPointData->GetScalars(); - if (_verbose) std::cout << " found texture data in point data" << std::endl; - } - } - - if (imgCellData != NULL) - { - if (NULL != imgCellData->GetScalars()) - { - data = imgCellData->GetScalars(); - if (_verbose) std::cout << " found texture data in cell data" << std::endl; - } - } - - if (data == NULL) - { - std::cout << " could not load texture data" << std::endl; - return NullFC; - } - - int iImgComps = data->GetNumberOfComponents(); - int iImgPixels = data->GetNumberOfTuples(); - if (iImgPixels != (iImgDims[0] * iImgDims[1] * iImgDims[2])) - { - std::cout << "Number of pixels in data array seems to be wrong!" << std::endl; - return NullFC; - } - - UInt8 *newImageData = new UInt8[iImgDims[0] * iImgDims[1] * iImgDims[2] * iImgComps]; - vtkUnsignedCharArray *oldImageUChar = NULL; - oldImageUChar = dynamic_cast<vtkUnsignedCharArray*>(data); - int ucharCounter = 0; - if (oldImageUChar != NULL) - { - for (int i=0; i<iImgPixels; i++) - { - unsigned char pixel[4]; - oldImageUChar->GetTupleValue(i, pixel); - for (int j=0; j<iImgComps; j++) - newImageData[ucharCounter + j] = pixel[j]; - ucharCounter += iImgComps; - } - } - else - std::cout << "Pixel data come in unsupported vtk type" << std::endl; - - ImagePtr osgImage = Image::create(); - beginEditCP(osgImage);{ - osgImage->setWidth(iImgDims[0]); - osgImage->setHeight(iImgDims[1]); - osgImage->setDepth(iImgDims[2]); - osgImage->setDataType(Image::OSG_UINT8_IMAGEDATA); - if (iImgComps == 1) - osgImage->setPixelFormat(Image::OSG_L_PF); - else if (iImgComps == 3) - osgImage->setPixelFormat(Image::OSG_RGB_PF); - else if (iImgComps == 4) - osgImage->setPixelFormat(Image::OSG_RGBA_PF); - else - { - std::cout << "Unsupported image type!" << std::endl; - delete [] newImageData; - return NullFC; - } - osgImage->setData(newImageData); - };endEditCP(osgImage); - - TextureChunkPtr osgTextureChunk = TextureChunk::create(); - beginEditCP(osgTextureChunk);{ - osgTextureChunk->setImage(osgImage); - };endEditCP(osgTextureChunk); - - if (_verbose) - { - std::cout << " Loading image with " << iImgDims[0] << " x " << iImgDims[1] << " x " << iImgDims[2] << "pixels." << std::endl; - std::cout << " components: " << iImgComps << std::endl; - std::cout << "End CreateTexture()" << std::endl; - } - - return osgTextureChunk; + if(_verbose) + std::cout << "Calling CreateTexture()" << std::endl; + + // if(! m_bTextureHasChanged) + // { + // if (_verbose) + // { + // std::cout << " ... nothing to do" << std::endl; + // std::cout << " End CreateTexture()" << std::endl; + // } + // //can we check if the actual image has been updated, even if the texture is the same? + // return; + // } + // else if(m_pvtkTexture == NULL) + // { + // if (_verbose) + // { + // std::cout << " ... texture is (still ?) NULL" << std::endl; + // std::cout << " EndCreateTexture()" << std::endl; + // } + // //the texture has changed but it is NULL now. We should remove the texture from the material + // return; + // } + // m_bTextureHasChanged = false; + + vtkImageData* imgData = vtkTexture->GetInput(); + int iImgDims[3]; + imgData->GetDimensions(iImgDims); + + vtkPointData* imgPointData = imgData->GetPointData(); + vtkCellData* imgCellData = imgData->GetCellData(); + + vtkDataArray* data = NULL; + + if (imgPointData != NULL) + if (NULL != imgPointData->GetScalars()) + { + data = imgPointData->GetScalars(); + if (_verbose) + std::cout << " found texture data in point data" << std::endl; + } + + if (imgCellData != NULL) + if (NULL != imgCellData->GetScalars()) + { + data = imgCellData->GetScalars(); + if (_verbose) + std::cout << " found texture data in cell data" << std::endl; + } + + if (data == NULL) + { + std::cout << " could not load texture data" << std::endl; + return NullFC; + } + + int iImgComps = data->GetNumberOfComponents(); + int iImgPixels = data->GetNumberOfTuples(); + if (iImgPixels != (iImgDims[0] * iImgDims[1] * iImgDims[2])) + { + std::cout << "Number of pixels in data array seems to be wrong!" << std::endl; + return NullFC; + } + + UInt8* newImageData = new UInt8[iImgDims[0] * iImgDims[1] * iImgDims[2] * iImgComps]; + vtkUnsignedCharArray* oldImageUChar = NULL; + oldImageUChar = dynamic_cast<vtkUnsignedCharArray*>(data); + int ucharCounter = 0; + if (oldImageUChar != NULL) + for (int i = 0; i < iImgPixels; i++) + { + unsigned char pixel[4]; + oldImageUChar->GetTupleValue(i, pixel); + for (int j = 0; j < iImgComps; j++) + newImageData[ucharCounter + j] = pixel[j]; + ucharCounter += iImgComps; + } + else + std::cout << "Pixel data come in unsupported vtk type" << std::endl; + + ImagePtr osgImage = Image::create(); + beginEditCP(osgImage); + { + osgImage->setWidth(iImgDims[0]); + osgImage->setHeight(iImgDims[1]); + osgImage->setDepth(iImgDims[2]); + osgImage->setDataType(Image::OSG_UINT8_IMAGEDATA); + if (iImgComps == 1) + osgImage->setPixelFormat(Image::OSG_L_PF); + else if (iImgComps == 3) + osgImage->setPixelFormat(Image::OSG_RGB_PF); + else if (iImgComps == 4) + osgImage->setPixelFormat(Image::OSG_RGBA_PF); + else + { + std::cout << "Unsupported image type!" << std::endl; + delete [] newImageData; + return NullFC; + } + osgImage->setData(newImageData); + } endEditCP(osgImage); + + TextureChunkPtr osgTextureChunk = TextureChunk::create(); + beginEditCP(osgTextureChunk); + { + osgTextureChunk->setImage(osgImage); + } endEditCP(osgTextureChunk); + + if (_verbose) + { + std::cout << " Loading image with " << iImgDims[0] << " x " << iImgDims[1] << + " x " << iImgDims[2] << "pixels." << std::endl; + std::cout << " components: " << iImgComps << std::endl; + std::cout << "End CreateTexture()" << std::endl; + } + + return osgTextureChunk; } ChunkMaterialPtr vtkOsgConverter::CreateMaterial(bool lit, bool hasTexCoords) { - if (_verbose) - std::cout << "Start CreateMaterial()" << std::endl; - - vtkProperty *prop = _actor->GetProperty(); - double *diffuseColor = prop->GetDiffuseColor(); - double *ambientColor = prop->GetAmbientColor(); - double *specularColor = prop->GetSpecularColor(); - double specularPower = prop->GetSpecularPower(); - - double diffuse = prop->GetDiffuse(); - double ambient = prop->GetAmbient(); - double specular = prop->GetSpecular(); - double opacity = prop->GetOpacity(); - - float pointSize = prop->GetPointSize(); - float lineWidth = prop->GetLineWidth(); - // int lineStipplePattern = prop->GetLineStipplePattern(); - - int representation = prop->GetRepresentation(); - - if (_verbose) - { - std::cout << " Colors:" << std::endl; - std::cout << " diffuse " << diffuse << " * " << diffuseColor[0] << " " << diffuseColor[1] << " " << diffuseColor[2] << std::endl; - std::cout << " ambient " << ambient << " * " << ambientColor[0] << " " << ambientColor[1] << " " << ambientColor[2] << std::endl; - std::cout << " specular " << specular << " * " << specularColor[0] << " " << specularColor[1] << " " << specularColor[2] << std::endl; - } - - - PolygonChunkPtr polygonChunk = PolygonChunk::create(); - beginEditCP(polygonChunk);{ - if (representation == VTK_SURFACE) - { - polygonChunk->setFrontMode(GL_FILL); - polygonChunk->setBackMode(GL_FILL); - } - else if (representation == VTK_WIREFRAME) - { - polygonChunk->setFrontMode(GL_LINE); - polygonChunk->setBackMode(GL_LINE); - } - else - { - polygonChunk->setFrontMode(GL_POINT); - polygonChunk->setBackMode(GL_POINT); - } - };endEditCP(polygonChunk); - - MaterialChunkPtr osgMaterialChunk = MaterialChunk::create(); - beginEditCP(osgMaterialChunk);{ - osgMaterialChunk->setDiffuse(Color4f(diffuseColor[0]*diffuse, diffuseColor[1]*diffuse, diffuseColor[2]*diffuse, opacity)); - osgMaterialChunk->setSpecular(Color4f(specularColor[0]*specular, specularColor[1]*specular, specularColor[2]*specular, 1.0)); - osgMaterialChunk->setAmbient(Color4f(ambientColor[0]*ambient, ambientColor[1]*ambient, ambientColor[2]*ambient, opacity)); - osgMaterialChunk->setShininess(specularPower); - - //if(opacity < 1.0) - //{ - // osgMaterialChunk->setColorMaterial(GL_AMBIENT); // HACK: Opacity does not work with GL_AMBIENT_AND_DIFFUSE - //osgMaterialChunk->setTransparency(1.0f - opacity); - //} - //else - osgMaterialChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE); - - // On objects consisting only of points or lines, dont lit - if(!lit) - osgMaterialChunk->setLit(false); - - };endEditCP(osgMaterialChunk); - - ChunkMaterialPtr osgChunkMaterial = ChunkMaterial::create(); - beginEditCP(osgChunkMaterial);{ - osgChunkMaterial->addChunk(osgMaterialChunk); - osgChunkMaterial->addChunk(TwoSidedLightingChunk::create()); - osgChunkMaterial->addChunk(polygonChunk); - - if(pointSize > 1.0f) - { - PointChunkPtr pointChunk = PointChunk::create(); - pointChunk->setSize(pointSize); - osgChunkMaterial->addChunk(pointChunk); - } - - if(lineWidth > 1.0f) - { - LineChunkPtr lineChunk = LineChunk::create(); - lineChunk->setWidth(lineWidth); - osgChunkMaterial->addChunk(lineChunk); - } - - // TEXTURE - if (hasTexCoords) - { - vtkTexture* vtkTexture = _actor->GetTexture(); - if (vtkTexture) - { - TextureChunkPtr osgTextureChunk = NullFC; - osgTextureChunk = CreateTexture(vtkTexture); - - if(osgTextureChunk != NullFC) - { - if (_verbose) - std::cout << " Add TextureChunk" << std::endl; - osgChunkMaterial->addChunk(osgTextureChunk); - } - } - } - }endEditCP(osgChunkMaterial); - - if (_verbose) - std::cout << " End CreateMaterial()" << std::endl; - - return osgChunkMaterial; + if (_verbose) + std::cout << "Start CreateMaterial()" << std::endl; + + vtkProperty* prop = _actor->GetProperty(); + double* diffuseColor = prop->GetDiffuseColor(); + double* ambientColor = prop->GetAmbientColor(); + double* specularColor = prop->GetSpecularColor(); + double specularPower = prop->GetSpecularPower(); + + double diffuse = prop->GetDiffuse(); + double ambient = prop->GetAmbient(); + double specular = prop->GetSpecular(); + double opacity = prop->GetOpacity(); + + float pointSize = prop->GetPointSize(); + float lineWidth = prop->GetLineWidth(); + // int lineStipplePattern = prop->GetLineStipplePattern(); + + int representation = prop->GetRepresentation(); + + if (_verbose) + { + std::cout << " Colors:" << std::endl; + std::cout << " diffuse " << diffuse << " * " << diffuseColor[0] << " " << + diffuseColor[1] << " " << diffuseColor[2] << std::endl; + std::cout << " ambient " << ambient << " * " << ambientColor[0] << " " << + ambientColor[1] << " " << ambientColor[2] << std::endl; + std::cout << " specular " << specular << " * " << specularColor[0] << " " << + specularColor[1] << " " << specularColor[2] << std::endl; + } + + PolygonChunkPtr polygonChunk = PolygonChunk::create(); + beginEditCP(polygonChunk); + { + if (representation == VTK_SURFACE) + { + polygonChunk->setFrontMode(GL_FILL); + polygonChunk->setBackMode(GL_FILL); + } + else if (representation == VTK_WIREFRAME) + { + polygonChunk->setFrontMode(GL_LINE); + polygonChunk->setBackMode(GL_LINE); + } + else + { + polygonChunk->setFrontMode(GL_POINT); + polygonChunk->setBackMode(GL_POINT); + } + } endEditCP(polygonChunk); + + MaterialChunkPtr osgMaterialChunk = MaterialChunk::create(); + beginEditCP(osgMaterialChunk); + { + osgMaterialChunk->setDiffuse(Color4f(diffuseColor[0] * diffuse, diffuseColor[1] * + diffuse, diffuseColor[2] * diffuse, opacity)); + osgMaterialChunk->setSpecular(Color4f(specularColor[0] * specular, + specularColor[1] * specular, + specularColor[2] * specular, 1.0)); + osgMaterialChunk->setAmbient(Color4f(ambientColor[0] * ambient, ambientColor[1] * + ambient, ambientColor[2] * ambient, opacity)); + osgMaterialChunk->setShininess(specularPower); + + //if(opacity < 1.0) + //{ + // osgMaterialChunk->setColorMaterial(GL_AMBIENT); // HACK: Opacity does not work with GL_AMBIENT_AND_DIFFUSE + //osgMaterialChunk->setTransparency(1.0f - opacity); + //} + //else + osgMaterialChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE); + + // On objects consisting only of points or lines, dont lit + if(!lit) + osgMaterialChunk->setLit(false); + } endEditCP(osgMaterialChunk); + + ChunkMaterialPtr osgChunkMaterial = ChunkMaterial::create(); + beginEditCP(osgChunkMaterial); + { + osgChunkMaterial->addChunk(osgMaterialChunk); + osgChunkMaterial->addChunk(TwoSidedLightingChunk::create()); + osgChunkMaterial->addChunk(polygonChunk); + + if(pointSize > 1.0f) + { + PointChunkPtr pointChunk = PointChunk::create(); + pointChunk->setSize(pointSize); + osgChunkMaterial->addChunk(pointChunk); + } + + if(lineWidth > 1.0f) + { + LineChunkPtr lineChunk = LineChunk::create(); + lineChunk->setWidth(lineWidth); + osgChunkMaterial->addChunk(lineChunk); + } + + // TEXTURE + if (hasTexCoords) + { + vtkTexture* vtkTexture = _actor->GetTexture(); + if (vtkTexture) + { + TextureChunkPtr osgTextureChunk = NullFC; + osgTextureChunk = CreateTexture(vtkTexture); + + if(osgTextureChunk != NullFC) + { + if (_verbose) + std::cout << " Add TextureChunk" << std::endl; + osgChunkMaterial->addChunk(osgTextureChunk); + } + } + } + } endEditCP(osgChunkMaterial); + + if (_verbose) + std::cout << " End CreateMaterial()" << std::endl; + + return osgChunkMaterial; } diff --git a/OpenSG/vtkOsgConverter.h b/OpenSG/vtkOsgConverter.h index 81b0ccdd227e4c7f915b116a08cc19c90d0cd1b4..ca24f736743d01a1d5d547333a35d50d31712649 100644 --- a/OpenSG/vtkOsgConverter.h +++ b/OpenSG/vtkOsgConverter.h @@ -7,11 +7,11 @@ #ifndef VTKOSGCONVERTER_H #define VTKOSGCONVERTER_H -#include <OpenSG/OSGRefPtr.h> +#include <OpenSG/OSGChunkMaterial.h> #include <OpenSG/OSGNode.h> -#include <OpenSG/OSGTransform.h> +#include <OpenSG/OSGRefPtr.h> #include <OpenSG/OSGTextureChunk.h> -#include <OpenSG/OSGChunkMaterial.h> +#include <OpenSG/OSGTransform.h> class vtkActor; class vtkMapper; @@ -19,7 +19,7 @@ class vtkTexture; /// @brief Converts a vtkActor to an OpenSG-Node. /// Example usage: -/// +/// /// @code /// vtkOsgConverter* osgConverter = new vtkOsgConverter(aVtkActor); /// if(osgConverter->WriteAnActor()) @@ -32,29 +32,28 @@ class vtkTexture; class vtkOsgConverter { public: - vtkOsgConverter(vtkActor* actor); - virtual ~vtkOsgConverter(); - - bool WriteAnActor(); - void SetVerbose(bool value); - OSG::NodePtr GetOsgNode(); + vtkOsgConverter(vtkActor* actor); + virtual ~vtkOsgConverter(); + + bool WriteAnActor(); + void SetVerbose(bool value); + OSG::NodePtr GetOsgNode(); protected: private: - vtkActor* _actor; - vtkMapper* _mapper; - - enum {NOT_GIVEN, PER_VERTEX, PER_CELL}; - bool _verbose; + vtkActor* _actor; + vtkMapper* _mapper; + enum {NOT_GIVEN, PER_VERTEX, PER_CELL}; + bool _verbose; - //For the translation to OpenSG - OSG::RefPtr<OSG::NodePtr> _osgRoot; - OSG::RefPtr<OSG::TransformPtr> _osgTransform; + //For the translation to OpenSG + OSG::RefPtr<OSG::NodePtr> _osgRoot; + OSG::RefPtr<OSG::TransformPtr> _osgTransform; - OSG::TextureChunkPtr CreateTexture(vtkTexture* vtkTexture); - OSG::ChunkMaterialPtr CreateMaterial(bool lit, bool hasTexCoords); + OSG::TextureChunkPtr CreateTexture(vtkTexture* vtkTexture); + OSG::ChunkMaterialPtr CreateMaterial(bool lit, bool hasTexCoords); }; #endif // VTKOSGCONVERTER_H \ No newline at end of file diff --git a/Vrpn/QSpaceNavigatorClient.cpp b/Vrpn/QSpaceNavigatorClient.cpp index 94309727446b17a4ed4f00b30cbd5c4104747ace..b62ecbc994892e2458918da5dffdd9984ef26f81 100644 --- a/Vrpn/QSpaceNavigatorClient.cpp +++ b/Vrpn/QSpaceNavigatorClient.cpp @@ -1,7 +1,7 @@ /** * \file QSpaceNavigatorClient.cpp * 31/08/2010 LB Initial implementation - * + * * Implementation of QSpaceNavigatorClient class */ @@ -11,7 +11,7 @@ QSpaceNavigatorClient* QSpaceNavigatorClient::_singleton = 0; QSpaceNavigatorClient::QSpaceNavigatorClient(QObject* parent /*= NULL*/) -: QObject(parent), SpaceNavigatorClient() + : QObject(parent), SpaceNavigatorClient() { //SpaceNavigatorClient::Instance(); _time.start(); @@ -21,7 +21,6 @@ QSpaceNavigatorClient::QSpaceNavigatorClient(QObject* parent /*= NULL*/) QSpaceNavigatorClient::~QSpaceNavigatorClient() { - } QSpaceNavigatorClient* QSpaceNavigatorClient::Instance(QObject* parent /*= NULL*/) @@ -31,8 +30,8 @@ QSpaceNavigatorClient* QSpaceNavigatorClient::Instance(QObject* parent /*= NULL* return _singleton; } -void QSpaceNavigatorClient::init(const char *deviceName, - int updateInterval /*= 100*/, SpaceNavigatorAxes axis /*= Y*/) +void QSpaceNavigatorClient::init(const char* deviceName, + int updateInterval /*= 100*/, SpaceNavigatorAxes axis /*= Y*/) { SpaceNavigatorClient::init(deviceName, axis); if (updateInterval > 0) diff --git a/Vrpn/QSpaceNavigatorClient.h b/Vrpn/QSpaceNavigatorClient.h index 76e117001ed9519aa75f3109a0f003130d71d2ce..20ede3f9c6f9216b72b9a8b161090f8600f7ab17 100644 --- a/Vrpn/QSpaceNavigatorClient.h +++ b/Vrpn/QSpaceNavigatorClient.h @@ -6,8 +6,8 @@ #ifndef QSPACENAVIGATORCLIENT_H #define QSPACENAVIGATORCLIENT_H -#include <QObject> #include "SpaceNavigatorClient.h" +#include <QObject> #include <QTime> #include <QTimer> @@ -15,11 +15,11 @@ class QSpaceNavigatorClient : public QObject, public SpaceNavigatorClient { Q_OBJECT - + public: - /// @brief Returns the singleton of this class + /// @brief Returns the singleton of this class static QSpaceNavigatorClient* Instance(QObject* parent = NULL); - + /// @brief Initializes the SpaceNavigator. /// Connects with the server and registers the callback handlers. /// It is possible to specify the z-axis as the up-axis. @@ -28,32 +28,32 @@ public: /// @param updateInterval The update interval in ms. If 0 then you have to /// manually call update(). /// @param axis The up axis. - void init(const char *deviceName, int updateInterval = 100, SpaceNavigatorAxes axis = Y); - + void init(const char* deviceName, int updateInterval = 100, SpaceNavigatorAxes axis = Y); + public slots: /// @brief Calls the SpaceNavigatorClient::update() method and emits updated() /// and translated() signals if there is new data. /// Is called automatically if an updateInterval was given in init(). void update(); - + protected: /// @brief The constructor is protected because of the singleton /// design pattern. QSpaceNavigatorClient(QObject* parent = NULL); - + /// @brief Destructor. virtual ~QSpaceNavigatorClient(); - + /// @brief Returns the elapsed time since the last function call in ms. int getFrameTime(); private: /// Used in getFrameTime() to compute the elapsed time since last call. QTime _time; - + /// Calls update(), see init(). QTimer* _timer; - + /// @brief This one points to the class itself. /// You can use only one QSpaceNavigatorClient because it´s static. /// This is needed for the callback methods which only @@ -62,7 +62,7 @@ private: signals: void updated(double x, double y, double z, double rx, double ry, double rz); - + /// Is emitted when there is new translation data. void translated(double x, double y, double z); }; diff --git a/Vrpn/QVrpnArtTrackingClient.cpp b/Vrpn/QVrpnArtTrackingClient.cpp index 30c3a351617b62999f26129c803b6adc8eb4cfe0..a6a3eb83c9006b5dc8f5cb96be81c6b04411af5c 100644 --- a/Vrpn/QVrpnArtTrackingClient.cpp +++ b/Vrpn/QVrpnArtTrackingClient.cpp @@ -1,7 +1,7 @@ /** * \file QVrpnArtTrackingClient.cpp * 03/09/2010 LB Initial implementation - * + * * Implementation of QVrpnArtTrackingClient class */ @@ -17,7 +17,7 @@ QVrpnArtTrackingClient* QVrpnArtTrackingClient::_singleton = 0; QVrpnArtTrackingClient::QVrpnArtTrackingClient(QObject* parent /*= NULL*/) -: QObject(parent), VrpnArtTrackingClient() + : QObject(parent), VrpnArtTrackingClient() { //SpaceNavigatorClient::Instance(); _timer = new QTimer(this); @@ -34,7 +34,7 @@ QVrpnArtTrackingClient::~QVrpnArtTrackingClient() settings.setValue("artDeviceNameAt", list.at(1)); settings.setValue("artUpdateInterval", _updateInterval); settings.endGroup(); - + delete _timer; } @@ -45,8 +45,8 @@ QVrpnArtTrackingClient* QVrpnArtTrackingClient::Instance(QObject* parent /*= NUL return _singleton; } -void QVrpnArtTrackingClient::StartTracking(const char *deviceName, - int updateInterval /*= 100*/) +void QVrpnArtTrackingClient::StartTracking(const char* deviceName, + int updateInterval /*= 100*/) { _deviceName = QString(deviceName); _updateInterval = updateInterval; @@ -59,22 +59,22 @@ void QVrpnArtTrackingClient::StartTracking(const char *deviceName, void QVrpnArtTrackingClient::MainLoop() { VrpnArtTrackingClient::MainLoop(); - + double x, y, z; VrpnArtTrackingClient::GetBodyTranslation(x, y, z); //std::cout << "Body: " << x << " " << y << " " << z << std::endl; //std::cout << "Body: " << m_dBodyTranslation[0] << " " << m_dBodyTranslation[1] << " " << m_dBodyTranslation[2] << std::endl; emit positionUpdated(x, z, y); - + /* - if (_unconsumedData) - { - _unconsumedData = false; - double x, y, z, rx, ry, rz; - getTranslation(x, y, z); - getRotation(rx, ry, rz); - //emit updated(x, y, z, rx, ry, rz); - emit translated(x, y, z); - } - */ + if (_unconsumedData) + { + _unconsumedData = false; + double x, y, z, rx, ry, rz; + getTranslation(x, y, z); + getRotation(rx, ry, rz); + //emit updated(x, y, z, rx, ry, rz); + emit translated(x, y, z); + } + */ } diff --git a/Vrpn/QVrpnArtTrackingClient.h b/Vrpn/QVrpnArtTrackingClient.h index 5aa77d1292908e14173a80a2bef882ad702599a7..eee1184da33d8acba1d3e4b9c95fabb4aaf79122 100644 --- a/Vrpn/QVrpnArtTrackingClient.h +++ b/Vrpn/QVrpnArtTrackingClient.h @@ -6,8 +6,8 @@ #ifndef QVRPNARTTRACKINGCLIENT_H #define QVRPNARTTRACKINGCLIENT_H -#include <QObject> #include "VrpnArtTrackingClient.h" +#include <QObject> #include <QTimer> @@ -16,11 +16,11 @@ class QString; class QVrpnArtTrackingClient : public QObject, public VrpnArtTrackingClient { Q_OBJECT - + public: - /// @brief Returns the singleton of this class + /// @brief Returns the singleton of this class static QVrpnArtTrackingClient* Instance(QObject* parent = NULL); - + /// @brief Initializes and starts the tracking. /// @param deviceName The name of the vrpn device @ vrpn server host name /// e.g. DTrack@visserv3.intern.ufz.de @@ -33,13 +33,13 @@ public: /// @ Returns the update interval. int updateInterval() const { return _updateInterval; } - + public slots: /// @brief Calls the vrpn mainloop functions. Must be called once per frame. /// Is called automatically if an updateInterval was given in init(). void MainLoop(); -protected: +protected: QVrpnArtTrackingClient(QObject* parent = NULL); virtual ~QVrpnArtTrackingClient(); @@ -52,7 +52,7 @@ private: /// The update interval int _updateInterval; - + /// @brief This one points to the class itself. /// You can use only one QVrpnArtTrackingClient because it´s static. /// This is needed for the callback methods which only diff --git a/Vrpn/SpaceNavigatorClient.cpp b/Vrpn/SpaceNavigatorClient.cpp index 71217cfcfa36acd1556cdd8fcf64b487f3414dee..e737d53c927ede4177a52b07f91a572a80dd4983 100644 --- a/Vrpn/SpaceNavigatorClient.cpp +++ b/Vrpn/SpaceNavigatorClient.cpp @@ -7,10 +7,9 @@ #include "SpaceNavigatorClient.h" #include <iostream> - SpaceNavigatorClient* SpaceNavigatorClient::_spacenavigator = 0; -SpaceNavigatorClient::SpaceNavigatorClient() +SpaceNavigatorClient::SpaceNavigatorClient() { _button = NULL; _analog = NULL; @@ -39,39 +38,57 @@ SpaceNavigatorClient::~SpaceNavigatorClient() // clean up if(_button) { - _button->unregister_change_handler(NULL, (vrpn_BUTTONCHANGEHANDLER)SpaceNavigatorClient::_handleButtons); + _button->unregister_change_handler( + NULL, + (vrpn_BUTTONCHANGEHANDLER) SpaceNavigatorClient + ::_handleButtons); delete _button; _button = NULL; } if(_analog) { - _analog->unregister_change_handler(NULL, (vrpn_ANALOGCHANGEHANDLER)SpaceNavigatorClient::_handleAnalogs); + _analog->unregister_change_handler( + NULL, + (vrpn_ANALOGCHANGEHANDLER) SpaceNavigatorClient + ::_handleAnalogs); delete _analog; _analog = NULL; } } -void SpaceNavigatorClient::init( const char *deviceName, SpaceNavigatorAxes axis /*= Y*/ ) +void SpaceNavigatorClient::init( const char* deviceName, SpaceNavigatorAxes axis /*= Y*/ ) { // Create new button_remote object that connects to the corresponding server object // at the specified computer and register the callback function if(_button) { - _button->unregister_change_handler(NULL, (vrpn_BUTTONCHANGEHANDLER)SpaceNavigatorClient::_handleButtons); + _button->unregister_change_handler( + NULL, + (vrpn_BUTTONCHANGEHANDLER) SpaceNavigatorClient + ::_handleButtons); delete _button; } _button = new vrpn_Button_Remote(deviceName); - _button->register_change_handler(NULL, (vrpn_BUTTONCHANGEHANDLER)SpaceNavigatorClient::_handleButtons); + _button->register_change_handler( + NULL, + (vrpn_BUTTONCHANGEHANDLER) SpaceNavigatorClient:: + _handleButtons); // Create new analog_remote object that connects to the corresponding server object // at the specified computer and register the callback function if(_analog) { - _analog->unregister_change_handler(NULL, (vrpn_ANALOGCHANGEHANDLER)SpaceNavigatorClient::_handleAnalogs); + _analog->unregister_change_handler( + NULL, + (vrpn_ANALOGCHANGEHANDLER) SpaceNavigatorClient + ::_handleAnalogs); delete _analog; } _analog = new vrpn_Analog_Remote(deviceName); - _analog->register_change_handler(NULL, (vrpn_ANALOGCHANGEHANDLER)SpaceNavigatorClient::_handleAnalogs); + _analog->register_change_handler( + NULL, + (vrpn_ANALOGCHANGEHANDLER) SpaceNavigatorClient:: + _handleAnalogs); // set up axis if(axis == Z) @@ -98,8 +115,8 @@ void SpaceNavigatorClient::update() { double frameTime = getFrameTime(); // in ms _frameTranslationFactor = _translationFactor * (frameTime / 1000.0); - _frameRotationFactor = _rotationFactor * (frameTime / 800.0); - + _frameRotationFactor = _rotationFactor * (frameTime / 800.0); + // process messages from server this->_button->mainloop(); this->_analog->mainloop(); @@ -134,56 +151,56 @@ void SpaceNavigatorClient::setDomination(bool dominating) { this->_dominating = dominating; - #ifdef SPACENAVIGATOR_DEBUG_OUTPUT - std::cout << "SpaceNavigator: Axis domination mode: "; - if(dominating) - std::cout << "ON" << std::endl; - else - std::cout << "OFF" << std::endl; - #endif // SPACENAVIGATOR_DEBUG_OUTPUT +#ifdef SPACENAVIGATOR_DEBUG_OUTPUT + std::cout << "SpaceNavigator: Axis domination mode: "; + if(dominating) + std::cout << "ON" << std::endl; + else + std::cout << "OFF" << std::endl; +#endif // SPACENAVIGATOR_DEBUG_OUTPUT } void SpaceNavigatorClient::switchDomination() { this->_dominating = !this->_dominating; - - #ifdef SPACENAVIGATOR_DEBUG_OUTPUT - std::cout << "SpaceNavigator: Axis domination mode: "; - if(_dominating) - std::cout << "ON" << std::endl; - else - std::cout << "OFF" << std::endl; - #endif // SPACENAVIGATOR_DEBUG_OUTPUT + +#ifdef SPACENAVIGATOR_DEBUG_OUTPUT + std::cout << "SpaceNavigator: Axis domination mode: "; + if(_dominating) + std::cout << "ON" << std::endl; + else + std::cout << "OFF" << std::endl; +#endif // SPACENAVIGATOR_DEBUG_OUTPUT } void SpaceNavigatorClient::setMode(SpaceNavigatorClient::SpaceNavigatorMode mode) { this->_mode = mode; - #ifdef SPACENAVIGATOR_DEBUG_OUTPUT - std::cout << "SpaceNavigator: Transformation mode: "; - if(mode == TRANSROT) - std::cout << "TRANSLATION and ROTATION" << std::endl; - else if(mode == TRANS) - std::cout << "TRANSLATION only" << std::endl; - else if(mode == ROT) - std::cout << "ROTATION only" << std::endl; - #endif // SPACENAVIGATOR_DEBUG_OUTPUT +#ifdef SPACENAVIGATOR_DEBUG_OUTPUT + std::cout << "SpaceNavigator: Transformation mode: "; + if(mode == TRANSROT) + std::cout << "TRANSLATION and ROTATION" << std::endl; + else if(mode == TRANS) + std::cout << "TRANSLATION only" << std::endl; + else if(mode == ROT) + std::cout << "ROTATION only" << std::endl; +#endif // SPACENAVIGATOR_DEBUG_OUTPUT } void SpaceNavigatorClient::switchMode() { this->_mode = (SpaceNavigatorClient::SpaceNavigatorMode)((this->_mode + 1) % 3); - #ifdef SPACENAVIGATOR_DEBUG_OUTPUT - std::cout << "SpaceNavigator: Transformation mode: "; - if(_mode == TRANSROT) - std::cout << "TRANSLATION and ROTATION" << std::endl; - else if(_mode == TRANS) - std::cout << "TRANSLATION only" << std::endl; - else if(_mode == ROT) - std::cout << "ROTATION only" << std::endl; - #endif // SPACENAVIGATOR_DEBUG_OUTPUT +#ifdef SPACENAVIGATOR_DEBUG_OUTPUT + std::cout << "SpaceNavigator: Transformation mode: "; + if(_mode == TRANSROT) + std::cout << "TRANSLATION and ROTATION" << std::endl; + else if(_mode == TRANS) + std::cout << "TRANSLATION only" << std::endl; + else if(_mode == ROT) + std::cout << "ROTATION only" << std::endl; +#endif // SPACENAVIGATOR_DEBUG_OUTPUT } void SpaceNavigatorClient::setDefaultButtonBehaviour(bool enable) @@ -191,7 +208,6 @@ void SpaceNavigatorClient::setDefaultButtonBehaviour(bool enable) _defaultButtonBehaviour = enable; } - void SpaceNavigatorClient::invertAxis(SpaceNavigatorAxes axisToInvert) { if(axisToInvert < 7 && axisToInvert > 0) @@ -199,14 +215,14 @@ void SpaceNavigatorClient::invertAxis(SpaceNavigatorAxes axisToInvert) if(_invertAxes[axisToInvert - 1] == 1.0) _invertAxes[axisToInvert - 1] = -1.0; else - _invertAxes[axisToInvert -1] = 1.0; + _invertAxes[axisToInvert - 1] = 1.0; } } -void VRPN_CALLBACK SpaceNavigatorClient::_handleButtons(void *, vrpn_BUTTONCB buttonData) +void VRPN_CALLBACK SpaceNavigatorClient::_handleButtons(void*, vrpn_BUTTONCB buttonData) { // read button data - _spacenavigator->buttons[buttonData.button] = buttonData.state ? true:false; + _spacenavigator->buttons[buttonData.button] = buttonData.state ? true : false; if(_spacenavigator->_defaultButtonBehaviour) { @@ -216,11 +232,11 @@ void VRPN_CALLBACK SpaceNavigatorClient::_handleButtons(void *, vrpn_BUTTONCB bu if(_spacenavigator->buttons[1]) _spacenavigator->switchDomination(); } - + _spacenavigator->_unconsumedData = true; } -void VRPN_CALLBACK SpaceNavigatorClient::_handleAnalogs(void *, vrpn_ANALOGCB analogData) +void VRPN_CALLBACK SpaceNavigatorClient::_handleAnalogs(void*, vrpn_ANALOGCB analogData) { // read data from the analog axes // range [0, 1] @@ -234,32 +250,45 @@ void VRPN_CALLBACK SpaceNavigatorClient::_handleAnalogs(void *, vrpn_ANALOGCB an double max = analogData.channel[0]; int index = 0; for(int i = 1; i < 6; i++) - { if(abs(analogData.channel[i]) > abs(max)) { index = i; max = analogData.channel[i]; } - } - _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = _spacenavigator->rx = _spacenavigator->ry = _spacenavigator->rz = 0; + _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = + _spacenavigator->rx = + _spacenavigator-> + ry = _spacenavigator->rz = 0; switch(index) { - case 0: _spacenavigator->x = max * _spacenavigator->_invertAxes[0]; break; - case 2: _spacenavigator->y = max * _spacenavigator->_invertAxes[1]; break; - case 1: _spacenavigator->z = max * _spacenavigator->_invertAxes[2]; break; - case 3: _spacenavigator->rx = max * _spacenavigator->_invertAxes[3]; break; - case 5: _spacenavigator->ry = max * _spacenavigator->_invertAxes[4]; break; - case 4: _spacenavigator->rz = max * _spacenavigator->_invertAxes[5]; break; + case 0: _spacenavigator->x = max * _spacenavigator->_invertAxes[0]; + break; + case 2: _spacenavigator->y = max * _spacenavigator->_invertAxes[1]; + break; + case 1: _spacenavigator->z = max * _spacenavigator->_invertAxes[2]; + break; + case 3: _spacenavigator->rx = max * _spacenavigator->_invertAxes[3]; + break; + case 5: _spacenavigator->ry = max * _spacenavigator->_invertAxes[4]; + break; + case 4: _spacenavigator->rz = max * _spacenavigator->_invertAxes[5]; + break; } } else { - _spacenavigator->x = analogData.channel[0] * _spacenavigator->_invertAxes[0]; - _spacenavigator->y = analogData.channel[2] * _spacenavigator->_invertAxes[1]; - _spacenavigator->z = analogData.channel[1] * _spacenavigator->_invertAxes[2]; - _spacenavigator->rx = analogData.channel[3] * _spacenavigator->_invertAxes[3]; - _spacenavigator->ry = analogData.channel[5] * _spacenavigator->_invertAxes[4]; - _spacenavigator->rz = analogData.channel[4] * _spacenavigator->_invertAxes[5]; + _spacenavigator->x = analogData.channel[0] * + _spacenavigator->_invertAxes[0]; + _spacenavigator->y = analogData.channel[2] * + _spacenavigator->_invertAxes[1]; + _spacenavigator->z = analogData.channel[1] * + _spacenavigator->_invertAxes[2]; + _spacenavigator->rx = analogData.channel[3] * + _spacenavigator->_invertAxes[3]; + _spacenavigator->ry = analogData.channel[5] * + _spacenavigator->_invertAxes[4]; + _spacenavigator->rz = analogData.channel[4] * + _spacenavigator->_invertAxes[5]; } } @@ -271,26 +300,33 @@ void VRPN_CALLBACK SpaceNavigatorClient::_handleAnalogs(void *, vrpn_ANALOGCB an double max = analogData.channel[0]; int index = 0; for(int i = 1; i < 3; i++) - { if(abs(analogData.channel[i]) > abs(max)) { index = i; max = analogData.channel[i]; } - } - _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = _spacenavigator->rx = _spacenavigator->ry = _spacenavigator->rz = 0; + _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = + _spacenavigator->rx = + _spacenavigator-> + ry = _spacenavigator->rz = 0; switch(index) { - case 0: _spacenavigator->x = max * _spacenavigator->_invertAxes[0]; break; - case 2: _spacenavigator->y = max * _spacenavigator->_invertAxes[1]; break; - case 1: _spacenavigator->z = max * _spacenavigator->_invertAxes[2]; break; + case 0: _spacenavigator->x = max * _spacenavigator->_invertAxes[0]; + break; + case 2: _spacenavigator->y = max * _spacenavigator->_invertAxes[1]; + break; + case 1: _spacenavigator->z = max * _spacenavigator->_invertAxes[2]; + break; } } else { - _spacenavigator->x = analogData.channel[0] * _spacenavigator->_invertAxes[0]; - _spacenavigator->y = analogData.channel[2] * _spacenavigator->_invertAxes[1]; - _spacenavigator->z = analogData.channel[1] * _spacenavigator->_invertAxes[2]; + _spacenavigator->x = analogData.channel[0] * + _spacenavigator->_invertAxes[0]; + _spacenavigator->y = analogData.channel[2] * + _spacenavigator->_invertAxes[1]; + _spacenavigator->z = analogData.channel[1] * + _spacenavigator->_invertAxes[2]; _spacenavigator->rx = _spacenavigator->ry = _spacenavigator->rz = 0; } } @@ -303,26 +339,33 @@ void VRPN_CALLBACK SpaceNavigatorClient::_handleAnalogs(void *, vrpn_ANALOGCB an double max = analogData.channel[3]; int index = 3; for(int i = 4; i < 6; i++) - { if(abs(analogData.channel[i]) > abs(max)) { index = i; max = analogData.channel[i]; } - } - _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = _spacenavigator->rx = _spacenavigator->ry = _spacenavigator->rz = 0; + _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = + _spacenavigator->rx = + _spacenavigator-> + ry = _spacenavigator->rz = 0; switch(index) { - case 3: _spacenavigator->rx = max * _spacenavigator->_invertAxes[3]; break; - case 5: _spacenavigator->ry = max * _spacenavigator->_invertAxes[4]; break; - case 4: _spacenavigator->rz = max * _spacenavigator->_invertAxes[5]; break; + case 3: _spacenavigator->rx = max * _spacenavigator->_invertAxes[3]; + break; + case 5: _spacenavigator->ry = max * _spacenavigator->_invertAxes[4]; + break; + case 4: _spacenavigator->rz = max * _spacenavigator->_invertAxes[5]; + break; } } else { - _spacenavigator->rx = analogData.channel[3] * _spacenavigator->_invertAxes[3]; - _spacenavigator->ry = analogData.channel[5] * _spacenavigator->_invertAxes[4]; - _spacenavigator->rz = analogData.channel[4] * _spacenavigator->_invertAxes[5]; + _spacenavigator->rx = analogData.channel[3] * + _spacenavigator->_invertAxes[3]; + _spacenavigator->ry = analogData.channel[5] * + _spacenavigator->_invertAxes[4]; + _spacenavigator->rz = analogData.channel[4] * + _spacenavigator->_invertAxes[5]; _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = 0; } } @@ -338,19 +381,21 @@ void VRPN_CALLBACK SpaceNavigatorClient::_handleAnalogs(void *, vrpn_ANALOGCB an _spacenavigator->ry = _spacenavigator->rz; _spacenavigator->rz = temp; } - + _spacenavigator->_unconsumedData = true; - - #ifdef SPACENAVIGATOR_DEBUG_OUTPUT - std::cout << "Translation: { " << _spacenavigator->x << ", " << _spacenavigator->y << ", " << _spacenavigator->z << " }" << std::endl; - std::cout << "Rotation: { " << _spacenavigator->rx << ", " << _spacenavigator->ry << ", " << _spacenavigator->rz << " }" << std::endl; - #endif // SPACENAVIGATOR_DEBUG_OUTPUT + +#ifdef SPACENAVIGATOR_DEBUG_OUTPUT + std::cout << "Translation: { " << _spacenavigator->x << ", " << _spacenavigator->y << + ", " << _spacenavigator->z << " }" << std::endl; + std::cout << "Rotation: { " << _spacenavigator->rx << ", " << _spacenavigator->ry << + ", " << _spacenavigator->rz << " }" << std::endl; +#endif // SPACENAVIGATOR_DEBUG_OUTPUT } SpaceNavigatorClient* SpaceNavigatorClient::Instance() { if(_spacenavigator == 0) _spacenavigator = new SpaceNavigatorClient(); - + return _spacenavigator; } diff --git a/Vrpn/SpaceNavigatorClient.h b/Vrpn/SpaceNavigatorClient.h index f322496d696b61f1f2b03cd8ce66f587a5d84f62..f6f1115e97063b3651a96ec3d46842711c952810 100644 --- a/Vrpn/SpaceNavigatorClient.h +++ b/Vrpn/SpaceNavigatorClient.h @@ -10,17 +10,17 @@ //#define SPACENAVIGATOR_DEBUG_OUTPUT // ** INCLUDES ** -#include <vrpn_Button.h> #include <vrpn_Analog.h> +#include <vrpn_Button.h> // ** SpaceNavigatorClient - CLASS ** // This implements the singleton design pattern. // ****************************** class SpaceNavigatorClient -{ +{ public: // ** ENUMS ** - + /// @brief Navigation modes: translation and rotation or translation /// or rotation only. enum SpaceNavigatorMode @@ -57,40 +57,40 @@ public: /// @param axis The up axis. /// It is possible to specify the z-axis as the up-axis. /// Default the y-axis is the up-axis. - void init(const char *deviceName, SpaceNavigatorAxes axis = Y); - + void init(const char* deviceName, SpaceNavigatorAxes axis = Y); + /// @brief Returns the translation values. void getTranslation(double& retx, double& rety, double& retz) const; - + /// @brief Returns the rotation values void getRotation(double& retx, double& rety, double& retz) const; - + /// @brief Updates the translation and rotation values. /// Must be called once per frame before getTranslation/Rotation. void update(); - + /// @brief Sets the translation scaling factor. void setTranslationFactor(double factor); - + /// @brief Sets the rotation scaling factor. void setRotationFactor(double factor); /// @brief Returns true if Z is the up axis. bool getZUpAxis(); - + /// @brief Sets if Z is the up axis. void setZUpAxis(bool zUp); /// @brief Enables / disables the axis-domination mode. /// Only the axis with the highest value is used. void setDomination(bool dominating); - + /// @brief Switches axis-domination mode. void switchDomination(); /// @brief Switch navigation mode. See SpaceNavigatorMode. void setMode(SpaceNavigatorClient::SpaceNavigatorMode mode); - + /// @brief Switch through navigation modes. void switchMode(); @@ -105,14 +105,14 @@ public: protected: // ** Protected member functions ** - + /// @brief The constructor is protected because of the singleton /// design pattern. SpaceNavigatorClient(); /// @brief Destructor virtual ~SpaceNavigatorClient(); - + /// @brief Returns the elapsed time since the last function call in ms. /// This must be implemented in a subclass. virtual int getFrameTime() { return 1; } @@ -127,20 +127,20 @@ protected: /// @brief Actual values of the translation double x, y, z; - + /// @brief This one points to the class itself. /// You can use only one SpaceNavigatorClient because it´s static. /// This is needed for the callback methods which only /// can access static members. static SpaceNavigatorClient* _spacenavigator; - + /// @brief Is set to true if a vrpn callback was called. bool _unconsumedData; private: // ** Private member fields ** - vrpn_Button_Remote *_button; - vrpn_Analog_Remote *_analog; + vrpn_Button_Remote* _button; + vrpn_Analog_Remote* _analog; // is domination mode active? bool _dominating; @@ -159,23 +159,22 @@ private: /// @brief Callbacks which are called whenever a button is pressed /// or the SpaceNavigator is moved. /// Callbacks as class members have to be static. - static void VRPN_CALLBACK _handleButtons(void *, vrpn_BUTTONCB buttonData); - static void VRPN_CALLBACK _handleAnalogs(void *, vrpn_ANALOGCB analogData); - + static void VRPN_CALLBACK _handleButtons(void*, vrpn_BUTTONCB buttonData); + static void VRPN_CALLBACK _handleAnalogs(void*, vrpn_ANALOGCB analogData); + // which is the up-axis (y - normal, z - from the gis world) SpaceNavigatorAxes _upAxis; - + // The translation factor. double _translationFactor; - + // The rotation factor. double _rotationFactor; - + // The translation factor for this frame. double _frameTranslationFactor; - + // The rotation factor for this frame. double _frameRotationFactor; - }; #endif // SPACENAVIGATORCLIENT_H diff --git a/Vrpn/TrackingSettingsWidget.cpp b/Vrpn/TrackingSettingsWidget.cpp index 704d684701e70d34669db3fa56acf88b8d7e1f8f..ad3a078d8182cfc8d3390f2a3fc47c6cbdabb085 100644 --- a/Vrpn/TrackingSettingsWidget.cpp +++ b/Vrpn/TrackingSettingsWidget.cpp @@ -1,33 +1,33 @@ /** * \file TrackingSettingsWidget.cpp * 06/09/2010 LB Initial implementation - * + * * Implementation of TrackingSettingsWidget class */ // ** INCLUDES ** -#include "TrackingSettingsWidget.h" -#include "VtkTrackedCamera.h" #include "QSpaceNavigatorClient.h" #include "QVrpnArtTrackingClient.h" +#include "TrackingSettingsWidget.h" +#include "VtkTrackedCamera.h" #include <QCompleter> -#include <QStringList> -#include <QLineEdit> #include <QDoubleValidator> +#include <QLineEdit> +#include <QStringList> TrackingSettingsWidget::TrackingSettingsWidget(VtkTrackedCamera* cam, - QWidget* parent /*= 0*/, Qt::WindowFlags f /*= 0*/) -: QWidget(parent, f), _cam(cam) + QWidget* parent /*= 0*/, Qt::WindowFlags f /*= 0*/) + : QWidget(parent, f), _cam(cam) { setupUi(this); - + QStringList deviceNameAtSuggestionList; deviceNameAtSuggestionList << "141.65.34.36" << "visserv3.intern.ufz.de" << "localhost"; QCompleter* deviceNameAtCompleter = new QCompleter(deviceNameAtSuggestionList, this); deviceNameAtCompleter->setCaseSensitivity(Qt::CaseInsensitive); deviceNameAtLineEdit->setCompleter(deviceNameAtCompleter); - + offsetXLineEdit->setValidator(new QDoubleValidator(offsetXLineEdit)); offsetYLineEdit->setValidator(new QDoubleValidator(offsetYLineEdit)); offsetZLineEdit->setValidator(new QDoubleValidator(offsetZLineEdit)); diff --git a/Vrpn/TrackingSettingsWidget.h b/Vrpn/TrackingSettingsWidget.h index 4457473b2804e4dd34314eba5f6df23f28079ac4..eb29a90fa0ea300357679e95d5f4ff65812bbdbc 100644 --- a/Vrpn/TrackingSettingsWidget.h +++ b/Vrpn/TrackingSettingsWidget.h @@ -16,7 +16,7 @@ class QVrpnArtTrackingClient; class TrackingSettingsWidget : public QWidget, public Ui_TrackingSettingsWidgetBase { Q_OBJECT - + public: TrackingSettingsWidget(VtkTrackedCamera* cam, QWidget* parent = 0, Qt::WindowFlags f = 0); virtual ~TrackingSettingsWidget(); diff --git a/Vrpn/VrpnArtTrackingClient.cpp b/Vrpn/VrpnArtTrackingClient.cpp index 259d9e6c6cce4dfdff08f18e6be950fa6a1ce1b3..0364d8d761ed00ef3293c34ec1a64051a799c4d1 100644 --- a/Vrpn/VrpnArtTrackingClient.cpp +++ b/Vrpn/VrpnArtTrackingClient.cpp @@ -1,25 +1,25 @@ #include "VrpnArtTrackingClient.h" -#include <iostream> #include <assert.h> +#include <iostream> VrpnArtTrackingClient* VrpnArtTrackingClient::m_pInstance = NULL; VrpnArtTrackingClient::VrpnArtTrackingClient() { int i; - for (i=0; i<3; i++) + for (i = 0; i < 3; i++) { m_dBodyTranslation[i] = 0.0; m_dFlyTranslation[i] = 0.0; } - for (i=0; i<4; i++) + for (i = 0; i < 4; i++) { m_dBodyQuaternion[i] = 0.0; m_dFlyQuaternion[i] = 0.0; } - for (i=0; i<10; i++) + for (i = 0; i < 10; i++) { m_dAnalogData[i] = 0.0; m_bButtonData[i] = false; @@ -30,12 +30,11 @@ VrpnArtTrackingClient::VrpnArtTrackingClient() m_pvrpnButtons = NULL; m_bTrackingStarted = false; - + m_pInstance = this; } - -VrpnArtTrackingClient *VrpnArtTrackingClient::Instance() +VrpnArtTrackingClient* VrpnArtTrackingClient::Instance() { if (m_pInstance == NULL) { @@ -46,42 +45,57 @@ VrpnArtTrackingClient *VrpnArtTrackingClient::Instance() return m_pInstance; } - VrpnArtTrackingClient::~VrpnArtTrackingClient() { StopTracking(); } - void VrpnArtTrackingClient::StartTracking(const char* deviceName) { m_pvrpnAnalog = new vrpn_Analog_Remote(deviceName); m_pvrpnTracker = new vrpn_Tracker_Remote(deviceName); m_pvrpnButtons = new vrpn_Button_Remote(deviceName); - m_pvrpnTracker->register_change_handler(NULL, (vrpn_TRACKERCHANGEHANDLER) VrpnArtTrackingClient::CBHandleTracker); - m_pvrpnAnalog->register_change_handler(NULL, (vrpn_ANALOGCHANGEHANDLER) VrpnArtTrackingClient::CBHandleAnalogs); - m_pvrpnButtons->register_change_handler(NULL, (vrpn_BUTTONCHANGEHANDLER) VrpnArtTrackingClient::CBHandleButtons); + m_pvrpnTracker->register_change_handler( + NULL, + (vrpn_TRACKERCHANGEHANDLER) VrpnArtTrackingClient:: + CBHandleTracker); + m_pvrpnAnalog->register_change_handler( + NULL, + (vrpn_ANALOGCHANGEHANDLER) VrpnArtTrackingClient:: + CBHandleAnalogs); + m_pvrpnButtons->register_change_handler( + NULL, + (vrpn_BUTTONCHANGEHANDLER) VrpnArtTrackingClient:: + CBHandleButtons); m_bTrackingStarted = true; } - void VrpnArtTrackingClient::StopTracking() { if (m_pvrpnAnalog) { - m_pvrpnAnalog->unregister_change_handler(NULL, (vrpn_ANALOGCHANGEHANDLER) VrpnArtTrackingClient::CBHandleAnalogs); + m_pvrpnAnalog->unregister_change_handler( + NULL, + (vrpn_ANALOGCHANGEHANDLER) + VrpnArtTrackingClient::CBHandleAnalogs); delete m_pvrpnAnalog; } if (m_pvrpnTracker) { - m_pvrpnTracker->unregister_change_handler(NULL, (vrpn_TRACKERCHANGEHANDLER) VrpnArtTrackingClient::CBHandleTracker); + m_pvrpnTracker->unregister_change_handler( + NULL, + (vrpn_TRACKERCHANGEHANDLER) + VrpnArtTrackingClient::CBHandleTracker); delete m_pvrpnTracker; } if (m_pvrpnButtons) { - m_pvrpnButtons->unregister_change_handler(NULL, (vrpn_BUTTONCHANGEHANDLER) VrpnArtTrackingClient::CBHandleButtons); + m_pvrpnButtons->unregister_change_handler( + NULL, + (vrpn_BUTTONCHANGEHANDLER) + VrpnArtTrackingClient::CBHandleButtons); delete m_pvrpnButtons; } @@ -90,18 +104,18 @@ void VrpnArtTrackingClient::StopTracking() m_pvrpnButtons = NULL; int i; - for (i=0; i<3; i++) + for (i = 0; i < 3; i++) { m_dBodyTranslation[i] = 0.0; m_dFlyTranslation[i] = 0.0; } - for (i=0; i<4; i++) + for (i = 0; i < 4; i++) { m_dBodyQuaternion[i] = 0.0; m_dFlyQuaternion[i] = 0.0; } - for (i=0; i<10; i++) + for (i = 0; i < 10; i++) { m_dAnalogData[i] = 0.0; m_bButtonData[i] = false; @@ -120,7 +134,9 @@ void VrpnArtTrackingClient::MainLoop() m_pvrpnButtons->mainloop(); } else - std::cout << "WARNING: VrpnArtTrackingClient::MainLoop() has been called but tracking ist not been started!" << std::endl; + std::cout << + "WARNING: VrpnArtTrackingClient::MainLoop() has been called but tracking ist not been started!" + << std::endl; } void VrpnArtTrackingClient::GetBodyTranslation(double &x, double &y, double &z) @@ -129,8 +145,10 @@ void VrpnArtTrackingClient::GetBodyTranslation(double &x, double &y, double &z) y = m_dBodyTranslation[1]; z = m_dBodyTranslation[2]; - if (! m_bTrackingStarted) - std::cout << "WARNING: VrpnArtTrackingClient::GetBodyTranslation() has been called but tracking has not been started!" << std::endl; + if (!m_bTrackingStarted) + std::cout << + "WARNING: VrpnArtTrackingClient::GetBodyTranslation() has been called but tracking has not been started!" + << std::endl; } void VrpnArtTrackingClient::GetBodyQuaternion(double &v0, double &v1, double &v2, double &v3) @@ -140,8 +158,10 @@ void VrpnArtTrackingClient::GetBodyQuaternion(double &v0, double &v1, double &v2 v2 = m_dBodyQuaternion[2]; v3 = m_dBodyQuaternion[3]; - if (! m_bTrackingStarted) - std::cout << "WARNING: VrpnArtTrackingClient::GetBodyQuaternion() has been called but tracking has not been started!" << std::endl; + if (!m_bTrackingStarted) + std::cout << + "WARNING: VrpnArtTrackingClient::GetBodyQuaternion() has been called but tracking has not been started!" + << std::endl; } void VrpnArtTrackingClient::GetFlyTranslation(double &x, double &y, double &z) @@ -150,8 +170,10 @@ void VrpnArtTrackingClient::GetFlyTranslation(double &x, double &y, double &z) y = m_dFlyTranslation[1]; z = m_dFlyTranslation[2]; - if (! m_bTrackingStarted) - std::cout << "WARNING: VrpnArtTrackingClient::GetFlyTranslation() has been called but tracking has not been started!" << std::endl; + if (!m_bTrackingStarted) + std::cout << + "WARNING: VrpnArtTrackingClient::GetFlyTranslation() has been called but tracking has not been started!" + << std::endl; } void VrpnArtTrackingClient::GetFlyQuaternion(double &v0, double &v1, double &v2, double &v3) @@ -161,20 +183,23 @@ void VrpnArtTrackingClient::GetFlyQuaternion(double &v0, double &v1, double &v2, v2 = m_dFlyQuaternion[2]; v3 = m_dFlyQuaternion[3]; - if (! m_bTrackingStarted) - std::cout << "WARNING: VrpnArtTrackingClient::GetFlyQuaternion() has been called but tracking has not been started!" << std::endl; + if (!m_bTrackingStarted) + std::cout << + "WARNING: VrpnArtTrackingClient::GetFlyQuaternion() has been called but tracking has not been started!" + << std::endl; } double VrpnArtTrackingClient::GetAnalogData(int index) { - if (index < 10){ + if (index < 10) return m_dAnalogData[index]; - }else{ + else return 0.0; - } - if (! m_bTrackingStarted) - std::cout << "WARNING: VrpnArtTrackingClient::GetAnalogData() has been called but tracking has not been started!" << std::endl; + if (!m_bTrackingStarted) + std::cout << + "WARNING: VrpnArtTrackingClient::GetAnalogData() has been called but tracking has not been started!" + << std::endl; } bool VrpnArtTrackingClient::GetButtonData(int index) @@ -184,66 +209,64 @@ bool VrpnArtTrackingClient::GetButtonData(int index) else return false; - if (! m_bTrackingStarted) - std::cout << "WARNING: VrpnArtTrackingClient::GetButtonData() has been called but tracking has not been started!" << std::endl; + if (!m_bTrackingStarted) + std::cout << + "WARNING: VrpnArtTrackingClient::GetButtonData() has been called but tracking has not been started!" + << std::endl; } -void VRPN_CALLBACK VrpnArtTrackingClient::CBHandleTracker(void *userdata, const vrpn_TRACKERCB t) +void VRPN_CALLBACK VrpnArtTrackingClient::CBHandleTracker(void* userdata, const vrpn_TRACKERCB t) { (void)userdata; - VrpnArtTrackingClient *art = m_pInstance; + VrpnArtTrackingClient* art = m_pInstance; if (art != NULL) { if (t.sensor == 0) { //std::cout << "CBHandleTracker" << std::endl; - for (int i=0; i<3; i++) - { + for (int i = 0; i < 3; i++) art->m_dBodyTranslation[i] = t.pos[i]; //std::cout << t.pos[i] << std::endl; - } - for (int i=0; i<4; i++) - { + for (int i = 0; i < 4; i++) art->m_dBodyQuaternion[i] = t.quat[i]; //std::cout << t.quat[i] << std::endl; - } } else if (t.sensor == 1) { - for (int i=0; i<3; i++) + for (int i = 0; i < 3; i++) art->m_dFlyTranslation[i] = t.pos[i]; - for (int i=0; i<4; i++) + for (int i = 0; i < 4; i++) art->m_dFlyQuaternion[i] = t.quat[i]; } } } -void VRPN_CALLBACK VrpnArtTrackingClient::CBHandleAnalogs(void *, vrpn_ANALOGCB analogData) +void VRPN_CALLBACK VrpnArtTrackingClient::CBHandleAnalogs(void*, vrpn_ANALOGCB analogData) { - //std::cout << "CBHandleAnalogs" << std::endl; - - VrpnArtTrackingClient *art = m_pInstance; + + VrpnArtTrackingClient* art = m_pInstance; if (art != NULL) { int numChannels = analogData.num_channel; - if (numChannels > 10) numChannels = 10; - for (int i=0; i<numChannels; i++) + if (numChannels > 10) + numChannels = 10; + for (int i = 0; i < numChannels; i++) art->m_dAnalogData[i] = analogData.channel[i]; } } -void VRPN_CALLBACK VrpnArtTrackingClient::CBHandleButtons(void *userdata, vrpn_BUTTONCB buttonData) +void VRPN_CALLBACK VrpnArtTrackingClient::CBHandleButtons(void* userdata, vrpn_BUTTONCB buttonData) { //std::cout << "CBHandleButtons" << std::endl; - + (void)userdata; - VrpnArtTrackingClient *art = m_pInstance; + VrpnArtTrackingClient* art = m_pInstance; if (art != NULL) { int buttonIndex = buttonData.button; if (buttonIndex < 10) - art->m_bButtonData[buttonIndex] = buttonData.state ? true:false; + art->m_bButtonData[buttonIndex] = buttonData.state ? true : false; } } diff --git a/Vrpn/VrpnArtTrackingClient.h b/Vrpn/VrpnArtTrackingClient.h index 212c521420bdf1b43bdd3e7878d36bd9e620452b..9cfd40026cd2368b1fbbbb5b142c5db0468edebd 100644 --- a/Vrpn/VrpnArtTrackingClient.h +++ b/Vrpn/VrpnArtTrackingClient.h @@ -1,8 +1,8 @@ #ifndef VRPNARTTRACKINGCLIENT_H #define VRPNARTTRACKINGCLIENT_H -#include <vrpn_Button.h> #include <vrpn_Analog.h> +#include <vrpn_Button.h> #include <vrpn_Tracker.h> /// @brief Vrpn client fort ART-Tracking system @@ -10,81 +10,81 @@ class VrpnArtTrackingClient { public: /// @brief Returns the singleton of this class - static VrpnArtTrackingClient *Instance(); + static VrpnArtTrackingClient* Instance(); /// @brief Initializes and starts the tracking. /// @param deviceName The name of the vrpn device @ vrpn server host name /// e.g. DTrack@visserv3.intern.ufz.de - void StartTracking(const char* deviceName); - + void StartTracking(const char* deviceName); + /// @brief Stops the tracking. - void StopTracking(); - + void StopTracking(); + /// @brief Returns true if tracking is started - bool IsStarted() const {return m_bTrackingStarted;} + bool IsStarted() const {return m_bTrackingStarted; } /// @brief Calls the vrpn mainloop functions. Must be called once per frame. - void MainLoop(); + void MainLoop(); /// @brief Returns the bodys (head) position. - void GetBodyTranslation(double &x, double &y, double &z); - + void GetBodyTranslation(double &x, double &y, double &z); + /// @brief Returns the bodys orientation as a quaternion. - void GetBodyQuaternion(double &v0, double &v1, double &v2, double &v3); + void GetBodyQuaternion(double &v0, double &v1, double &v2, double &v3); /// @brief Returns the flysticks position. - void GetFlyTranslation(double &x, double &y, double &z); - + void GetFlyTranslation(double &x, double &y, double &z); + /// @brief Returns the flysticks orientation as a quaternion. - void GetFlyQuaternion(double &v0, double &v1, double &v2, double &v3); + void GetFlyQuaternion(double &v0, double &v1, double &v2, double &v3); /// @brief Returns the analog value of an axis of the flysticks yellow little joystick. /// @param index The axis. - double GetAnalogData(int index); - + double GetAnalogData(int index); + /// @brief Returns if the button with the given index of the flystick is pressed. - bool GetButtonData(int index); + bool GetButtonData(int index); protected: - + /// @brief The constructor is protected because of the singleton /// design pattern. VrpnArtTrackingClient(); - + /// @brief Destructor. ~VrpnArtTrackingClient(); - + /// @brief This one points to the class itself. /// You can use only one VrpnArtTrackingClient because it´s static. /// This is needed for the callback methods which only /// can access static members. - static VrpnArtTrackingClient *m_pInstance; + static VrpnArtTrackingClient* m_pInstance; // Is the tracker initialized ? - bool m_bTrackingStarted; + bool m_bTrackingStarted; // Tracking values - double m_dBodyQuaternion[4]; - double m_dBodyTranslation[3]; + double m_dBodyQuaternion[4]; + double m_dBodyTranslation[3]; // Flystick - double m_dFlyQuaternion[4]; - double m_dFlyTranslation[3]; + double m_dFlyQuaternion[4]; + double m_dFlyTranslation[3]; // Analogs - double m_dAnalogData[10]; + double m_dAnalogData[10]; // Buttons - bool m_bButtonData[10]; + bool m_bButtonData[10]; // VRPN related stuff - vrpn_Analog_Remote *m_pvrpnAnalog; - vrpn_Tracker_Remote *m_pvrpnTracker; - vrpn_Button_Remote *m_pvrpnButtons; + vrpn_Analog_Remote* m_pvrpnAnalog; + vrpn_Tracker_Remote* m_pvrpnTracker; + vrpn_Button_Remote* m_pvrpnButtons; - static void VRPN_CALLBACK CBHandleTracker(void *userdata, const vrpn_TRACKERCB t); - static void VRPN_CALLBACK CBHandleAnalogs(void *userdata, vrpn_ANALOGCB analogData); - static void VRPN_CALLBACK CBHandleButtons(void *userdata, vrpn_BUTTONCB buttonData); + static void VRPN_CALLBACK CBHandleTracker(void* userdata, const vrpn_TRACKERCB t); + static void VRPN_CALLBACK CBHandleAnalogs(void* userdata, vrpn_ANALOGCB analogData); + static void VRPN_CALLBACK CBHandleButtons(void* userdata, vrpn_BUTTONCB buttonData); }; #endif // VRPNARTTRACKINGCLIENT_H diff --git a/Vrpn/VrpnClient.cpp b/Vrpn/VrpnClient.cpp index bfdc5a2615895f90e0daa1a801e3acbb7add9afe..8b9d9b5bb667824ea2cb0c823f154337fc53d78d 100644 --- a/Vrpn/VrpnClient.cpp +++ b/Vrpn/VrpnClient.cpp @@ -1,43 +1,43 @@ /** * \file VrpnClient.cpp * 30/08/2010 LB Initial implementation - * + * * Implementation of VrpnClient class */ // ** INCLUDES ** #include "VrpnClient.h" -#include <vrpn_Analog.h> #include <QTimer> +#include <vrpn_Analog.h> void VRPN_CALLBACK handle_analog( void* userData, const vrpn_ANALOGCB a ) { int i; - const char *name = (const char *)userData; + const char* name = (const char*)userData; - printf("Analog %s:\n %5.2f", name, a.channel[0]); - for (i = 1; i < a.num_channel; i++) + printf("Analog %s:\n %5.2f", name, a.channel[0]); + for (i = 1; i < a.num_channel; i++) printf(", %5.2f", a.channel[i]); - printf(" (%d chans)\n", a.num_channel); + printf(" (%d chans)\n", a.num_channel); // if (a.num_channel >= 3) - // emit positionChanged(a.channel[1], a.channel[2], a.channel[3]); - // if (a.num_channel >= 6) - // emit rotationChanged(a.channel[4], a.channel[5], a.channel[6]); + // emit positionChanged(a.channel[1], a.channel[2], a.channel[3]); + // if (a.num_channel >= 6) + // emit rotationChanged(a.channel[4], a.channel[5], a.channel[6]); } VrpnClient::VrpnClient( QString deviceName, int updateInterval /*= 100*/, QObject* parent /*= NULL*/ ) -: QObject(parent) + : QObject(parent) { // Create vrpn analog device _deviceName = deviceName; _vrpnAnalog = new vrpn_Analog_Remote( deviceName.toStdString().c_str() ); _vrpnAnalog->register_change_handler( 0, handle_analog ); - + int numChannels = _vrpnAnalog->getNumChannels(); _analogData.fill(0.0, numChannels); - + // Call the vrpn mainloop every updateInterval ms QTimer* vrpnTimer = new QTimer(this); connect(vrpnTimer, SIGNAL(timeout()), this, SLOT(update())); diff --git a/Vrpn/VrpnClient.h b/Vrpn/VrpnClient.h index 1eda793ae41c99b0c8256646e1a325d6f1ca5541..cdd673da83869208684146c73b0189bbf49ebe0c 100644 --- a/Vrpn/VrpnClient.h +++ b/Vrpn/VrpnClient.h @@ -16,13 +16,13 @@ class vrpn_Analog_Remote; class VrpnClient : public QObject { Q_OBJECT - + public: VrpnClient(QString deviceName, int updateInterval = 100, QObject* parent = NULL); virtual ~VrpnClient(); - + double getAnalog(int channel); - + public slots: void update(); diff --git a/VtkAct/VtkCustomInteractorStyle.cpp b/VtkAct/VtkCustomInteractorStyle.cpp index 2c24bef0186dcd015dffa39436e0e145a37066bf..34cfc3397fa139646355fe69b0db81f2dad6591a 100644 --- a/VtkAct/VtkCustomInteractorStyle.cpp +++ b/VtkAct/VtkCustomInteractorStyle.cpp @@ -1,30 +1,30 @@ /** * \file VtkCustomInteractorStyle.cpp * 21/6/2010 LB Initial implementation - * + * * Implementation of VtkInteractorStyle */ // ** INCLUDES ** #include "VtkCustomInteractorStyle.h" -#include <vtkRenderWindowInteractor.h> -#include <vtkObjectFactory.h> -#include <vtkProp.h> -#include <vtkSmartPointer.h> -#include <vtkDataSetMapper.h> #include <vtkActor.h> +#include <vtkAlgorithmOutput.h> +#include <vtkCamera.h> #include <vtkCellPicker.h> -#include <vtkSelection.h> -#include <vtkSelectionNode.h> +#include <vtkDataSetMapper.h> #include <vtkExtractSelection.h> #include <vtkIdTypeArray.h> -#include <vtkUnstructuredGrid.h> +#include <vtkObjectFactory.h> +#include <vtkProp.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> +#include <vtkRenderWindowInteractor.h> #include <vtkRendererCollection.h> -#include <vtkCamera.h> -#include <vtkAlgorithmOutput.h> +#include <vtkSelection.h> +#include <vtkSelectionNode.h> +#include <vtkSmartPointer.h> +#include <vtkUnstructuredGrid.h> #include <string> @@ -33,7 +33,7 @@ vtkStandardNewMacro(VtkCustomInteractorStyle); VtkCustomInteractorStyle::VtkCustomInteractorStyle() -: _highlightActor(true), _alternateMouseActions(false) + : _highlightActor(true), _alternateMouseActions(false) { selectedMapper = vtkDataSetMapper::New(); selectedActor = vtkActor::New(); @@ -97,7 +97,7 @@ void VtkCustomInteractorStyle::highlightActor( vtkProp3D* actor ) } void VtkCustomInteractorStyle::setHighlightActor(bool on) -{ +{ _highlightActor = on; if (!on) HighlightProp((vtkProp*)NULL); @@ -108,7 +108,8 @@ void VtkCustomInteractorStyle::pickableDataObject(vtkDataObject* object) Data = object; if (!object) { - this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(selectedActor); + this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()-> + RemoveActor(selectedActor); selectedMapper->SetInputConnection(NULL); } } @@ -118,14 +119,14 @@ void VtkCustomInteractorStyle::OnLeftButtonDown() { if (!Data) return vtkInteractorStyleTrackballCamera::OnLeftButtonDown(); - + if (_alternateMouseActions) { // Get the location of the click (in window coordinates) int* pos = this->GetInteractor()->GetEventPosition(); vtkSmartPointer<vtkCellPicker> picker = - vtkSmartPointer<vtkCellPicker>::New(); + vtkSmartPointer<vtkCellPicker>::New(); picker->SetTolerance(0.0005); // Pick from this location. @@ -136,53 +137,58 @@ void VtkCustomInteractorStyle::OnLeftButtonDown() if(picker->GetCellId() != -1) { - - std::cout << "Pick position is: " << worldPosition[0] << " " << worldPosition[1] - << " " << worldPosition[2] << endl; + std::cout << "Pick position is: " << worldPosition[0] << " " << + worldPosition[1] + << " " << worldPosition[2] << endl; vtkSmartPointer<vtkIdTypeArray> ids = - vtkSmartPointer<vtkIdTypeArray>::New(); + vtkSmartPointer<vtkIdTypeArray>::New(); ids->SetNumberOfComponents(1); ids->InsertNextValue(picker->GetCellId()); vtkSmartPointer<vtkSelectionNode> selectionNode = - vtkSmartPointer<vtkSelectionNode>::New(); + vtkSmartPointer<vtkSelectionNode>::New(); selectionNode->SetFieldType(vtkSelectionNode::CELL); selectionNode->SetContentType(vtkSelectionNode::INDICES); selectionNode->SetSelectionList(ids); vtkSmartPointer<vtkSelection> selection = - vtkSmartPointer<vtkSelection>::New(); + vtkSmartPointer<vtkSelection>::New(); selection->AddNode(selectionNode); vtkSmartPointer<vtkExtractSelection> extractSelection = - vtkSmartPointer<vtkExtractSelection>::New(); + vtkSmartPointer<vtkExtractSelection>::New(); extractSelection->SetInput(0, this->Data); extractSelection->SetInput(1, selection); extractSelection->Update(); // In selection vtkSmartPointer<vtkUnstructuredGrid> selected = - vtkSmartPointer<vtkUnstructuredGrid>::New(); + vtkSmartPointer<vtkUnstructuredGrid>::New(); selected->ShallowCopy(extractSelection->GetOutput()); std::cout << "There are " << selected->GetNumberOfPoints() - << " points in the selection." << std::endl; + << " points in the selection." << std::endl; std::cout << "There are " << selected->GetNumberOfCells() - << " cells in the selection." << std::endl; + << " cells in the selection." << std::endl; // check if the underlying object is a mesh and if so, send a signal to the element model for display of information about the picked element. - vtkAlgorithm* data_set = picker->GetActor()->GetMapper()->GetInputConnection(0, 0)->GetProducer()->GetInputConnection(0,0)->GetProducer(); + vtkAlgorithm* data_set = + picker->GetActor()->GetMapper()->GetInputConnection(0, + 0)->GetProducer() + ->GetInputConnection(0,0)->GetProducer(); VtkMeshSource* source = dynamic_cast<VtkMeshSource*>(data_set); if (source) emit elementPicked(source->GetGrid(), picker->GetCellId()); selectedMapper->SetInputConnection(selected->GetProducerPort()); - this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor); + this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()-> + AddActor(selectedActor); } else - this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(selectedActor); + this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()-> + RemoveActor(selectedActor); emit requestViewUpdate(); } else @@ -201,7 +207,7 @@ void VtkCustomInteractorStyle::OnRightButtonDown() int* pos = this->GetInteractor()->GetEventPosition(); vtkSmartPointer<vtkCellPicker> picker = - vtkSmartPointer<vtkCellPicker>::New(); + vtkSmartPointer<vtkCellPicker>::New(); picker->SetTolerance(0.0005); // Pick from this location. @@ -212,7 +218,9 @@ void VtkCustomInteractorStyle::OnRightButtonDown() if(picker->GetCellId() != -1) { - vtkRenderer* renderer = this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer(); + vtkRenderer* renderer = + this->Interactor->GetRenderWindow()->GetRenderers()-> + GetFirstRenderer(); vtkCamera* cam = renderer->GetActiveCamera(); cam->SetFocalPoint(worldPosition); emit requestViewUpdate(); diff --git a/VtkAct/VtkCustomInteractorStyle.h b/VtkAct/VtkCustomInteractorStyle.h index cb9cdbef00babff66f4f2436e1b2cfc2ba658ffe..b4fa3d033d70e4010c363848d7dc7a696e5fea4a 100644 --- a/VtkAct/VtkCustomInteractorStyle.h +++ b/VtkAct/VtkCustomInteractorStyle.h @@ -1,10 +1,9 @@ /** * \file VtkCustomInteractorStyle.h * 21/6/2010 LB Initial implementation - * + * */ - #ifndef VTKCUSTOMINTERACTORSTYLE_H #define VTKCUSTOMINTERACTORSTYLE_H @@ -41,7 +40,7 @@ public: /// @brief Handles key up events. virtual void OnKeyUp(); - + /// @brief Handles left mouse button events (picking). virtual void OnLeftButtonDown(); @@ -51,23 +50,22 @@ public: public slots: void highlightActor(vtkProp3D* prop); void setHighlightActor(bool on); - + /// @brief Sets the highlightable vtk object. void pickableDataObject(vtkDataObject* object); protected: VtkCustomInteractorStyle(); virtual ~VtkCustomInteractorStyle(); - + /// @brief The vtk object to pick. vtkDataObject* Data; - + /// @brief The mapper for highlighting the selected cell. vtkDataSetMapper* selectedMapper; - + /// @brief The actor for highlighting the selected cell. vtkActor* selectedActor; - private: bool _highlightActor; @@ -83,7 +81,6 @@ signals: /// @brief Emitted when a mesh element has been picked void elementPicked(const GridAdapter*, const size_t); - }; #endif // VTKINTERACTORSTYLE_H diff --git a/VtkAct/VtkPickCallback.cpp b/VtkAct/VtkPickCallback.cpp index cc5df3598f990d52f40363adcc26ce44ebd6294b..11873328cb58d11b3c6117004b454786e43723cd 100644 --- a/VtkAct/VtkPickCallback.cpp +++ b/VtkAct/VtkPickCallback.cpp @@ -1,7 +1,7 @@ /** * \file VtkPickCallback.cpp * 21/6/2010 LB Initial implementation - * + * * Implementation of VtkPickCallback */ @@ -11,13 +11,13 @@ #include <vtkActor.h> #include <vtkCellPicker.h> - VtkPickCallback* VtkPickCallback::New() { return new VtkPickCallback(); } -void VtkPickCallback::Execute( vtkObject *caller, unsigned long vtkNotUsed(eventId), void *vtkNotUsed(callData) ) +void VtkPickCallback::Execute( vtkObject* caller, unsigned long vtkNotUsed( + eventId), void* vtkNotUsed(callData) ) { vtkCellPicker* picker = static_cast<vtkCellPicker*>(caller); if (picker->GetCellId() < 0) @@ -32,11 +32,12 @@ void VtkPickCallback::Execute( vtkObject *caller, unsigned long vtkNotUsed(event double* pos = picker->GetPickPosition(); std::cout << "Picked cell id is: " << picker->GetCellId() << std::endl; - std::cout << "Picked position is: " << pos[0] << " " << pos[1] << " " << pos[2] << std::endl; + std::cout << "Picked position is: " << pos[0] << " " << pos[1] << " " << pos[2] << + std::endl; } } VtkPickCallback::VtkPickCallback() -: QObject() + : QObject() { } diff --git a/VtkAct/VtkPickCallback.h b/VtkAct/VtkPickCallback.h index 907b9fe703366ba7bb35562c83ea193adf184606..d71792df23dca94fe733b3ed4945bfea0a37d1da 100644 --- a/VtkAct/VtkPickCallback.h +++ b/VtkAct/VtkPickCallback.h @@ -1,10 +1,9 @@ /** * \file VtkPickCallback.h * 21/6/2010 LB Initial implementation - * + * */ - #ifndef VTKPICKCALLBACK_H #define VTKPICKCALLBACK_H @@ -25,7 +24,7 @@ class VtkPickCallback : public QObject, public vtkCommand public: static VtkPickCallback* New(); - void Execute(vtkObject *caller, unsigned long eventId, void *callData); + void Execute(vtkObject* caller, unsigned long eventId, void* callData); protected: VtkPickCallback(); @@ -33,7 +32,6 @@ protected: signals: /// Is emitted when an vtkActor was picked. void actorPicked (vtkProp3D* actor); - }; #endif // VTKPICKCALLBACK_H diff --git a/VtkVis/OGSFilterInfo.h b/VtkVis/OGSFilterInfo.h index 70b87f881c3d7c4e0cd25d7fd99c0748c2873da8..d4cfe368ee6340d736cf755eb4d18e76a9d543b7 100644 --- a/VtkVis/OGSFilterInfo.h +++ b/VtkVis/OGSFilterInfo.h @@ -7,8 +7,8 @@ #ifndef OGSFILTERINFO_H #define OGSFILTERINFO_H -#include <string> #include "VtkOGSFilter.h" +#include <string> ///Stores information about filters in VtkOGSFilter for access-routines from the GUI. class OGSFilterInfo @@ -18,17 +18,18 @@ public: { POLYDATA = 0, UNSTRUCTUREDGRID = 1, - IMAGEDATA = 3 + IMAGEDATA = 3 }; - OGSFilterInfo(std::string t, VtkOGSFilter::OGSVisFilter f, VtkTargetObject v) : _text(t), _filter(f), _target(v) {} - ~OGSFilterInfo() {}; + OGSFilterInfo(std::string t, VtkOGSFilter::OGSVisFilter f, + VtkTargetObject v) : _text(t), _filter(f), _target(v) {} + ~OGSFilterInfo() {} const std::string& text() const { return _text; } const VtkOGSFilter::OGSVisFilter& filter() const { return _filter; } const VtkTargetObject& target() const { return _target; } private: - std::string _text; + std::string _text; VtkOGSFilter::OGSVisFilter _filter; VtkTargetObject _target; }; diff --git a/VtkVis/QVtkDataSetMapper.cpp b/VtkVis/QVtkDataSetMapper.cpp index 4fb1c72f1237c370066fc974c3a20dab0d46d7f5..ec6d0b6396f0bd616ee5297e70b8095b8875cdd1 100644 --- a/VtkVis/QVtkDataSetMapper.cpp +++ b/VtkVis/QVtkDataSetMapper.cpp @@ -1,7 +1,7 @@ /** * \file QVtkDataSetMapper.cpp * 12/11/2010 LB Initial implementation - * + * * Implementation of QVtkDataSetMapper class */ @@ -13,7 +13,7 @@ vtkStandardNewMacro(QVtkDataSetMapper); QVtkDataSetMapper::QVtkDataSetMapper() -: QObject(NULL) + : QObject(NULL) { } diff --git a/VtkVis/QVtkDataSetMapper.h b/VtkVis/QVtkDataSetMapper.h index 90ebed76e0dd32b1fe4691783c0e5a9c70d31064..2138b3cecefd977b6a57bba21dbf4a4a98cb79b6 100644 --- a/VtkVis/QVtkDataSetMapper.h +++ b/VtkVis/QVtkDataSetMapper.h @@ -13,7 +13,7 @@ class QVtkDataSetMapper : public QObject, public vtkDataSetMapper { Q_OBJECT - + public: /// @brief Create new objects with New() because of VTKs reference counting. static QVtkDataSetMapper* New(); @@ -36,8 +36,8 @@ protected: virtual ~QVtkDataSetMapper(); private: - QVtkDataSetMapper(const QVtkDataSetMapper&); // Not implemented. - void operator=(const QVtkDataSetMapper&); // Not implemented + QVtkDataSetMapper(const QVtkDataSetMapper&); // Not implemented. + void operator=(const QVtkDataSetMapper&); // Not implemented }; #endif // QVTKDATASETMAPPER_H diff --git a/VtkVis/VisPrefsDialog.cpp b/VtkVis/VisPrefsDialog.cpp index e62c23d7b7c50bfe6bbb5594ae12b5f76ef65e8c..3bfcd6210f14a2e7aaf938bb83e140fa687ca036 100644 --- a/VtkVis/VisPrefsDialog.cpp +++ b/VtkVis/VisPrefsDialog.cpp @@ -3,18 +3,21 @@ * 14/06/2010 KR Initial implementation */ -#include <QSettings> +#include "VisPrefsDialog.h" #include <QDoubleValidator> #include <QLineEdit> +#include <QSettings> #include <QVariant> -#include "VisPrefsDialog.h" -#include "VtkVisPipeline.h" #include "VisualizationWidget.h" +#include "VtkVisPipeline.h" /// Constructor -VisPrefsDialog::VisPrefsDialog(VtkVisPipeline* pipeline, VisualizationWidget* widget, QDialog* parent) : - QDialog(parent), _vtkVisPipeline(pipeline), _visWidget(widget), _above(0,0,2000000), _below(0,0,-2000000) +VisPrefsDialog::VisPrefsDialog(VtkVisPipeline* pipeline, + VisualizationWidget* widget, + QDialog* parent) : + QDialog(parent), _vtkVisPipeline(pipeline), _visWidget(widget), + _above(0,0,2000000), _below(0,0,-2000000) { setupUi(this); if (_vtkVisPipeline->getLight(_above)) diff --git a/VtkVis/VisPrefsDialog.h b/VtkVis/VisPrefsDialog.h index 3f82be69710094c40a79d44d66c446877b24e2ca..a3b979d0e292875e5afc03c4b333ee8173fcc971 100644 --- a/VtkVis/VisPrefsDialog.h +++ b/VtkVis/VisPrefsDialog.h @@ -6,9 +6,9 @@ #ifndef VISPREFSDIALOG_H #define VISPREFSDIALOG_H -#include <QDialog> -#include "ui_VisPrefs.h" #include "Point.h" +#include "ui_VisPrefs.h" +#include <QDialog> class VtkVisPipeline; class VisualizationWidget; @@ -21,7 +21,9 @@ class VisPrefsDialog : public QDialog, private Ui_VisPrefsDialog Q_OBJECT public: - VisPrefsDialog(VtkVisPipeline* pipeline, VisualizationWidget* widget, QDialog* parent = NULL); + VisPrefsDialog(VtkVisPipeline* pipeline, + VisualizationWidget* widget, + QDialog* parent = NULL); protected slots: /// Sets the background colour. @@ -44,7 +46,6 @@ private: VisualizationWidget* _visWidget; GEOLIB::Point _above; GEOLIB::Point _below; - }; #endif //VISPREFSDIALOG_H diff --git a/VtkVis/VisualizationWidget.cpp b/VtkVis/VisualizationWidget.cpp index e6221d0f3a59b447c35172b8f023c43819bdd825..39c95d3cac8ac12b224babc19c607c51a40dcddd 100644 --- a/VtkVis/VisualizationWidget.cpp +++ b/VtkVis/VisualizationWidget.cpp @@ -6,47 +6,47 @@ */ // ** INCLUDES ** -#include "VisualizationWidget.h" #include "Point.h" -#include "VtkPickCallback.h" +#include "VisualizationWidget.h" #include "VtkCustomInteractorStyle.h" +#include "VtkPickCallback.h" #include "VtkTrackedCamera.h" +#include <vtkCamera.h> +#include <vtkCellPicker.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> -#include <vtkCamera.h> #include <vtkSmartPointer.h> -#include <vtkCellPicker.h> -#include <vtkInteractorStyleSwitch.h> +#include <vtkAxesActor.h> +#include <vtkCommand.h> #include <vtkInteractorStyleRubberBandZoom.h> +#include <vtkInteractorStyleSwitch.h> #include <vtkMath.h> -#include <vtkCommand.h> -#include <vtkAxesActor.h> #include <vtkOrientationMarkerWidget.h> #include <vtkPNGWriter.h> -#include <vtkWindowToImageFilter.h> #include <vtkSmartPointer.h> +#include <vtkWindowToImageFilter.h> -#include <QSettings> +#include <QCursor> +#include <QDir> #include <QFileDialog> -#include <QLineEdit> -#include <QString> #include <QInputDialog> +#include <QLineEdit> #include <QSettings> -#include <QDir> -#include <QCursor> +#include <QSettings> +#include <QString> #ifdef OGS_USE_VRPN #include "QSpaceNavigatorClient.h" -#include "VtkTrackedCamera.h" -#include <vtkEventQtSlotConnect.h> #include "QVrpnArtTrackingClient.h" +#include "VtkTrackedCamera.h" #include <QTimer> +#include <vtkEventQtSlotConnect.h> #endif // OGS_USE_VRPN VisualizationWidget::VisualizationWidget( QWidget* parent /*= 0*/ ) -: QWidget(parent) + : QWidget(parent) { this->setupUi(this); @@ -66,14 +66,14 @@ VisualizationWidget::VisualizationWidget( QWidget* parent /*= 0*/ ) _vtkRender = vtkRenderer::New(); renderWindow->AddRenderer(_vtkRender); _interactorStyle->SetDefaultRenderer(_vtkRender); -#endif // OGS_VRED_PLUGIN +#endif // OGS_VRED_PLUGIN QSettings settings("UFZ", "OpenGeoSys-5"); #ifdef OGS_USE_VRPN VtkTrackedCamera* cam = new VtkTrackedCamera(this); _vtkRender->SetActiveCamera(cam); - connect( cam, SIGNAL(viewUpdated()), this, SLOT(updateView()) ); + connect( cam, SIGNAL(viewUpdated()), this, SLOT(updateView()) ); //QSpaceNavigatorClient* spacenav = QSpaceNavigatorClient::Instance(); //spacenav->init("spacenav@localhost", 1000 / 15, SpaceNavigatorClient::Z); @@ -89,19 +89,19 @@ VisualizationWidget::VisualizationWidget( QWidget* parent /*= 0*/ ) QString deviceName = settings.value("Tracking/artDeviceName").toString(); QString deviceNameAt = settings.value("Tracking/artDeviceNameAt").toString(); art->StartTracking(QString(deviceName + "@" + deviceNameAt).toStdString().c_str(), - settings.value("Tracking/artUpdateInterval").toInt()); + settings.value("Tracking/artUpdateInterval").toInt()); } else art->StartTracking("DTrack@141.65.34.36"); connect( art, SIGNAL(positionUpdated(double, double, double)), - cam, SLOT(setTrackingData(double, double, double)) ); + cam, SLOT(setTrackingData(double, double, double)) ); // Connect the vtk event to the qt slot _qtConnect = vtkEventQtSlotConnect::New(); _qtConnect->Connect(vtkWidget->GetRenderWindow()->GetInteractor(), - vtkCommand::EndInteractionEvent, - cam, - SLOT(updatedFromOutside())); + vtkCommand::EndInteractionEvent, + cam, + SLOT(updatedFromOutside())); #endif // OGS_USE_VRPN @@ -114,14 +114,14 @@ VisualizationWidget::VisualizationWidget( QWidget* parent /*= 0*/ ) //else // cam->SetEyeAngle(2.0); /* - if (!stereoToolButton->isChecked()) - { - eyeAngleLabel->setEnabled(false); - eyeAngleSlider->setEnabled(false); - } -*/ + if (!stereoToolButton->isChecked()) + { + eyeAngleLabel->setEnabled(false); + eyeAngleSlider->setEnabled(false); + } + */ //eyeAngleSlider->setValue((int)(_vtkRender->GetActiveCamera()->GetEyeAngle() * 10)); - + // Create an orientation marker using vtkAxesActor vtkSmartPointer<vtkAxesActor> axesActor = vtkSmartPointer<vtkAxesActor>::New(); vtkOrientationMarkerWidget* markerWidget = vtkOrientationMarkerWidget::New(); @@ -135,7 +135,7 @@ VisualizationWidget::VisualizationWidget( QWidget* parent /*= 0*/ ) // Set alternate cursor shapes connect(_interactorStyle, SIGNAL(cursorChanged(Qt::CursorShape)), - this, SLOT(setCursorShape(Qt::CursorShape))); + this, SLOT(setCursorShape(Qt::CursorShape))); } VisualizationWidget::~VisualizationWidget() @@ -147,9 +147,9 @@ VisualizationWidget::~VisualizationWidget() _interactorStyle->deleteLater(); _vtkPickCallback->deleteLater(); - #ifdef OGS_USE_VRPN +#ifdef OGS_USE_VRPN _qtConnect->Delete(); - #endif // OGS_USE_VRPN +#endif // OGS_USE_VRPN } VtkCustomInteractorStyle* VisualizationWidget::interactorStyle() const { @@ -160,7 +160,7 @@ VtkPickCallback* VisualizationWidget::vtkPickCallback() const return _vtkPickCallback; } void VisualizationWidget::updateView() -{ +{ vtkWidget->GetRenderWindow()->Render(); } @@ -187,34 +187,30 @@ void VisualizationWidget::updateViewOnLoad() void VisualizationWidget::on_stereoToolButton_toggled( bool checked ) { if (checked) - { vtkWidget->GetRenderWindow()->StereoRenderOn(); //eyeAngleLabel->setEnabled(true); //eyeAngleSlider->setEnabled(true); - } else - { vtkWidget->GetRenderWindow()->StereoRenderOff(); //eyeAngleLabel->setEnabled(false); //eyeAngleSlider->setEnabled(false); - } this->updateView(); } /* -void VisualizationWidget::on_eyeAngleSlider_valueChanged( int value ) -{ - Q_UNUSED(value); - //_vtkRender->GetActiveCamera()->SetEyeAngle(value / 10.0); - //updateView(); -} -*/ + void VisualizationWidget::on_eyeAngleSlider_valueChanged( int value ) + { + Q_UNUSED(value); + //_vtkRender->GetActiveCamera()->SetEyeAngle(value / 10.0); + //updateView(); + } + */ void VisualizationWidget::on_zoomToolButton_toggled( bool checked ) { if (checked) { vtkSmartPointer<vtkInteractorStyleRubberBandZoom> interactorStyle = - vtkSmartPointer<vtkInteractorStyleRubberBandZoom>::New(); + vtkSmartPointer<vtkInteractorStyleRubberBandZoom>::New(); vtkWidget->GetRenderWindow()->GetInteractor()->SetInteractorStyle(interactorStyle); QCursor cursor; cursor.setShape(Qt::CrossCursor); @@ -249,13 +245,16 @@ void VisualizationWidget::on_screenshotPushButton_pressed() { QSettings settings("UFZ", "OpenGeoSys-5"); QString filename = QFileDialog::getSaveFileName(this, tr("Save screenshot"), - settings.value("lastScreenshotDir").toString(), "PNG file (*.png)"); + settings.value( + "lastScreenshotDir").toString(), + "PNG file (*.png)"); if (filename.count() > 4) { bool ok; int magnification = QInputDialog::getInt(this, tr("Screenshot magnification"), - tr("Enter a magnification factor for the resulting image."), - 2, 1, 10, 1, &ok); + tr( + "Enter a magnification factor for the resulting image."), + 2, 1, 10, 1, &ok); if (ok) { QDir dir(filename); @@ -268,7 +267,7 @@ void VisualizationWidget::on_screenshotPushButton_pressed() void VisualizationWidget::screenshot(QString filename, int magnification) { vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter = - vtkSmartPointer<vtkWindowToImageFilter>::New(); + vtkSmartPointer<vtkWindowToImageFilter>::New(); windowToImageFilter->SetInput(vtkWidget->GetRenderWindow()); // Set the resolution of the output image // magnification times the current resolution of vtk render window diff --git a/VtkVis/VisualizationWidget.h b/VtkVis/VisualizationWidget.h index fe9195b58681ebfb42aedb3631b45cb0c010d852..3495cc9b33b85e58143bf445fdb1abc65a489e0b 100644 --- a/VtkVis/VisualizationWidget.h +++ b/VtkVis/VisualizationWidget.h @@ -1,10 +1,9 @@ - /** +/** * \file VisualizationWidget.h * 3/11/2009 LB Initial implementation * */ - #ifndef VISUALIZATIONWIDGET_H #define VISUALIZATIONWIDGET_H @@ -71,10 +70,10 @@ protected slots: /// @brief Toggles rectangular zooming mode. void on_zoomToolButton_toggled(bool checked); - + /// @brief Resets the camera to view the entire scene. void on_showAllPushButton_pressed(); - + /// @brief Toggles the display of bounding boxes around. void on_highlightToolButton_toggled(bool checked); @@ -89,9 +88,9 @@ private: VtkCustomInteractorStyle* _interactorStyle; VtkPickCallback* _vtkPickCallback; bool _isShowAllOnLoad; - #ifdef OGS_USE_VRPN +#ifdef OGS_USE_VRPN vtkEventQtSlotConnect* _qtConnect; - #endif // OGS_USE_VRPN +#endif // OGS_USE_VRPN }; #endif // VISUALIZATIONWIDGET_H diff --git a/VtkVis/VtkAddFilterDialog.cpp b/VtkVis/VtkAddFilterDialog.cpp index 4337b341ed2afff484945a7bc1ce0022ba028a6a..6eddb7665822a0059faa8398fd03d565e37cb904 100644 --- a/VtkVis/VtkAddFilterDialog.cpp +++ b/VtkVis/VtkAddFilterDialog.cpp @@ -1,4 +1,4 @@ - /** +/** * \file VtkAddFilterDialog.cpp * 23/2/2010 LB Initial implementation * @@ -7,12 +7,12 @@ // ** INCLUDES ** #include "VtkAddFilterDialog.h" +#include "VtkCompositeFilter.h" +#include "VtkFilterFactory.h" +#include "VtkVisImageItem.h" #include "VtkVisPipeline.h" #include "VtkVisPipelineItem.h" -#include "VtkVisImageItem.h" #include "VtkVisPointSetItem.h" -#include "VtkCompositeFilter.h" -#include "VtkFilterFactory.h" #include <vtkContourFilter.h> #include <vtkOutlineFilter.h> @@ -20,35 +20,36 @@ #include <QModelIndex> - -VtkAddFilterDialog::VtkAddFilterDialog( VtkVisPipeline* pipeline, QModelIndex parentIndex, QDialog* parent /*= 0*/ ) -: QDialog(parent), _pipeline(pipeline), _parentIndex(parentIndex) +VtkAddFilterDialog::VtkAddFilterDialog( VtkVisPipeline* pipeline, + QModelIndex parentIndex, + QDialog* parent /*= 0*/ ) + : QDialog(parent), _pipeline(pipeline), _parentIndex(parentIndex) { setupUi(this); filterListWidget->setSelectionMode(QAbstractItemView::SingleSelection); - VtkVisPipelineItem* parentItem = static_cast<VtkVisPipelineItem*>(_pipeline->getItem(parentIndex)); + VtkVisPipelineItem* parentItem = + static_cast<VtkVisPipelineItem*>(_pipeline->getItem(parentIndex)); vtkDataObject* parentDataObject = parentItem->algorithm()->GetOutputDataObject(0); int parentDataObjectType = parentDataObject->GetDataObjectType(); - QVector<VtkFilterInfo> filterList = VtkFilterFactory::GetFilterList(); foreach(VtkFilterInfo filter, filterList) { // Check for suitable filters (see vtkDataSet inheritance diagram) int inputType = filter.inputDataObjectType; if ((inputType == parentDataObjectType) || - (inputType == VTK_POINT_SET && parentDataObjectType != VTK_IMAGE_DATA) || - (inputType == VTK_IMAGE_DATA && - (parentDataObjectType == VTK_STRUCTURED_POINTS || parentDataObjectType == VTK_UNIFORM_GRID))) + (inputType == VTK_POINT_SET && parentDataObjectType != VTK_IMAGE_DATA) || + (inputType == VTK_IMAGE_DATA && + (parentDataObjectType == VTK_STRUCTURED_POINTS || parentDataObjectType == + VTK_UNIFORM_GRID))) new QListWidgetItem(filter.readableName, filterListWidget); } // On double clicking an item the dialog gets accepted connect(filterListWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)), - this->buttonBox,SIGNAL(accepted())); - + this->buttonBox,SIGNAL(accepted())); } void VtkAddFilterDialog::on_buttonBox_accepted() @@ -63,7 +64,8 @@ void VtkAddFilterDialog::on_buttonBox_accepted() break; } } - VtkVisPipelineItem* parentItem = static_cast<VtkVisPipelineItem*>(_pipeline->getItem(_parentIndex)); + VtkVisPipelineItem* parentItem = + static_cast<VtkVisPipelineItem*>(_pipeline->getItem(_parentIndex)); QList<QVariant> itemData; itemData << filterListWidget->currentItem()->text() << true; @@ -71,7 +73,8 @@ void VtkAddFilterDialog::on_buttonBox_accepted() if (dynamic_cast<VtkVisImageItem*>(parentItem)) filter = VtkFilterFactory::CreateCompositeFilter(filterName, parentItem->algorithm()); else - filter = VtkFilterFactory::CreateCompositeFilter(filterName, parentItem->transformFilter()); + filter = VtkFilterFactory::CreateCompositeFilter(filterName, + parentItem->transformFilter()); VtkVisPipelineItem* item; if (filter) @@ -88,7 +91,8 @@ void VtkAddFilterDialog::on_buttonBox_accepted() item = new VtkVisPointSetItem(algorithm, parentItem, itemData); else { - std::cout << "Error: VtkFilterFavctory cannot create " << filterName.toStdString() << std::endl; + std::cout << "Error: VtkFilterFavctory cannot create " << + filterName.toStdString() << std::endl; return; } } @@ -103,9 +107,9 @@ void VtkAddFilterDialog::on_filterListWidget_currentRowChanged( int currentRow ) { QString desc = filter.description; desc = desc + QString("\n\nThis filter outputs ") + - filter.OutputDataObjectTypeAsString() + - QString("\n\nFilter class name: ") + - filter.name; + filter.OutputDataObjectTypeAsString() + + QString("\n\nFilter class name: ") + + filter.name; this->filterDescTextEdit->setText(desc); continue; diff --git a/VtkVis/VtkAddFilterDialog.h b/VtkVis/VtkAddFilterDialog.h index 557d5981a65d6ba41bd118696852745c9304f724..3e8d9d73bf2eb39916654673942e21d80824382c 100644 --- a/VtkVis/VtkAddFilterDialog.h +++ b/VtkVis/VtkAddFilterDialog.h @@ -4,7 +4,6 @@ * */ - #ifndef VTKADDFILTERDIALOG_H #define VTKADDFILTERDIALOG_H @@ -15,7 +14,6 @@ class VtkVisPipeline; class QModelIndex; class QRadioButton; - /** * \brief Dialog for selecting a filter to be applied to a VtkPipelineItem. * The dialog lets you select filters defined in VtkOGSFilter that have been registered as OGSFilterInfo - objects. @@ -39,5 +37,4 @@ private: QModelIndex _parentIndex; }; - #endif // VTKADDFILTERDIALOG_H diff --git a/VtkVis/VtkAlgorithmProperties.h b/VtkVis/VtkAlgorithmProperties.h index b22e30cdba987d915a024d35198306d5be452dd1..0536f4f6c99c33f10e827b719e89828d54a54642 100644 --- a/VtkVis/VtkAlgorithmProperties.h +++ b/VtkVis/VtkAlgorithmProperties.h @@ -4,112 +4,123 @@ * */ - #ifndef VTKALGORITHMPROPERTIES_H #define VTKALGORITHMPROPERTIES_H // ** INCLUDES ** +#include <QList> +#include <QMap> #include <QObject> -#include <vtkProperty.h> -#include <vtkTexture.h> #include <QString> -#include <QMap> #include <QVariant> -#include <QList> +#include <vtkProperty.h> +#include <vtkTexture.h> #include "VtkColorLookupTable.h" #define ogsUserPropertyMacro(name,type) \ -virtual void Set##name (type _arg) \ -{ \ - vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting " #name " to " << _arg); \ - if (this->name != _arg) \ + virtual void Set ## name (type _arg) \ { \ - this->name = _arg; \ - this->Modified(); \ - (*(this->_algorithmUserProperties))[QString(#name)] = QVariant(_arg); \ + vtkDebugMacro( \ + << this->GetClassName() << " (" << this << "): setting " # name " to " << \ + _arg); \ + if (this->name != _arg) \ + { \ + this->name = _arg; \ + this->Modified(); \ + (*(this->_algorithmUserProperties))[QString(# name)] = QVariant(_arg); \ + } \ } \ -} \ \ -type name; + type name; // End of ogsUserPropertyMacro #define ogsUserVec2PropertyMacro(name,type) \ -virtual void Set##name (type _arg1, type _arg2) \ -{ \ - vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting " << #name " to (" << _arg1 << "," << _arg2 << ")"); \ - if ((this->name[0] != _arg1)||(this->name[1] != _arg2)) \ + virtual void Set ## name (type _arg1, type _arg2) \ { \ - this->name[0] = _arg1; \ - this->name[1] = _arg2; \ - this->Modified(); \ - QList<QVariant> list; \ - list.push_back(QVariant(_arg1)); \ - list.push_back(QVariant(_arg2)); \ - (*(this->_algorithmUserVectorProperties))[QString(#name)] = list; \ + vtkDebugMacro( \ + << this->GetClassName() << " (" << this << "): setting " << \ + # name " to (" << \ + _arg1 << "," << _arg2 << ")"); \ + if ((this->name[0] != _arg1) || (this->name[1] != _arg2)) \ + { \ + this->name[0] = _arg1; \ + this->name[1] = _arg2; \ + this->Modified(); \ + QList<QVariant> list; \ + list.push_back(QVariant(_arg1)); \ + list.push_back(QVariant(_arg2)); \ + (*(this->_algorithmUserVectorProperties))[QString(# name)] = list; \ + } \ } \ -} \ \ -virtual void Set##name (type _arg[2]) \ -{ \ - this->Set##name (_arg[0], _arg[1]);\ -} \ + virtual void Set ## name (type _arg[2]) \ + { \ + this->Set ## name (_arg[0], _arg[1]); \ + } \ \ -type name[2]; + type name[2]; // End of ogsUserVec2PropertyMacro #define ogsUserVec3PropertyMacro(name,type) \ -virtual void Set##name (type _arg1, type _arg2, type _arg3) \ -{ \ - vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting " << #name " to (" << _arg1 << "," << _arg2 << "," << _arg3 << ")"); \ - if ((this->name[0] != _arg1)||(this->name[1] != _arg2)||(this->name[2] != _arg3)) \ + virtual void Set ## name (type _arg1, type _arg2, type _arg3) \ { \ - this->name[0] = _arg1; \ - this->name[1] = _arg2; \ - this->name[2] = _arg3; \ - this->Modified(); \ - QList<QVariant> list; \ - list.push_back(QVariant(_arg1)); \ - list.push_back(QVariant(_arg2)); \ - list.push_back(QVariant(_arg3)); \ - (*(this->_algorithmUserVectorProperties))[QString(#name)] = list; \ + vtkDebugMacro( \ + << this->GetClassName() << " (" << this << "): setting " << \ + # name " to (" << \ + _arg1 << "," << _arg2 << "," << _arg3 << ")"); \ + if ((this->name[0] != _arg1) || (this->name[1] != _arg2) || (this->name[2] != _arg3)) \ + { \ + this->name[0] = _arg1; \ + this->name[1] = _arg2; \ + this->name[2] = _arg3; \ + this->Modified(); \ + QList<QVariant> list; \ + list.push_back(QVariant(_arg1)); \ + list.push_back(QVariant(_arg2)); \ + list.push_back(QVariant(_arg3)); \ + (*(this->_algorithmUserVectorProperties))[QString(# name)] = list; \ + } \ } \ -} \ \ -virtual void Set##name (type _arg[3]) \ -{ \ - this->Set##name (_arg[0], _arg[1], _arg[2]);\ -} \ + virtual void Set ## name (type _arg[3]) \ + { \ + this->Set ## name (_arg[0], _arg[1], _arg[2]); \ + } \ \ -type name[3]; + type name[3]; // End of ogsUserVec3PropertyMacro #define ogsUserVec4PropertyMacro(name,type) \ -virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4) \ -{ \ - vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting " << #name " to (" << _arg1 << "," << _arg2 << "," << _arg3 << "," << _arg4 << ")"); \ - if ((this->name[0] != _arg1)||(this->name[1] != _arg2)||(this->name[2] != _arg3)||(this->name[3] != _arg4)) \ + virtual void Set ## name (type _arg1, type _arg2, type _arg3, type _arg4) \ { \ - this->name[0] = _arg1; \ - this->name[1] = _arg2; \ - this->name[2] = _arg3; \ - this->name[3] = _arg4; \ - this->Modified(); \ - QList<QVariant> list; \ - list.push_back(QVariant(_arg1)); \ - list.push_back(QVariant(_arg2)); \ - list.push_back(QVariant(_arg3)); \ - list.push_back(QVariant(_arg4)); \ - (*(this->_algorithmUserVectorProperties))[QString(#name)] = list; \ + vtkDebugMacro( \ + << this->GetClassName() << " (" << this << "): setting " << \ + # name " to (" << \ + _arg1 << "," << _arg2 << "," << _arg3 << "," << _arg4 << ")"); \ + if ((this->name[0] != _arg1) || (this->name[1] != _arg2) || \ + (this->name[2] != _arg3) || (this->name[3] != _arg4)) \ + { \ + this->name[0] = _arg1; \ + this->name[1] = _arg2; \ + this->name[2] = _arg3; \ + this->name[3] = _arg4; \ + this->Modified(); \ + QList<QVariant> list; \ + list.push_back(QVariant(_arg1)); \ + list.push_back(QVariant(_arg2)); \ + list.push_back(QVariant(_arg3)); \ + list.push_back(QVariant(_arg4)); \ + (*(this->_algorithmUserVectorProperties))[QString(# name)] = list; \ + } \ } \ -} \ \ -virtual void Set##name (type _arg[4]) \ -{ \ - this->Set##name (_arg[0], _arg[1], _arg[2], _arg[3]);\ -} \ + virtual void Set ## name (type _arg[4]) \ + { \ + this->Set ## name (_arg[0], _arg[1], _arg[2], _arg[3]); \ + } \ \ -type name[4]; + type name[4]; // End of ogsUserVec4PropertyMacro /** @@ -121,10 +132,10 @@ class VtkAlgorithmProperties : public QObject public: /// Constructor (sets default values) - VtkAlgorithmProperties(QObject* parent = NULL) + VtkAlgorithmProperties(QObject* parent = NULL) : QObject(parent) - { - _property = vtkProperty::New(); + { + _property = vtkProperty::New(); _texture = NULL; _scalarVisibility = true; _algorithmUserProperties = new QMap<QString, QVariant>; @@ -132,53 +143,54 @@ public: _activeAttributeName = ""; } - virtual ~VtkAlgorithmProperties() + virtual ~VtkAlgorithmProperties() { _property->Delete(); if (_texture != NULL) _texture->Delete(); - - for (std::map<QString, vtkLookupTable*>::iterator it = _lut.begin(); it != _lut.end(); ++it) + + for (std::map<QString, vtkLookupTable*>::iterator it = _lut.begin(); it != _lut.end(); + ++it) it->second->Delete(); delete _algorithmUserProperties; delete _algorithmUserVectorProperties; - }; - + } + /// @brief Returns the vtk properties - vtkProperty* GetProperties() const { return _property; }; - + vtkProperty* GetProperties() const { return _property; } + /// @brief Returns a texture (if one has been assigned). - vtkTexture* GetTexture() { return _texture; }; + vtkTexture* GetTexture() { return _texture; } /// @brief Sets a texture for the VtkVisPipelineItem. - void SetTexture(vtkTexture* t) { _texture = t; }; + void SetTexture(vtkTexture* t) { _texture = t; } /// @brief Returns the colour lookup table (if one has been assigned). - vtkLookupTable* GetLookupTable(const QString& array_name) - { + vtkLookupTable* GetLookupTable(const QString& array_name) + { std::map<QString, vtkLookupTable*>::iterator it = _lut.find(array_name); if (it != _lut.end()) return it->second; return NULL; - }; + } /// @brief Sets a colour lookup table for the given scalar array of the VtkVisPipelineItem. - void SetLookUpTable(const QString array_name, vtkLookupTable* lut) + void SetLookUpTable(const QString array_name, vtkLookupTable* lut) { - if (array_name.length()>0) + if (array_name.length() > 0) { std::map<QString, vtkLookupTable*>::iterator it = _lut.find(array_name); if (it != _lut.end()) it->second->Delete(); - _lut.insert( std::pair<QString, vtkLookupTable*>(array_name, lut) ); + _lut.insert( std::pair<QString, vtkLookupTable*>(array_name, lut) ); } - }; - + } + /// Loads a predefined color lookup table from a file for the specified scalar array. void SetLookUpTable(const QString &array_name, const std::string &filename) - { + { VtkColorLookupTable* colorLookupTable = VtkColorLookupTable::New(); colorLookupTable->readFromFile(filename); colorLookupTable->setInterpolationType(VtkColorLookupTable::NONE); colorLookupTable->Build(); SetLookUpTable(array_name, colorLookupTable); - }; + } /// @brief Returns the scalar visibility. bool GetScalarVisibility() const { return _scalarVisibility; } @@ -188,12 +200,12 @@ public: _scalarVisibility = on; emit ScalarVisibilityChanged(on); } - + /// @brief Returns the name. This is set to the file path if it is a source algorithm. QString GetName() const { return _name; } /// @brief Sets the name. void SetName(QString name) { _name = name; } - + /// @brief Returns a map of user properties. QMap<QString, QVariant>* GetAlgorithmUserProperties() const { @@ -243,8 +255,8 @@ public: } /// @brief Returns the desired active attribute. - QString GetActiveAttribute() const { return _activeAttributeName; }; - + QString GetActiveAttribute() const { return _activeAttributeName; } + protected: // Properties set on vtkActor @@ -254,17 +266,16 @@ protected: // Properties set on vtkMapper bool _scalarVisibility; std::map<QString, vtkLookupTable*> _lut; - + // Properties used in the GUI QString _name; QString _activeAttributeName; - + QMap<QString, QVariant>* _algorithmUserProperties; QMap<QString, QList<QVariant> >* _algorithmUserVectorProperties; signals: void ScalarVisibilityChanged(bool on); - }; #endif // VTKALGORITHMPROPERTIES_H diff --git a/VtkVis/VtkAlgorithmPropertyCheckbox.cpp b/VtkVis/VtkAlgorithmPropertyCheckbox.cpp index f4087f271538f4c19dfe6f597806e10a7267c447..98f9c7169de7ca666f366da0c1f89fb985a955d7 100644 --- a/VtkVis/VtkAlgorithmPropertyCheckbox.cpp +++ b/VtkVis/VtkAlgorithmPropertyCheckbox.cpp @@ -1,7 +1,7 @@ /** * \file VtkAlgorithmPropertyCheckbox.cpp * 20/10/2010 LB Initial implementation - * + * * Implementation of VtkAlgorithmPropertyCheckbox class */ @@ -11,8 +11,9 @@ #include "VtkAlgorithmProperties.h" VtkAlgorithmPropertyCheckbox::VtkAlgorithmPropertyCheckbox(const bool value, - const QString& name, VtkAlgorithmProperties* algProps, - QWidget* parent /*= 0*/ ) + const QString& name, + VtkAlgorithmProperties* algProps, + QWidget* parent /*= 0*/ ) : QCheckBox(parent), _name(name), _algProps(algProps) { this->setChecked(value); @@ -21,7 +22,6 @@ VtkAlgorithmPropertyCheckbox::VtkAlgorithmPropertyCheckbox(const bool value, VtkAlgorithmPropertyCheckbox::~VtkAlgorithmPropertyCheckbox() { - } void VtkAlgorithmPropertyCheckbox::setNewValue( int state ) diff --git a/VtkVis/VtkAlgorithmPropertyCheckbox.h b/VtkVis/VtkAlgorithmPropertyCheckbox.h index af45da1822edf126be1cee10bbeb43f66b545951..d6da25deaa9b74852e540a68a103e62512fc792c 100644 --- a/VtkVis/VtkAlgorithmPropertyCheckbox.h +++ b/VtkVis/VtkAlgorithmPropertyCheckbox.h @@ -23,8 +23,8 @@ public: /// @param algProps The VtkAlgorithmProperties object. /// @param parent The parent widget. VtkAlgorithmPropertyCheckbox(const bool value, const QString& name, - VtkAlgorithmProperties* algProps, QWidget* parent = 0); - + VtkAlgorithmProperties* algProps, QWidget* parent = 0); + /// @brief Destructor. virtual ~VtkAlgorithmPropertyCheckbox(); diff --git a/VtkVis/VtkAlgorithmPropertyLineEdit.cpp b/VtkVis/VtkAlgorithmPropertyLineEdit.cpp index 9273e24435faa52fe789ce5c500948490aa9df2f..3403ed9fb546708dff378eee36893595ff5509d5 100644 --- a/VtkVis/VtkAlgorithmPropertyLineEdit.cpp +++ b/VtkVis/VtkAlgorithmPropertyLineEdit.cpp @@ -1,7 +1,7 @@ /** * \file VtkAlgorithmPropertyLineEdit.cpp * 18/10/2010 LB Initial implementation - * + * * Implementation of VtkAlgorithmPropertyLineEdit class */ @@ -13,9 +13,12 @@ #include <QDoubleValidator> #include <QIntValidator> -VtkAlgorithmPropertyLineEdit::VtkAlgorithmPropertyLineEdit(const QString& contents, const QString& name, - QVariant::Type type, VtkAlgorithmProperties* algProps, QWidget* parent /*= 0*/) -: QLineEdit(contents, parent), _name(name), _algProps(algProps), _type(type) +VtkAlgorithmPropertyLineEdit::VtkAlgorithmPropertyLineEdit(const QString& contents, + const QString& name, + QVariant::Type type, + VtkAlgorithmProperties* algProps, + QWidget* parent /*= 0*/) + : QLineEdit(contents, parent), _name(name), _algProps(algProps), _type(type) { switch(_type) { @@ -25,21 +28,20 @@ VtkAlgorithmPropertyLineEdit::VtkAlgorithmPropertyLineEdit(const QString& conten case QVariant::Int: this->setValidator(new QIntValidator(this)); - + default: break; } - - connect(this, SIGNAL(editingFinished()), this, SLOT(setNewValue())); + + connect(this, SIGNAL(editingFinished()), this, SLOT(setNewValue())); } VtkAlgorithmPropertyLineEdit::~VtkAlgorithmPropertyLineEdit() { - } void VtkAlgorithmPropertyLineEdit::setNewValue() -{ +{ QVariant value(this->text()); if (value.convert(_type)) _algProps->SetUserProperty(_name, value); diff --git a/VtkVis/VtkAlgorithmPropertyLineEdit.h b/VtkVis/VtkAlgorithmPropertyLineEdit.h index 312a1df0a6383c3c16c5ced3d8b0ed613747cb5a..5f277330a9a08319e68f9d9d43cbcc4db9dd463e 100644 --- a/VtkVis/VtkAlgorithmPropertyLineEdit.h +++ b/VtkVis/VtkAlgorithmPropertyLineEdit.h @@ -17,7 +17,7 @@ class QString; class VtkAlgorithmPropertyLineEdit : public QLineEdit { Q_OBJECT - + public: /// @brief Constructor. /// @param contents The initial text. @@ -25,15 +25,18 @@ public: /// @param type The type of the property. /// @param algProps The VtkAlgorithmProperties object. /// @param parent The parent widget. - VtkAlgorithmPropertyLineEdit(const QString& contents, const QString& name, - QVariant::Type type, VtkAlgorithmProperties* algProps, QWidget* parent = 0); + VtkAlgorithmPropertyLineEdit(const QString& contents, + const QString& name, + QVariant::Type type, + VtkAlgorithmProperties* algProps, + QWidget* parent = 0); virtual ~VtkAlgorithmPropertyLineEdit(); private: const QString _name; VtkAlgorithmProperties* _algProps; QVariant::Type _type; - + private slots: /// @brief This slots is automatically called when the text changed. void setNewValue(); diff --git a/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp b/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp index 99149015b5dd9e8b8c9fbccf34137c9e46e13b0a..951f61f8aa038262a195a07b41cb6c49396fcb32 100644 --- a/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp +++ b/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp @@ -1,7 +1,7 @@ /** * \file VtkAlgorithmPropertyVectorEdit.cpp * 22/10/2010 LB Initial implementation - * + * * Implementation of VtkAlgorithmPropertyVectorEdit class */ @@ -11,13 +11,17 @@ #include "VtkAlgorithmProperties.h" #include <QDoubleValidator> -#include <QIntValidator> #include <QHBoxLayout> +#include <QIntValidator> #include <QLineEdit> #include <QSize> -VtkAlgorithmPropertyVectorEdit::VtkAlgorithmPropertyVectorEdit( const QList<QString> contents, const QString& name, QVariant::Type type, VtkAlgorithmProperties* algProps, QWidget* parent /*= 0*/ ) -: QWidget(parent), _name(name), _algProps(algProps), _type(type) +VtkAlgorithmPropertyVectorEdit::VtkAlgorithmPropertyVectorEdit( const QList<QString> contents, + const QString& name, + QVariant::Type type, + VtkAlgorithmProperties* algProps, + QWidget* parent /*= 0*/ ) + : QWidget(parent), _name(name), _algProps(algProps), _type(type) { QHBoxLayout* layout = new QHBoxLayout; layout->setSpacing(3); @@ -27,7 +31,7 @@ VtkAlgorithmPropertyVectorEdit::VtkAlgorithmPropertyVectorEdit( const QList<QStr { QLineEdit* lineEdit = new QLineEdit(content, this); layout->addWidget(lineEdit); - + switch(_type) { case QVariant::Double: @@ -50,7 +54,6 @@ VtkAlgorithmPropertyVectorEdit::VtkAlgorithmPropertyVectorEdit( const QList<QStr VtkAlgorithmPropertyVectorEdit::~VtkAlgorithmPropertyVectorEdit() { - } void VtkAlgorithmPropertyVectorEdit::setNewValue() @@ -62,7 +65,7 @@ void VtkAlgorithmPropertyVectorEdit::setNewValue() QLineEdit* lineEdit = static_cast<QLineEdit*>(layout->itemAt(i)->widget()); list.push_back(QVariant(lineEdit->text())); } - + _algProps->SetUserVectorProperty(_name, list); emit editingFinished(); diff --git a/VtkVis/VtkAlgorithmPropertyVectorEdit.h b/VtkVis/VtkAlgorithmPropertyVectorEdit.h index 236d8b9cdbe2da1e37b87db68c737acd9eefe747..6a62c83be20b93c809390429d05802c83f461e1b 100644 --- a/VtkVis/VtkAlgorithmPropertyVectorEdit.h +++ b/VtkVis/VtkAlgorithmPropertyVectorEdit.h @@ -6,9 +6,9 @@ #ifndef VTKALGORITHMPROPERTYVECTOREDIT_H #define VTKALGORITHMPROPERTYVECTOREDIT_H -#include <QWidget> #include <QList> #include <QVariant> +#include <QWidget> class VtkAlgorithmProperties; @@ -25,8 +25,11 @@ public: /// @param type The type of the property. /// @param algProps The VtkAlgorithmProperties object. /// @param parent The parent widget. - VtkAlgorithmPropertyVectorEdit(const QList<QString> contents, const QString& name, - QVariant::Type type, VtkAlgorithmProperties* algProps, QWidget* parent = 0); + VtkAlgorithmPropertyVectorEdit(const QList<QString> contents, + const QString& name, + QVariant::Type type, + VtkAlgorithmProperties* algProps, + QWidget* parent = 0); virtual ~VtkAlgorithmPropertyVectorEdit(); private: diff --git a/VtkVis/VtkApplyColorTableFilter.cpp b/VtkVis/VtkApplyColorTableFilter.cpp index 8180f6ef1f77f8058d69e81eeffaffc0a956a8d3..1f95f30467134a6c2e7b65b5f62e973540c31fee 100644 --- a/VtkVis/VtkApplyColorTableFilter.cpp +++ b/VtkVis/VtkApplyColorTableFilter.cpp @@ -5,15 +5,15 @@ */ // ** VTK INCLUDES ** +#include "vtkObjectFactory.h" +#include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> -#include "vtkObjectFactory.h" -#include <vtkStreamingDemandDrivenPipeline.h> -#include <vtkPolyData.h> -#include <vtkSmartPointer.h> #include <vtkLookupTable.h> #include <vtkPointData.h> -#include <vtkCellData.h> +#include <vtkPolyData.h> +#include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> #include "VtkApplyColorTableFilter.h" @@ -21,7 +21,6 @@ vtkStandardNewMacro(VtkApplyColorTableFilter); vtkCxxSetObjectMacro(VtkApplyColorTableFilter, ColorLookupTable, vtkLookupTable); vtkCxxRevisionMacro(VtkApplyColorTableFilter, "$Revision: 6575 $"); - VtkApplyColorTableFilter::VtkApplyColorTableFilter() : ColorLookupTable(NULL) { this->SetColorsOnCells(false); @@ -31,39 +30,42 @@ VtkApplyColorTableFilter::~VtkApplyColorTableFilter() { } -int VtkApplyColorTableFilter::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkApplyColorTableFilter::RequestData( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { - if (this->ColorLookupTable==NULL) return 0; + if (this->ColorLookupTable == NULL) + return 0; (void)request; vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkPolyData *input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData* input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkUnsignedCharArray> colorTable = this->ColorLookupTable->GetTable(); - vtkSmartPointer<vtkUnsignedCharArray> colorArray = vtkSmartPointer<vtkUnsignedCharArray>::New(); - colorArray->SetNumberOfComponents(4); - colorArray->SetName("Colors"); - vtkSmartPointer<vtkUnsignedCharArray> scalars = - (!ColorsOnCells) ? vtkUnsignedCharArray::SafeDownCast(input->GetPointData()->GetScalars()) - : vtkUnsignedCharArray::SafeDownCast(input->GetCellData()->GetScalars()); + vtkSmartPointer<vtkUnsignedCharArray> colorArray = + vtkSmartPointer<vtkUnsignedCharArray>::New(); + colorArray->SetNumberOfComponents(4); + colorArray->SetName("Colors"); + vtkSmartPointer<vtkUnsignedCharArray> scalars = + (!ColorsOnCells) ? vtkUnsignedCharArray::SafeDownCast( + input->GetPointData()->GetScalars()) + : vtkUnsignedCharArray::SafeDownCast(input->GetCellData()->GetScalars()); int limit = (!ColorsOnCells) ? input->GetNumberOfPoints() : input->GetNumberOfCells(); - - for (int i=0; i<limit; i++) + + for (int i = 0; i < limit; i++) { double* value = scalars->GetTuple(i); unsigned char* rgba = new unsigned char[4]; colorTable->GetTupleValue(static_cast<int>(value[0]), rgba); - colorArray->InsertNextTupleValue(rgba); + colorArray->InsertNextTupleValue(rgba); } vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - output->CopyStructure(input); - output->GetPointData()->PassData(input->GetPointData()); - output->GetCellData() ->PassData(input->GetCellData()); + vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + output->CopyStructure(input); + output->GetPointData()->PassData(input->GetPointData()); + output->GetCellData()->PassData(input->GetCellData()); if (!ColorsOnCells) { output->GetPointData()->AddArray(colorArray); diff --git a/VtkVis/VtkApplyColorTableFilter.h b/VtkVis/VtkApplyColorTableFilter.h index 217eaccca8c4e24e937df8de63a47c349990380c..0306842daa39faa1b234f49c9c126abfbc9862de 100644 --- a/VtkVis/VtkApplyColorTableFilter.h +++ b/VtkVis/VtkApplyColorTableFilter.h @@ -4,21 +4,19 @@ * */ - #ifndef VTKAPPLYCOLORTABLEFILTER_H #define VTKAPPLYCOLORTABLEFILTER_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" #include <vtkLookupTable.h> +#include <vtkPolyDataAlgorithm.h> /** * \brief Applying a color table to a vtk object. */ class VtkApplyColorTableFilter : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkApplyColorTableFilter* New(); @@ -54,10 +52,9 @@ protected: ~VtkApplyColorTableFilter(); /// Computes the unstructured grid data object. - int RequestData(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector); - + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); private: vtkLookupTable* ColorLookupTable; diff --git a/VtkVis/VtkBGImageSource.cpp b/VtkVis/VtkBGImageSource.cpp index 8db518fe798ea34d8a6b7e62b52b9c01ca10b3be..4f5cd20bce8e60565179991e673fc09d5e8604a6 100644 --- a/VtkVis/VtkBGImageSource.cpp +++ b/VtkVis/VtkBGImageSource.cpp @@ -13,15 +13,14 @@ #include "vtkObjectFactory.h" #include <vtkInformation.h> #include <vtkInformationVector.h> -#include <vtkStreamingDemandDrivenPipeline.h> -#include <vtkSmartPointer.h> #include <vtkPlaneSource.h> +#include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> #include <vtkTexture.h> vtkStandardNewMacro(VtkBGImageSource); vtkCxxRevisionMacro(VtkBGImageSource, "$Revision$"); - VtkBGImageSource::VtkBGImageSource() : _origin(0,0), _cellsize(1) { } @@ -30,24 +29,22 @@ VtkBGImageSource::~VtkBGImageSource() { } -void VtkBGImageSource::SetImage(vtkTexture* texture) -{ - this->SetTexture(texture); +void VtkBGImageSource::SetImage(vtkTexture* texture) +{ + this->SetTexture(texture); } -void VtkBGImageSource::SetRaster(QImage &img) +void VtkBGImageSource::SetRaster(QImage &img) { vtkTexture* texture = VtkVisHelper::QImageToVtkTexture(img); vtkSmartPointer<vtkPlaneSource> plane = vtkSmartPointer<vtkPlaneSource>::New(); - plane->SetOrigin( _origin.first, _origin.second, -1 ); - plane->SetPoint1( _origin.first + img.width() * _cellsize, _origin.second, -1 ); - plane->SetPoint2( _origin.first,_origin.second + img.height() * _cellsize, -1 ); + plane->SetOrigin( _origin.first, _origin.second, -1 ); + plane->SetPoint1( _origin.first + img.width() * _cellsize, _origin.second, -1 ); + plane->SetPoint2( _origin.first,_origin.second + img.height() * _cellsize, -1 ); - this->SetInputConnection(0, plane->GetOutputPort(0)); + this->SetInputConnection(0, plane->GetOutputPort(0)); this->SetTexture(texture); - - } void VtkBGImageSource::SetUserProperty( QString name, QVariant value ) diff --git a/VtkVis/VtkBGImageSource.h b/VtkVis/VtkBGImageSource.h index f9775758e2bdd86e8c1a69eb112552cffa9f2aba..8767b4260088aba8ddc366d547da2c7442b32bd8 100644 --- a/VtkVis/VtkBGImageSource.h +++ b/VtkVis/VtkBGImageSource.h @@ -4,7 +4,6 @@ * */ - #ifndef VTKBGIMAGESOURCE_H #define VTKBGIMAGESOURCE_H @@ -13,7 +12,6 @@ #include "VtkAlgorithmProperties.h" - class QImage; /** @@ -22,7 +20,6 @@ class QImage; */ class VtkBGImageSource : public vtkTextureMapToPlane, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkBGImageSource* New(); @@ -33,14 +30,17 @@ public: void SetImage(vtkTexture* texture); /// Sets the cellsize (i.e. the actual dimension of a pixel) - void SetCellSize(double c) { _cellsize = c; }; + void SetCellSize(double c) { _cellsize = c; } /// Sets the raster/image to be used as a texture map void SetRaster(QImage &img); /// Sets the geo-referenced origin of the image (i.e. the lower left corner) - virtual void SetOrigin(double x, double y, double z = 0.0) { _origin.first = x; _origin.second = y; (void)z; }; - virtual void SetOrigin(double* pos) { _origin.first = pos[0]; _origin.second = pos[1]; }; + virtual void SetOrigin(double x, double y, double z = 0.0) { _origin.first = x; + _origin.second = y; + (void)z; } + virtual void SetOrigin(double* pos) { _origin.first = pos[0]; + _origin.second = pos[1]; } virtual void SetUserProperty(QString name, QVariant value); @@ -48,13 +48,10 @@ protected: VtkBGImageSource(); ~VtkBGImageSource(); - private: - + std::pair<double, double> _origin; double _cellsize; - - }; #endif // VTKBGIMAGESOURCE_H diff --git a/VtkVis/VtkColorByHeightFilter.cpp b/VtkVis/VtkColorByHeightFilter.cpp index daa917f61de01985f0fa7f142c5933ad8865bd55..95519d88cb34ea2fe28765cdd213217ebcc2ea2a 100644 --- a/VtkVis/VtkColorByHeightFilter.cpp +++ b/VtkVis/VtkColorByHeightFilter.cpp @@ -8,20 +8,19 @@ #include "VtkColorByHeightFilter.h" #include "VtkColorLookupTable.h" +#include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> +#include <vtkLookupTable.h> #include <vtkObjectFactory.h> -#include <vtkStreamingDemandDrivenPipeline.h> +#include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkSmartPointer.h> -#include <vtkLookupTable.h> -#include <vtkPointData.h> -#include <vtkCellData.h> +#include <vtkStreamingDemandDrivenPipeline.h> vtkStandardNewMacro(VtkColorByHeightFilter); vtkCxxRevisionMacro(VtkColorByHeightFilter, "$Revision$"); - VtkColorByHeightFilter::VtkColorByHeightFilter() { ColorLookupTable = VtkColorLookupTable::New(); @@ -60,25 +59,23 @@ unsigned long VtkColorByHeightFilter::GetMTime() } return t1; } -int VtkColorByHeightFilter::RequestData( vtkInformation*, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkColorByHeightFilter::RequestData( vtkInformation*, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { - vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkPolyData *input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - + vtkPolyData* input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); ColorLookupTable->SetTableRange(getMinHeight(input), getMaxHeight(input)); ColorLookupTable->Build(); vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New(); - colors->SetNumberOfComponents(3); - colors->SetName("Colors"); + colors->SetNumberOfComponents(3); + colors->SetName("Colors"); // Generate the colors for each point based on the color map size_t nPoints = input->GetNumberOfPoints(); - for (size_t i=0; i<nPoints; i++) + for (size_t i = 0; i < nPoints; i++) { double p[3]; input->GetPoint(i,p); @@ -89,12 +86,12 @@ int VtkColorByHeightFilter::RequestData( vtkInformation*, } vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkPolyData *output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - output->CopyStructure(input); - output->GetPointData()->PassData(input->GetPointData()); - output->GetCellData()->PassData(input->GetCellData()); - output->GetPointData()->AddArray(colors); - output->GetPointData()->SetActiveScalars("Colors"); + vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + output->CopyStructure(input); + output->GetPointData()->PassData(input->GetPointData()); + output->GetCellData()->PassData(input->GetCellData()); + output->GetPointData()->AddArray(colors); + output->GetPointData()->SetActiveScalars("Colors"); return 1; } @@ -111,10 +108,11 @@ double VtkColorByHeightFilter::getMinHeight(vtkPolyData* data) data->GetPoint(0,p); min = p[2]; - for (size_t i=1; i<nPoints; i++) + for (size_t i = 1; i < nPoints; i++) { data->GetPoint(i,p); - if (p[2]<min) min = p[2]; + if (p[2] < min) + min = p[2]; } } return min; @@ -132,17 +130,16 @@ double VtkColorByHeightFilter::getMaxHeight(vtkPolyData* data) data->GetPoint(0,p); max = p[2]; - for (size_t i=1; i<nPoints; i++) + for (size_t i = 1; i < nPoints; i++) { data->GetPoint(i,p); - if (p[2]>max) + if (p[2] > max) max = p[2]; } } return max; } - void VtkColorByHeightFilter::SetTableRange(double min, double max) { if (min < max) @@ -151,13 +148,15 @@ void VtkColorByHeightFilter::SetTableRange(double min, double max) this->_tableRange[1] = max; this->ColorLookupTable->SetTableRange(min, max); } - else - vtkstd::cout << "VtkColorByHeightFilter::SetLimits(min, max) - Limits not changed because min value > max value." << vtkstd::endl; + else + vtkstd::cout << + "VtkColorByHeightFilter::SetLimits(min, max) - Limits not changed because min value > max value." + << vtkstd::endl; } void VtkColorByHeightFilter::SetTableRangeScaling( double scale ) { this->_tableRangeScaling = scale; this->ColorLookupTable->SetTableRange( - this->_tableRange[0] * scale, this->_tableRange[1] * scale); + this->_tableRange[0] * scale, this->_tableRange[1] * scale); } diff --git a/VtkVis/VtkColorByHeightFilter.h b/VtkVis/VtkColorByHeightFilter.h index b4997961f3bb4a0ab0e71904b05a492df9d1617c..64458b9a35b8eca0b5fd163d4b9514d4881c3f28 100644 --- a/VtkVis/VtkColorByHeightFilter.h +++ b/VtkVis/VtkColorByHeightFilter.h @@ -4,13 +4,12 @@ * */ - #ifndef VTKCOLORBYHEIGHTFILTER_H #define VTKCOLORBYHEIGHTFILTER_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" +#include <vtkPolyDataAlgorithm.h> class VtkColorLookupTable; @@ -21,12 +20,11 @@ class VtkColorLookupTable; * ColorLookupTable using the method GetColorLookupTable(). Using this method allows the user to set a number * of properties on that lookup table such as interpolation method, the range of values over which the lookup * table is calculated and so on. - * If no range boundaries are explicitly set, the minimum and maximum height value will be calculated from + * If no range boundaries are explicitly set, the minimum and maximum height value will be calculated from * the data and set as minimum and maximum value for the lookup table. */ class VtkColorByHeightFilter : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties { - public: /// @brief Create new objects with New() because of VTKs object reference counting. static VtkColorByHeightFilter* New(); @@ -43,11 +41,11 @@ public: virtual unsigned long GetMTime(); /// @brief Sets user properties. - void SetUserProperty(QString name, QVariant value) - { + void SetUserProperty(QString name, QVariant value) + { Q_UNUSED(name); Q_UNUSED(value); - } + } /// @brief Sets the boundaries for the color look-up table. void SetTableRange(double min, double max); @@ -61,9 +59,9 @@ protected: ~VtkColorByHeightFilter(); /// @brief The filter logic. - int RequestData(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); /// @brief Calculates the color lookup table based on set parameters. VtkColorLookupTable* BuildColorTable(); diff --git a/VtkVis/VtkColorLookupTable.cpp b/VtkVis/VtkColorLookupTable.cpp index 5508d2563f604abbdf372510f43e5c381d91369e..42ff65f70270f3ae4b87fe9ce2a7d7977b8a67ba 100644 --- a/VtkVis/VtkColorLookupTable.cpp +++ b/VtkVis/VtkColorLookupTable.cpp @@ -6,44 +6,51 @@ #include "VtkColorLookupTable.h" -#include <cmath> #include <Color.h> +#include <cmath> #include <vtkObjectFactory.h> vtkStandardNewMacro(VtkColorLookupTable); vtkCxxRevisionMacro(VtkColorLookupTable, "$Revision$"); VtkColorLookupTable::VtkColorLookupTable() -: _type(VtkColorLookupTable::LINEAR) + : _type(VtkColorLookupTable::LINEAR) { this->SetNumberOfTableValues(256); } VtkColorLookupTable::~VtkColorLookupTable() { - for (std::map<double, unsigned char*>::const_iterator it = _dict.begin(); it != _dict.end(); ++it) delete it->second; + for (std::map<double, unsigned char*>::const_iterator it = _dict.begin(); it != _dict.end(); + ++it) + delete it->second; } - -unsigned char VtkColorLookupTable::linInterpolation(unsigned char a, unsigned char b, double p) const +unsigned char VtkColorLookupTable::linInterpolation(unsigned char a, unsigned char b, + double p) const { - return static_cast<unsigned char>(a * (1 - p) + b * p); + return static_cast<unsigned char>(a * (1 - p) + b * p); } -unsigned char VtkColorLookupTable::expInterpolation(unsigned char a, unsigned char b, double gamma, double p) const +unsigned char VtkColorLookupTable::expInterpolation(unsigned char a, + unsigned char b, + double gamma, + double p) const { - assert (gamma>0 && gamma<4); - return static_cast<unsigned char>((b-a)*pow(p,gamma)+a); + assert (gamma > 0 && gamma < 4); + return static_cast<unsigned char>((b - a) * pow(p,gamma) + a); } - void VtkColorLookupTable::Build() { if (!_dict.empty()) { // make sure that color map starts with the first color in the dictionary unsigned char* startcolor = new unsigned char[4]; - startcolor[0] = _dict.begin()->second[0]; startcolor[1] = _dict.begin()->second[1]; startcolor[2] = _dict.begin()->second[2]; startcolor[3] = _dict.begin()->second[3]; + startcolor[0] = _dict.begin()->second[0]; + startcolor[1] = _dict.begin()->second[1]; + startcolor[2] = _dict.begin()->second[2]; + startcolor[3] = _dict.begin()->second[3]; std::pair<size_t, unsigned char*> lastValue(0, startcolor); size_t nextIndex(0); @@ -53,46 +60,55 @@ void VtkColorLookupTable::Build() if (lastitr->first != 1) { unsigned char* lastcolor = new unsigned char[4]; - for (size_t i=0; i<4; i++) lastcolor[i] = lastitr->second[i]; + for (size_t i = 0; i < 4; i++) + lastcolor[i] = lastitr->second[i]; _dict.insert( std::pair<double, unsigned char*>(1.0, lastcolor) ); } - for (std::map<double, unsigned char*>::const_iterator it = _dict.begin(); it != _dict.end(); ++it) + for (std::map<double, unsigned char*>::const_iterator it = _dict.begin(); + it != _dict.end(); ++it) { //unsigned char rgba[4]; //rgba[0] = (*it->second)[0]; rgba[1] = (*it->second)[1]; rgba[2] = (*it->second)[2]; rgba[3] = 255; - nextIndex = static_cast<size_t>( floor(it->first * this->GetNumberOfTableValues()) ); - if (nextIndex >= static_cast<size_t>(this->GetNumberOfTableValues())) nextIndex--; // this happens for the very last colour + nextIndex = + static_cast<size_t>( floor(it->first * this->GetNumberOfTableValues()) ); + if (nextIndex >= static_cast<size_t>(this->GetNumberOfTableValues())) + nextIndex--; // this happens for the very last colour this->SetTableValue(nextIndex, it->second); - if ( nextIndex-lastValue.first > 1 ) - { - for (size_t i = lastValue.first+1; i < nextIndex; i++) + if ( nextIndex - lastValue.first > 1 ) + for (size_t i = lastValue.first + 1; i < nextIndex; i++) { unsigned char int_rgba[4]; int_rgba[3] = 255; - double pos = (i - lastValue.first) / (static_cast<double>(nextIndex - lastValue.first)); + double pos = + (i - + lastValue.first) / + (static_cast<double>(nextIndex - lastValue.first)); if (_type == VtkColorLookupTable::LINEAR) - { - for (size_t j=0; j<3; j++) - int_rgba[j] = linInterpolation((lastValue.second)[j], (it->second)[j], pos); - } + for (size_t j = 0; j < 3; j++) + int_rgba[j] = + linInterpolation( + (lastValue.second)[j], + (it->second)[j], + pos); else if (_type == VtkColorLookupTable::EXPONENTIAL) - { - for (size_t j=0; j<3; j++) - int_rgba[j] = expInterpolation((lastValue.second)[j], (it->second)[j], 0.2, pos); - } - else // no interpolation - { - for (size_t j=0; j<3; j++) - int_rgba[j] = (lastValue.second)[j]; - } + for (size_t j = 0; j < 3; j++) + int_rgba[j] = + expInterpolation( + (lastValue.second)[j], + (it->second)[j], + 0.2, + pos); + else // no interpolation + + for (size_t j = 0; j < 3; j++) + int_rgba[j] = (lastValue.second)[j]; this->SetTableValue(i, int_rgba); } - } lastValue.first = nextIndex; lastValue.second = it->second; @@ -108,10 +124,11 @@ void VtkColorLookupTable::readFromFile(const std::string &filename) GEOLIB::readColorLookupTable(colors, filename); this->SetNumberOfTableValues(colors.size()); - for (std::map<std::string, GEOLIB::Color*>::iterator it = colors.begin(); it != colors.end(); ++it) - { - this->SetTableValue( static_cast<vtkIdType>(strtod( it->first.c_str(), 0 )), (*(it->second))[0], (*(it->second))[1], (*(it->second))[2], 255 ); - } + for (std::map<std::string, GEOLIB::Color*>::iterator it = colors.begin(); it != colors.end(); + ++it) + this->SetTableValue( static_cast<vtkIdType>(strtod( it->first.c_str(), + 0 )), (*(it->second))[0], + (*(it->second))[1], (*(it->second))[2], 255 ); } void VtkColorLookupTable::writeToFile(const std::string &filename) @@ -120,18 +137,17 @@ void VtkColorLookupTable::writeToFile(const std::string &filename) std::ofstream out( filename.c_str(), std::ios::out ); size_t nColors = this->GetNumberOfTableValues(); - for (size_t i=0; i<nColors; i++) + for (size_t i = 0; i < nColors; i++) { unsigned char rgba[4]; this->GetTableValue(i, rgba); - out << i << "\t" << rgba[0] << "\t" <<rgba[1] << "\t" << rgba[2] << std::endl; + out << i << "\t" << rgba[0] << "\t" << rgba[1] << "\t" << rgba[2] << std::endl; } std::cout << " done." << std::endl; out.close(); } - void VtkColorLookupTable::SetTableValue(vtkIdType indx, unsigned char rgba[4]) { // Check the index to make sure it is valid @@ -142,49 +158,72 @@ void VtkColorLookupTable::SetTableValue(vtkIdType indx, unsigned char rgba[4]) } if (indx >= this->NumberOfColors) { - vtkErrorMacro("Index " << indx << " is greater than the number of colors " << this->NumberOfColors); + vtkErrorMacro( + "Index " << indx << " is greater than the number of colors " << + this->NumberOfColors); return; } - unsigned char *_rgba = this->Table->WritePointer(4*indx,4); - for (size_t i=0; i<4; i++) _rgba[i]=rgba[i]; + unsigned char* _rgba = this->Table->WritePointer(4 * indx,4); + for (size_t i = 0; i < 4; i++) + _rgba[i] = rgba[i]; this->InsertTime.Modified(); this->Modified(); } -void VtkColorLookupTable::SetTableValue(vtkIdType indx, unsigned char r, unsigned char g, unsigned char b, unsigned char a) +void VtkColorLookupTable::SetTableValue(vtkIdType indx, + unsigned char r, + unsigned char g, + unsigned char b, + unsigned char a) { - unsigned char rgba[4]; - rgba[0] = r; rgba[1] = g; rgba[2] = b; rgba[3] = a; - this->SetTableValue(indx,rgba); + unsigned char rgba[4]; + rgba[0] = r; + rgba[1] = g; + rgba[2] = b; + rgba[3] = a; + this->SetTableValue(indx,rgba); } void VtkColorLookupTable::GetTableValue(vtkIdType indx, unsigned char rgba[4]) { - unsigned char *_rgba; - _rgba = this->Table->GetPointer(indx*4); - for (size_t i=0; i<4; i++) rgba[i]=_rgba[i]; + unsigned char* _rgba; + _rgba = this->Table->GetPointer(indx * 4); + for (size_t i = 0; i < 4; i++) + rgba[i] = _rgba[i]; } void VtkColorLookupTable::setColor(double pos, unsigned char rgba[4]) { - if (pos>=0 && pos<=1) + if (pos >= 0 && pos <= 1) { unsigned char* dict_rgba = new unsigned char[4]; - for (size_t i=0; i<4; i++) dict_rgba[i] = rgba[i]; + for (size_t i = 0; i < 4; i++) + dict_rgba[i] = rgba[i]; _dict.insert( std::pair<double, unsigned char*>(pos, dict_rgba) ); } else - std::cout << "ColorLookupTable::setValue() - Error: pos should be in [0,1]" << std::endl; + std::cout << "ColorLookupTable::setValue() - Error: pos should be in [0,1]" << + std::endl; } void VtkColorLookupTable::getColor(vtkIdType indx, unsigned char rgba[4]) const { - indx = ((indx < this->TableRange[0]) ? static_cast<vtkIdType>(this->TableRange[0]) : (indx >= this->TableRange[1] ? static_cast<vtkIdType>(this->TableRange[1])-1 : indx)); - indx = static_cast<size_t>( floor( (indx - this->TableRange[0]) * (this->NumberOfColors/(this->TableRange[1]-this->TableRange[0])) ) ); - - unsigned char *_rgba; - _rgba = this->Table->GetPointer(indx*4); - for (size_t i=0; i<4; i++) rgba[i]=_rgba[i]; + indx = + ((indx < + this->TableRange[0]) ? static_cast<vtkIdType>(this->TableRange[0]) : (indx >= + this + -> + TableRange[1] ? static_cast<vtkIdType>(this->TableRange[1]) - 1 : indx)); + indx = + static_cast<size_t>( floor( (indx - + this->TableRange[0]) * + (this->NumberOfColors / + (this->TableRange[1] - this->TableRange[0])) ) ); + + unsigned char* _rgba; + _rgba = this->Table->GetPointer(indx * 4); + for (size_t i = 0; i < 4; i++) + rgba[i] = _rgba[i]; } diff --git a/VtkVis/VtkColorLookupTable.h b/VtkVis/VtkColorLookupTable.h index 3cacc8cba72cbbb167b94892bf4cf8ba93e40616..15b66d3b11d4b327ab8be209bd7da11ab1450505 100644 --- a/VtkVis/VtkColorLookupTable.h +++ b/VtkVis/VtkColorLookupTable.h @@ -4,14 +4,13 @@ * */ - #ifndef VTKCOLORLOOKUPTABLE_H #define VTKCOLORLOOKUPTABLE_H // ** INCLUDES ** #include <cassert> -#include <vector> #include <map> +#include <vector> #include <vtkLookupTable.h> /** @@ -19,7 +18,7 @@ * * Based on a start colour and an end colour, RGB-values are interpolated and stored in vector of GEOLIB::Color. If no * colours are set, default values are used for start (blue) and end (red). The number of entries of the colour table can - * be set in the constructor, the default value is 256. If additional colours are inserted into the table using setColor() + * be set in the constructor, the default value is 256. If additional colours are inserted into the table using setColor() * the interpolation will be calculated iteratively between set colour values. Interpolation can be linear (default) or * exponential. Based on the set range of values, colour values can be retrieved using getColor(). */ @@ -31,9 +30,9 @@ public: NONE = 0, LINEAR = 1, EXPONENTIAL = 2, - SIGMOID = 3 // not yet implemented + SIGMOID = 3 // not yet implemented }; - + static const int DEFAULTMINVALUE = -9999; static const int DEFAULTMAXVALUE = 9999; @@ -46,24 +45,24 @@ public: /// This method should only be called after all options have been set. void Build(); - /* \brief Sets the given colour as a constant in the colour lookup table. + /* \brief Sets the given colour as a constant in the colour lookup table. * The colour will subsequently be considered in the interpolation process when the lookup table is built. Note that pos is only a * relative position, i.e. pos in (0,1). The actual position of that colour in the table is dependent on the number of entries set * the SetRange() method. */ void setColor(double pos, unsigned char rgba[4]); - /* \brief Returns the colour at the given index from the colour lookup table. + /* \brief Returns the colour at the given index from the colour lookup table. * The colour will be interpolated from the colour-dictionary entries before and after this index. * Make sure that Build() has been called before using this method. */ void getColor(vtkIdType indx, unsigned char rgba[4]) const; /// Returns the type of interpolation used. - VtkColorLookupTable::LUTType getInterpolationType() const { return _type; }; + VtkColorLookupTable::LUTType getInterpolationType() const { return _type; } /// Sets the type of interpolation. - void setInterpolationType(VtkColorLookupTable::LUTType type) { _type = type; }; + void setInterpolationType(VtkColorLookupTable::LUTType type) { _type = type; } /// Imports a color table from a file. void readFromFile(const std::string &filename); @@ -71,7 +70,7 @@ public: /// Exports a color table to a file. void writeToFile(const std::string &filename); - /** + /** * Directly load color into lookup table. Use unsigned char values for color * component specification. Make sure that you've either used the * Build() method or used SetNumberOfTableValues() prior to using this method. @@ -81,9 +80,13 @@ public: /// Directly load color into lookup table. /// This is just a convenience method to use instead of vtkLookupTable::SetTableValue(). - void SetTableValue(vtkIdType indx, unsigned char r, unsigned char g, unsigned char b, unsigned char a); + void SetTableValue(vtkIdType indx, + unsigned char r, + unsigned char g, + unsigned char b, + unsigned char a); - /// Return a rgba color value for the given index into the lookup Table. + /// Return a rgba color value for the given index into the lookup Table. /// This is just a convenience method to use instead of vtkLookupTable::GetTableValue(). void GetTableValue(vtkIdType indx, unsigned char rgba[4]); @@ -99,7 +102,8 @@ private: unsigned char linInterpolation(unsigned char a, unsigned char b, double p) const; /// Interpolates values exponentially. gamma should roughly be in [0,4), for gamma=1 interpolation is linear. - unsigned char expInterpolation(unsigned char a, unsigned char b, double gamma, double p) const; + unsigned char expInterpolation(unsigned char a, unsigned char b, double gamma, + double p) const; std::map<double, unsigned char*> _dict; LUTType _type; diff --git a/VtkVis/VtkCompositeColorByHeightFilter.cpp b/VtkVis/VtkCompositeColorByHeightFilter.cpp index e47a2eac887293d68caf6f1499e38a7257f4f183..a4e0457f2a60bf049a3c0fdde1180f9dd3bc2e7a 100644 --- a/VtkVis/VtkCompositeColorByHeightFilter.cpp +++ b/VtkVis/VtkCompositeColorByHeightFilter.cpp @@ -1,21 +1,21 @@ /** * \file VtkCompositeColorByHeightFilter.cpp * 01/11/2010 KR Initial implementation - * + * * Implementation of VtkCompositePointToGlyphFilter class */ // ** INCLUDES ** -#include "VtkCompositeColorByHeightFilter.h" #include "VtkColorByHeightFilter.h" #include "VtkColorLookupTable.h" +#include "VtkCompositeColorByHeightFilter.h" -#include <vtkSmartPointer.h> #include <vtkDataSetSurfaceFilter.h> +#include <vtkSmartPointer.h> #include <vtkUnstructuredGrid.h> VtkCompositeColorByHeightFilter::VtkCompositeColorByHeightFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -39,10 +39,10 @@ void VtkCompositeColorByHeightFilter::init() heightFilter->SetTableRange(-35, 800); // default min- and max-height (default: blue to red) //heightFilter->GetColorLookupTable()->setInterpolationType(ColorLookupTable::EXPONENTIAL); - unsigned char a[4] = { 0, 0, 255, 255 }; // blue - unsigned char b[4] = { 0, 255, 0, 255 }; // green + unsigned char a[4] = { 0, 0, 255, 255 }; // blue + unsigned char b[4] = { 0, 255, 0, 255 }; // green unsigned char c[4] = { 255, 255, 0, 255 }; // yellow - unsigned char d[4] = { 255, 0, 0, 255 }; // red + unsigned char d[4] = { 255, 0, 0, 255 }; // red //unsigned char e[4] = { 255, 255, 255, 255 }; // white heightFilter->GetColorLookupTable()->setColor(0.0, a); heightFilter->GetColorLookupTable()->setColor(0.2, b); // green at about 150m diff --git a/VtkVis/VtkCompositeColorByHeightFilter.h b/VtkVis/VtkCompositeColorByHeightFilter.h index 69332cff2922eef698937107eaafebce450eb556..c6d8cebe1f3ddfeb6e40f182fab526149241d3e1 100644 --- a/VtkVis/VtkCompositeColorByHeightFilter.h +++ b/VtkVis/VtkCompositeColorByHeightFilter.h @@ -15,14 +15,13 @@ class VtkCompositeColorByHeightFilter : public VtkCompositeFilter { public: VtkCompositeColorByHeightFilter(vtkAlgorithm* inputAlgorithm); - virtual ~VtkCompositeColorByHeightFilter() {}; + virtual ~VtkCompositeColorByHeightFilter() {} virtual void init(); virtual void SetUserProperty(QString name, QVariant value); protected: - }; #endif // VTKCOMPOSITECOLORBYHEIGHTFILTER_H diff --git a/VtkVis/VtkCompositeColormapToImageFilter.cpp b/VtkVis/VtkCompositeColormapToImageFilter.cpp index a9fa07b747d4bcbf3a931ff519a94f40d6156b13..72a3c55bef7e6656ac4b05e2dbae274253f7afe9 100644 --- a/VtkVis/VtkCompositeColormapToImageFilter.cpp +++ b/VtkVis/VtkCompositeColormapToImageFilter.cpp @@ -1,19 +1,19 @@ /** * \file VtkCompositeColormapToImageFilter.cpp * 21/10/2010 LB Initial implementation - * + * * Implementation of VtkCompositeColormapToImageFilter class */ // ** INCLUDES ** #include "VtkCompositeColormapToImageFilter.h" -#include <vtkLookupTable.h> #include <vtkImageMapToColors.h> +#include <vtkLookupTable.h> #include <vtkSmartPointer.h> VtkCompositeColormapToImageFilter::VtkCompositeColormapToImageFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -58,7 +58,8 @@ void VtkCompositeColormapToImageFilter::SetUserProperty( QString name, QVariant if (name.compare("PassAlphaToOutput") == 0) map->SetPassAlphaToOutput(value.toBool()); else if (name.compare("NumberOfColors") == 0) - static_cast<vtkLookupTable*>(map->GetLookupTable())->SetNumberOfTableValues(value.toInt()); + static_cast<vtkLookupTable*>(map->GetLookupTable())->SetNumberOfTableValues( + value.toInt()); } void VtkCompositeColormapToImageFilter::SetUserVectorProperty( QString name, QList<QVariant> values ) @@ -67,7 +68,10 @@ void VtkCompositeColormapToImageFilter::SetUserVectorProperty( QString name, QLi vtkImageMapToColors* map = static_cast<vtkImageMapToColors*>(_outputAlgorithm); if (name.compare("TableRange") == 0) - static_cast<vtkLookupTable*>(map->GetLookupTable())->SetTableRange(values[0].toInt(), values[1].toInt()); + static_cast<vtkLookupTable*>(map->GetLookupTable())->SetTableRange( + values[0].toInt(), values[1].toInt()); else if (name.compare("HueRange") == 0) - static_cast<vtkLookupTable*>(map->GetLookupTable())->SetHueRange(values[0].toDouble(), values[1].toDouble()); + static_cast<vtkLookupTable*>(map->GetLookupTable())->SetHueRange(values[0].toDouble( + ), + values[1].toDouble()); } diff --git a/VtkVis/VtkCompositeColormapToImageFilter.h b/VtkVis/VtkCompositeColormapToImageFilter.h index b638fa615946945b4fe6a5c304f58c4efc74484b..f9f0821d511801a3a21bce3a718b440ab8479979 100644 --- a/VtkVis/VtkCompositeColormapToImageFilter.h +++ b/VtkVis/VtkCompositeColormapToImageFilter.h @@ -22,7 +22,6 @@ public: virtual void SetUserVectorProperty(QString name, QList<QVariant> values); private: - }; #endif // VTKCOMPOSITECOLORMAPTOIMAGEFILTER_H diff --git a/VtkVis/VtkCompositeContourFilter.cpp b/VtkVis/VtkCompositeContourFilter.cpp index ce22c94bd93bfce7fc7a52322b913cfcd5e65a87..0e7ef3bcebb13904096dbf869e081ea97bdc6911 100644 --- a/VtkVis/VtkCompositeContourFilter.cpp +++ b/VtkVis/VtkCompositeContourFilter.cpp @@ -6,13 +6,13 @@ // ** INCLUDES ** #include "VtkCompositeContourFilter.h" -#include <vtkContourFilter.h> -#include <vtkUnstructuredGrid.h> #include <vtkCellData.h> +#include <vtkContourFilter.h> #include <vtkSmartPointer.h> +#include <vtkUnstructuredGrid.h> VtkCompositeContourFilter::VtkCompositeContourFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -24,7 +24,7 @@ VtkCompositeContourFilter::~VtkCompositeContourFilter() void VtkCompositeContourFilter::init() { // Set meta information about input and output data types - this->_inputDataObjectType = VTK_UNSTRUCTURED_GRID;//VTK_DATA_SET; + this->_inputDataObjectType = VTK_UNSTRUCTURED_GRID; //VTK_DATA_SET; this->_outputDataObjectType = VTK_UNSTRUCTURED_GRID; // Because this is the only filter here we cannot use vtkSmartPointer @@ -33,7 +33,7 @@ void VtkCompositeContourFilter::init() // Sets a filter vector property which will be user editable contour->GenerateValues(10, 0, 100); - + // Create a list for the ThresholdBetween (vector) property. QList<QVariant> contourRangeList; // Insert the values (same values as above) @@ -41,10 +41,10 @@ void VtkCompositeContourFilter::init() contourRangeList.push_back(100); // Put that list in the property map (*_algorithmUserVectorProperties)["Range"] = contourRangeList; - + // Make a new entry in the property map for the SelectedComponent property (*_algorithmUserProperties)["Number of Contours"] = 10; - + // The threshold filter is last one and so it is also the _outputAlgorithm _outputAlgorithm = contour; } @@ -64,7 +64,8 @@ void VtkCompositeContourFilter::SetUserVectorProperty( QString name, QList<QVari // Use the same name as in init() if (name.compare("Range") == 0) - static_cast<vtkContourFilter*>(_outputAlgorithm)->GenerateValues(VtkAlgorithmProperties::GetUserProperty("Number of Contours").toInt(), values[0].toDouble(), values[1].toDouble()); - - + static_cast<vtkContourFilter*>(_outputAlgorithm)->GenerateValues( + VtkAlgorithmProperties::GetUserProperty("Number of Contours").toInt(), + values[0].toDouble(), + values[1].toDouble()); } diff --git a/VtkVis/VtkCompositeContourFilter.h b/VtkVis/VtkCompositeContourFilter.h index e0a5c34a67167ad5d9ac6974261b03f450140f95..e3810de045b92a35830e2a0bf07e0a78db34824f 100644 --- a/VtkVis/VtkCompositeContourFilter.h +++ b/VtkVis/VtkCompositeContourFilter.h @@ -14,7 +14,7 @@ class VtkCompositeContourFilter : public VtkCompositeFilter public: VtkCompositeContourFilter(vtkAlgorithm* inputAlgorithm); virtual ~VtkCompositeContourFilter(); - + virtual void init(); virtual void SetUserProperty(QString name, QVariant value); @@ -22,7 +22,6 @@ public: void SetUserVectorProperty( QString name, QList<QVariant> values ); private: - }; #endif // VTKCOMPOSITECONTOURFILTER_H diff --git a/VtkVis/VtkCompositeFilter.cpp b/VtkVis/VtkCompositeFilter.cpp index f5ea0e86f0b0cccdb73227a97875bdddccdf86a8..22cdf0ef9c4af7b080ef21cca6e25d1ebbd787ca 100644 --- a/VtkVis/VtkCompositeFilter.cpp +++ b/VtkVis/VtkCompositeFilter.cpp @@ -1,7 +1,7 @@ /** * \file VtkCompositeFilter.cpp * 19/10/2010 LB Initial implementation - * + * * Implementation of VtkCompositeFilter class */ @@ -10,17 +10,17 @@ #include "VtkCompositeImageToCylindersFilter.h" -#include <QVector> -#include <QString> #include <QMapIterator> +#include <QString> +#include <QVector> VtkCompositeFilter::VtkCompositeFilter(vtkAlgorithm* inputAlgorithm) -: _inputDataObjectType(0), _outputDataObjectType(1), - _inputAlgorithm(inputAlgorithm) + : _inputDataObjectType(0), _outputDataObjectType(1), + _inputAlgorithm(inputAlgorithm) { } VtkCompositeFilter::~VtkCompositeFilter() { - _outputAlgorithm->Delete(); + _outputAlgorithm->Delete(); } diff --git a/VtkVis/VtkCompositeFilter.h b/VtkVis/VtkCompositeFilter.h index 9e50f4ecf6a1e69fb219f24402d34f99577b8aac..460b81e80defcfd5ed43003edf979f8be744f924 100644 --- a/VtkVis/VtkCompositeFilter.h +++ b/VtkVis/VtkCompositeFilter.h @@ -12,7 +12,7 @@ /// use vtk filter and custom filter. To subclass this you have to implement the /// init() function. There you combine the filters. Make sure to set the members /// _inputDataObjectType, _outputDataObjectType and _outputAlgorithm. Make also -/// sure to implement VtkAlgorithmProperties::SetUserProperty() and +/// sure to implement VtkAlgorithmProperties::SetUserProperty() and /// VtkAlgorithmProperties::SetUserVectorProperty(). /// /// Allocate vtk objects inside init() with vtkSmartPointer except for the last @@ -33,7 +33,7 @@ public: /// @brief Constructor. /// @param inputAlgorithm The algorithm to attach this filter to. VtkCompositeFilter(vtkAlgorithm* inputAlgorithm); - + /// @brief Destructor. virtual ~VtkCompositeFilter(); diff --git a/VtkVis/VtkCompositeImageToCylindersFilter.cpp b/VtkVis/VtkCompositeImageToCylindersFilter.cpp index b750545334845f4e92d4acc31d38044f4d1801f5..5cd54c57ff238bfcea687470034d93a4536a499e 100644 --- a/VtkVis/VtkCompositeImageToCylindersFilter.cpp +++ b/VtkVis/VtkCompositeImageToCylindersFilter.cpp @@ -1,29 +1,30 @@ /** * \file VtkCompositeImageToCylindersFilter.cpp * 19/10/2010 LB Initial implementation - * + * * Implementation of VtkCompositeImageToCylindersFilter class */ // ** INCLUDES ** #include "VtkCompositeImageToCylindersFilter.h" -#include "VtkImageDataToLinePolyDataFilter.h" #include "VtkApplyColorTableFilter.h" +#include "VtkImageDataToLinePolyDataFilter.h" #include <vtkLookupTable.h> +#include <vtkPointData.h> #include <vtkSmartPointer.h> -#include <vtkUnsignedCharArray.h> #include <vtkTubeFilter.h> -#include <vtkPointData.h> +#include <vtkUnsignedCharArray.h> #include <QMap> -#include <QVector> #include <QString> #include <QVariant> +#include <QVector> -VtkCompositeImageToCylindersFilter::VtkCompositeImageToCylindersFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) +VtkCompositeImageToCylindersFilter::VtkCompositeImageToCylindersFilter( + vtkAlgorithm* inputAlgorithm ) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -63,7 +64,6 @@ void VtkCompositeImageToCylindersFilter::init() _ctf->SetInputConnection(_lineFilter->GetOutputPort()); _ctf->SetColorLookupTable(colormap); - vtkTubeFilter* tubeFilter = vtkTubeFilter::New(); tubeFilter->SetInputConnection(_ctf->GetOutputPort()); tubeFilter->CappingOn(); @@ -86,27 +86,32 @@ void VtkCompositeImageToCylindersFilter::SetUserProperty( QString name, QVariant // VtkImageDataToLinePolyDataFilter is equal to _firstAlgorithm // vtkTubeFilter is equal _outputAlgorithm if (name.compare("NumberOfColors") == 0) - static_cast<vtkLookupTable*>(_ctf->GetColorLookupTable())->SetNumberOfTableValues(value.toInt()); + static_cast<vtkLookupTable*>(_ctf->GetColorLookupTable())->SetNumberOfTableValues( + value.toInt()); else if (name.compare("NumberOfSides") == 0) static_cast<vtkTubeFilter*>(_outputAlgorithm)->SetNumberOfSides(value.toInt()); else if (name.compare("Capping") == 0) static_cast<vtkTubeFilter*>(_outputAlgorithm)->SetCapping(value.toBool()); else if (name.compare("RadiusFactor") == 0) static_cast<vtkTubeFilter*>(_outputAlgorithm)->SetRadius( - _lineFilter->GetImageSpacing() * value.toDouble()); + _lineFilter->GetImageSpacing() * value.toDouble()); } -void VtkCompositeImageToCylindersFilter::SetUserVectorProperty( QString name, QList<QVariant> values ) +void VtkCompositeImageToCylindersFilter::SetUserVectorProperty( QString name, + QList<QVariant> values ) { VtkAlgorithmProperties::SetUserVectorProperty(name, values); _lineFilter->SetUserVectorProperty(name, values); if (name.compare("TableRange") == 0) - static_cast<vtkLookupTable*>(_ctf->GetColorLookupTable())->SetTableRange(values[0].toInt(), values[1].toInt()); + static_cast<vtkLookupTable*>(_ctf->GetColorLookupTable())->SetTableRange( + values[0].toInt(), + values[1].toInt()); else if (name.compare("HueRange") == 0) - static_cast<vtkLookupTable*>(_ctf->GetColorLookupTable())->SetHueRange(values[0].toDouble(), values[1].toDouble()); - + static_cast<vtkLookupTable*>(_ctf->GetColorLookupTable())->SetHueRange( + values[0].toDouble(), + values[1].toDouble()); } VtkCompositeImageToCylindersFilter::~VtkCompositeImageToCylindersFilter() diff --git a/VtkVis/VtkCompositeImageToCylindersFilter.h b/VtkVis/VtkCompositeImageToCylindersFilter.h index 4f2b8bd80bc76a3da055782d0786cd1407a2e1e0..0bb4e65b50afeb035fddd464047473ed107af32b 100644 --- a/VtkVis/VtkCompositeImageToCylindersFilter.h +++ b/VtkVis/VtkCompositeImageToCylindersFilter.h @@ -26,7 +26,6 @@ public: void SetUserVectorProperty( QString name, QList<QVariant> values ); - private: VtkImageDataToLinePolyDataFilter* _lineFilter; VtkApplyColorTableFilter* _ctf; diff --git a/VtkVis/VtkCompositeLineToTubeFilter.cpp b/VtkVis/VtkCompositeLineToTubeFilter.cpp index 289983bfefbf186d97dd3e11a83ec00d81c0a145..23f1cc51a9c330109c30924f05674d043182b3ad 100644 --- a/VtkVis/VtkCompositeLineToTubeFilter.cpp +++ b/VtkVis/VtkCompositeLineToTubeFilter.cpp @@ -1,20 +1,19 @@ /** * \file VtkCompositeLineToTubeFilter.cpp * 18/11/2010 KR Initial implementation - * + * * Implementation of VtkCompositeLineToTubeFilter class */ // ** INCLUDES ** #include "VtkCompositeLineToTubeFilter.h" -#include <vtkSmartPointer.h> #include <vtkCleanPolyData.h> +#include <vtkSmartPointer.h> #include <vtkTubeFilter.h> - VtkCompositeLineToTubeFilter::VtkCompositeLineToTubeFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -30,17 +29,17 @@ void VtkCompositeLineToTubeFilter::init() // collapse coincident points vtkSmartPointer<vtkCleanPolyData> mergePoints = vtkSmartPointer<vtkCleanPolyData>::New(); - mergePoints->SetInputConnection(0, _inputAlgorithm->GetOutputPort(0)); - mergePoints->SetTolerance(0.0); - mergePoints->ConvertLinesToPointsOn(); + mergePoints->SetInputConnection(0, _inputAlgorithm->GetOutputPort(0)); + mergePoints->SetTolerance(0.0); + mergePoints->ConvertLinesToPointsOn(); vtkTubeFilter* tubes = vtkTubeFilter::New(); - tubes->SetInputConnection(0, mergePoints->GetOutputPort(0)); - tubes->SetInputArrayToProcess(1,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS,"Stratigraphies"); - tubes->SetRadius(150); - tubes->SetNumberOfSides(10); - tubes->SetCapping(1); - //tubes->SetVaryRadiusToVaryRadiusByScalar(); // KR radius changes with scalar + tubes->SetInputConnection(0, mergePoints->GetOutputPort(0)); + tubes->SetInputArrayToProcess(1,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS,"Stratigraphies"); + tubes->SetRadius(150); + tubes->SetNumberOfSides(10); + tubes->SetCapping(1); + //tubes->SetVaryRadiusToVaryRadiusByScalar(); // KR radius changes with scalar (*_algorithmUserProperties)["Radius"] = 150.0; (*_algorithmUserProperties)["NumberOfSides"] = 6; diff --git a/VtkVis/VtkCompositeLineToTubeFilter.h b/VtkVis/VtkCompositeLineToTubeFilter.h index 9ebc68ef88897eba76208fec8f5c78c18f66ecd2..b91ec023216429e81428fa7b5c86b846345f5892 100644 --- a/VtkVis/VtkCompositeLineToTubeFilter.h +++ b/VtkVis/VtkCompositeLineToTubeFilter.h @@ -8,7 +8,6 @@ #include "VtkCompositeFilter.h" - /// @brief Converts lines to tube-objects. class VtkCompositeLineToTubeFilter : public VtkCompositeFilter { @@ -21,8 +20,6 @@ public: virtual void SetUserProperty(QString name, QVariant value); private: - - }; #endif // VTKCOMPOSITELINETOTUBEFILTER_H diff --git a/VtkVis/VtkCompositePointToGlyphFilter.cpp b/VtkVis/VtkCompositePointToGlyphFilter.cpp index fb58ffc573efda85aae64cda4737714f189859f0..eccd50978c08ececf634dd23990b8da945bf49cd 100644 --- a/VtkVis/VtkCompositePointToGlyphFilter.cpp +++ b/VtkVis/VtkCompositePointToGlyphFilter.cpp @@ -1,21 +1,20 @@ /** * \file VtkCompositePointToGlyphFilter.cpp * 21/10/2010 LB Initial implementation - * + * * Implementation of VtkCompositePointToGlyphFilter class */ // ** INCLUDES ** #include "VtkCompositePointToGlyphFilter.h" -#include <vtkSphereSource.h> -#include <vtkGlyph3D.h> #include <vtkDataSetAlgorithm.h> +#include <vtkGlyph3D.h> #include <vtkPointData.h> - +#include <vtkSphereSource.h> VtkCompositePointToGlyphFilter::VtkCompositePointToGlyphFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -37,19 +36,23 @@ void VtkCompositePointToGlyphFilter::init() _glyphSource->SetThetaResolution(10); (*_algorithmUserProperties)["Radius"] = default_radius; - size_t nPoints = static_cast<vtkDataSetAlgorithm*>(_inputAlgorithm)->GetOutput()->GetPointData()->GetNumberOfTuples(); - int phi = 10-static_cast<size_t>(nPoints / 2000.0); - int theta = 10-static_cast<size_t>(nPoints / 2000.0); - if (phi<4) phi=4; - if (theta<3) theta=3; + size_t nPoints = + static_cast<vtkDataSetAlgorithm*>(_inputAlgorithm)->GetOutput()->GetPointData()-> + GetNumberOfTuples(); + int phi = 10 - static_cast<size_t>(nPoints / 2000.0); + int theta = 10 - static_cast<size_t>(nPoints / 2000.0); + if (phi < 4) + phi = 4; + if (theta < 3) + theta = 3; (*_algorithmUserProperties)["PhiResolution"] = phi; (*_algorithmUserProperties)["ThetaResolution"] = theta; vtkGlyph3D* glyphFilter = vtkGlyph3D::New(); - glyphFilter->ScalingOn(); // KR important to scale glyphs with double precision (e.g. 0.1 of their size for small datasets) + glyphFilter->ScalingOn(); // KR important to scale glyphs with double precision (e.g. 0.1 of their size for small datasets) //glyphFilter->SetScaleModeToScaleByScalar(); // KR can easily obscure view when scalar values have large differences (this is also the default scaling method) - glyphFilter->SetScaleModeToDataScalingOff(); // KR scaling is possible but scalar values are ignored + glyphFilter->SetScaleModeToDataScalingOff(); // KR scaling is possible but scalar values are ignored glyphFilter->SetScaleFactor(1.0); glyphFilter->SetSource(_glyphSource->GetOutput()); glyphFilter->SetInputConnection(_inputAlgorithm->GetOutputPort()); diff --git a/VtkVis/VtkCompositePointToGlyphFilter.h b/VtkVis/VtkCompositePointToGlyphFilter.h index 47b298be89f6e5e3c67a610237011238d434ee83..5d6956defe94c2b55db038c8b7ed0ad18134b2e8 100644 --- a/VtkVis/VtkCompositePointToGlyphFilter.h +++ b/VtkVis/VtkCompositePointToGlyphFilter.h @@ -23,7 +23,6 @@ public: private: vtkSphereSource* _glyphSource; - }; #endif // VTKCOMPOSITEPOINTTOGLYPHFILTER_H diff --git a/VtkVis/VtkCompositeSelectionFilter.cpp b/VtkVis/VtkCompositeSelectionFilter.cpp index 55aa25eab853eb6fae2706304161b6df19e225b1..21d20f3e6b604ff9dba7c8427a3dfb671b774633 100644 --- a/VtkVis/VtkCompositeSelectionFilter.cpp +++ b/VtkVis/VtkCompositeSelectionFilter.cpp @@ -9,13 +9,13 @@ #include "VtkCompositeSelectionFilter.h" #include "VtkSelectionFilter.h" -#include <vtkSmartPointer.h> #include <vtkDataSetSurfaceFilter.h> -#include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> #include <vtkThreshold.h> +#include <vtkUnstructuredGrid.h> VtkCompositeSelectionFilter::VtkCompositeSelectionFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { //this->init(); } @@ -30,16 +30,16 @@ void VtkCompositeSelectionFilter::init() this->SetLookUpTable(QString(filter_name), this->GetLookupTable()); VtkSelectionFilter* selFilter = VtkSelectionFilter::New(); - selFilter->SetInputConnection(_inputAlgorithm->GetOutputPort()); - selFilter->SetSelectionArray(_selection, thresholdLower, thresholdUpper); - selFilter->Update(); + selFilter->SetInputConnection(_inputAlgorithm->GetOutputPort()); + selFilter->SetSelectionArray(_selection, thresholdLower, thresholdUpper); + selFilter->Update(); vtkThreshold* threshold = vtkThreshold::New(); - threshold->SetInputConnection(selFilter->GetOutputPort()); - threshold->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS, filter_name); - threshold->SetSelectedComponent(0); - threshold->ThresholdBetween(thresholdLower, thresholdUpper); - threshold->Update(); + threshold->SetInputConnection(selFilter->GetOutputPort()); + threshold->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS, filter_name); + threshold->SetSelectedComponent(0); + threshold->ThresholdBetween(thresholdLower, thresholdUpper); + threshold->Update(); QList<QVariant> thresholdRangeList; thresholdRangeList.push_back(0.0); @@ -54,17 +54,18 @@ void VtkCompositeSelectionFilter::SetUserVectorProperty( QString name, QList<QVa VtkAlgorithmProperties::SetUserVectorProperty(name, values); if (name.compare("Threshold Between") == 0) - static_cast<vtkThreshold*>(_outputAlgorithm)->ThresholdBetween(values[0].toDouble(), values[1].toDouble()); + static_cast<vtkThreshold*>(_outputAlgorithm)->ThresholdBetween( + values[0].toDouble(), values[1].toDouble()); } VtkColorLookupTable* VtkCompositeSelectionFilter::GetLookupTable() { VtkColorLookupTable* lut = VtkColorLookupTable::New(); lut->SetTableRange(0,1); - unsigned char a[4] = { 0, 0, 255, 255 }; // blue - unsigned char b[4] = { 0, 255, 0, 255 }; // green + unsigned char a[4] = { 0, 0, 255, 255 }; // blue + unsigned char b[4] = { 0, 255, 0, 255 }; // green unsigned char c[4] = { 255, 255, 0, 255 }; // yellow - unsigned char d[4] = { 255, 0, 0, 255 }; // red + unsigned char d[4] = { 255, 0, 0, 255 }; // red lut->setColor(1.0, a); lut->setColor(0.5, b); lut->setColor(0.25, c); diff --git a/VtkVis/VtkCompositeSelectionFilter.h b/VtkVis/VtkCompositeSelectionFilter.h index 59b518c25ce8d285a636eaa3919e3b96807d8105..45a33409e4381c3ae923daf75d2396ec85be89d0 100644 --- a/VtkVis/VtkCompositeSelectionFilter.h +++ b/VtkVis/VtkCompositeSelectionFilter.h @@ -13,11 +13,12 @@ class VtkCompositeSelectionFilter : public VtkCompositeFilter { public: VtkCompositeSelectionFilter(vtkAlgorithm* inputAlgorithm); - virtual ~VtkCompositeSelectionFilter() {}; + virtual ~VtkCompositeSelectionFilter() {} virtual void init(); - void setSelectionArray(std::vector<double> selection) { _selection = selection; init(); }; + void setSelectionArray(std::vector<double> selection) { _selection = selection; + init(); } virtual void SetUserVectorProperty(QString name, QList<QVariant> values); @@ -26,7 +27,6 @@ private: VtkColorLookupTable* GetLookupTable(); std::vector<double> _selection; - }; #endif // VTKCOMPOSITESELECTIONFILTER_H diff --git a/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp b/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp index c606a643ce4dceabb838797fd8ae5efbedcadab5..e2647f58855ba3d1e56388f637bb41b998759730 100644 --- a/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp +++ b/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp @@ -1,7 +1,7 @@ /** * \file VtkCompositeTextureOnSurfaceFilter.cpp * 18/11/2010 KR Initial implementation - * + * * Implementation of VtkCompositeTextureOnSurfaceFilter class */ @@ -18,9 +18,9 @@ #include <QFileInfo> #include <QSettings> - -VtkCompositeTextureOnSurfaceFilter::VtkCompositeTextureOnSurfaceFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) +VtkCompositeTextureOnSurfaceFilter::VtkCompositeTextureOnSurfaceFilter( + vtkAlgorithm* inputAlgorithm ) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -49,20 +49,23 @@ void VtkCompositeTextureOnSurfaceFilter::init() QWidget* parent = 0; QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName(parent, - "Select raster file to apply as texture", - settings.value("lastOpenedTextureFileDirectory").toString(), - "Raster files (*.asc *.bmp *.jpg *.png *.tif);;"); + "Select raster file to apply as texture", + settings.value( + "lastOpenedTextureFileDirectory"). + toString(), + "Raster files (*.asc *.bmp *.jpg *.png *.tif);;"); QFileInfo fi(fileName); - if ((fi.suffix().toLower() == "asc") || (fi.suffix().toLower() == "tif") || (fi.suffix().toLower() == "png") || - (fi.suffix().toLower() == "jpg") || (fi.suffix().toLower() == "bmp")) + if ((fi.suffix().toLower() == "asc") || (fi.suffix().toLower() == "tif") || + (fi.suffix().toLower() == "png") || + (fi.suffix().toLower() == "jpg") || (fi.suffix().toLower() == "bmp")) { QImage img; QPointF origin; - double scalingFactor=0; + double scalingFactor = 0; OGSRaster::loadImage(fileName, img, origin, scalingFactor); - std::pair<float, float> org(origin.x(), origin.y()); + std::pair<float, float> org(origin.x(), origin.y()); surface->SetRaster(img, org, scalingFactor); surface->Update(); @@ -70,7 +73,9 @@ void VtkCompositeTextureOnSurfaceFilter::init() settings.setValue("lastOpenedTextureFileDirectory", dir.absolutePath()); } else - std::cout << "VtkCompositeTextureOnSurfaceFilter.init() - Error reading texture file..." << std::endl; + std::cout << + "VtkCompositeTextureOnSurfaceFilter.init() - Error reading texture file..." << + std::endl; _outputAlgorithm = surface; } @@ -78,5 +83,4 @@ void VtkCompositeTextureOnSurfaceFilter::init() void VtkCompositeTextureOnSurfaceFilter::SetUserProperty( QString name, QVariant value ) { VtkAlgorithmProperties::SetUserProperty(name, value); - } diff --git a/VtkVis/VtkCompositeTextureOnSurfaceFilter.h b/VtkVis/VtkCompositeTextureOnSurfaceFilter.h index e0aade39f9484e6bee33204eca38553d006a4c9b..f269351f6b6b23f3ec068687dc8b5f472848c6a2 100644 --- a/VtkVis/VtkCompositeTextureOnSurfaceFilter.h +++ b/VtkVis/VtkCompositeTextureOnSurfaceFilter.h @@ -22,7 +22,6 @@ public: virtual void SetUserProperty(QString name, QVariant value); private: - }; #endif // VTKCOMPOSITETEXTUREONSURFACEFILTER_H diff --git a/VtkVis/VtkCompositeThresholdFilter.cpp b/VtkVis/VtkCompositeThresholdFilter.cpp index 42fad28893fab24503575b97ddc1f54ef36cd384..ebe174ac33d593696f8b109b0f21c03a88fc4d1a 100644 --- a/VtkVis/VtkCompositeThresholdFilter.cpp +++ b/VtkVis/VtkCompositeThresholdFilter.cpp @@ -1,22 +1,22 @@ /** * \file VtkCompositeThresholdFilter.cpp * 25/10/2010 LB Initial implementation - * + * * Implementation of VtkCompositeThresholdFilter class */ // ** INCLUDES ** #include "VtkCompositeThresholdFilter.h" +#include <vtkCellData.h> #include <vtkThreshold.h> #include <vtkUnstructuredGrid.h> -#include <vtkCellData.h> #include <vtkIntArray.h> #include <vtkSmartPointer.h> VtkCompositeThresholdFilter::VtkCompositeThresholdFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { this->init(); } @@ -45,10 +45,10 @@ void VtkCompositeThresholdFilter::init() // Sets a filter property which will be user editable threshold->SetSelectedComponent(0); - + // Sets a filter vector property which will be user editable threshold->ThresholdBetween(0, 100); - + // Create a list for the ThresholdBetween (vector) property. QList<QVariant> thresholdRangeList; // Insert the values (same values as above) @@ -56,10 +56,10 @@ void VtkCompositeThresholdFilter::init() thresholdRangeList.push_back(100); // Put that list in the property map (*_algorithmUserVectorProperties)["Threshold Between"] = thresholdRangeList; - + // Make a new entry in the property map for the SelectedComponent property (*_algorithmUserProperties)["Selected Component"] = 0; - + // The threshold filter is last one and so it is also the _outputAlgorithm _outputAlgorithm = threshold; } @@ -80,18 +80,17 @@ void VtkCompositeThresholdFilter::SetUserVectorProperty( QString name, QList<QVa // Use the same name as in init() if (name.compare("Threshold Between") == 0) - { //double* range = dynamic_cast<vtkUnstructuredGridAlgorithm*>(_outputAlgorithm)->GetOutput()->GetScalarRange(); //std::cout << range[0] << ", " << range[1] << std::endl; // Set the vector property on the algorithm - static_cast<vtkThreshold*>(_outputAlgorithm)->ThresholdBetween(values[0].toInt(), values[1].toInt()); - } + static_cast<vtkThreshold*>(_outputAlgorithm)->ThresholdBetween( + values[0].toInt(), values[1].toInt()); } /* -void VtkCompositeThresholdFilter::SetScalarRangeOnItem( double min, double max ) -{ - _item->SetScalarRange(min, max); - emit requestViewUpdate(); -} + void VtkCompositeThresholdFilter::SetScalarRangeOnItem( double min, double max ) + { + _item->SetScalarRange(min, max); + emit requestViewUpdate(); + } -*/ + */ diff --git a/VtkVis/VtkCompositeThresholdFilter.h b/VtkVis/VtkCompositeThresholdFilter.h index 6e54a40547f18d2b7e59ddffe4a9a2a8239cdad4..54bbc963a1f44be93376096c91d51ccc53dfb48d 100644 --- a/VtkVis/VtkCompositeThresholdFilter.h +++ b/VtkVis/VtkCompositeThresholdFilter.h @@ -14,7 +14,7 @@ class VtkCompositeThresholdFilter : public VtkCompositeFilter public: VtkCompositeThresholdFilter(vtkAlgorithm* inputAlgorithm); virtual ~VtkCompositeThresholdFilter(); - + virtual void init(); virtual void SetUserProperty(QString name, QVariant value); @@ -22,7 +22,6 @@ public: void SetUserVectorProperty( QString name, QList<QVariant> values ); private: - }; #endif // VTKCOMPOSITETHRESHOLDFILTER_H diff --git a/VtkVis/VtkConditionSource.cpp b/VtkVis/VtkConditionSource.cpp index 26b6336badca29784490afffdd301f08338f33a7..806cf644a295da3c28c5e7d539807b64a6cd460d 100644 --- a/VtkVis/VtkConditionSource.cpp +++ b/VtkVis/VtkConditionSource.cpp @@ -4,21 +4,21 @@ */ // ** INCLUDES ** -#include "VtkConditionSource.h" #include "AxisAlignedBoundingBox.h" #include "FEMCondition.h" +#include "VtkConditionSource.h" #include <vtkCellArray.h> #include <vtkDoubleArray.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> -#include <vtkSmartPointer.h> -#include <vtkStreamingDemandDrivenPipeline.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPolygon.h> +#include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> #include <vtkLookupTable.h> @@ -26,19 +26,20 @@ vtkStandardNewMacro(VtkConditionSource); vtkCxxRevisionMacro(VtkConditionSource, "$Revision$"); VtkConditionSource::VtkConditionSource() -: _points(NULL), _cond_vec(NULL) + : _points(NULL), _cond_vec(NULL) { this->SetNumberOfInputPorts(0); const GEOLIB::Color* c = GEOLIB::getRandomColor(); - GetProperties()->SetColor((*c)[0]/255.0,(*c)[1]/255.0,(*c)[2]/255.0); + GetProperties()->SetColor((*c)[0] / 255.0,(*c)[1] / 255.0,(*c)[2] / 255.0); } VtkConditionSource::~VtkConditionSource() { } -void VtkConditionSource::setData(const std::vector<GEOLIB::Point*>* points, const std::vector<FEMCondition*>* conds) +void VtkConditionSource::setData(const std::vector<GEOLIB::Point*>* points, + const std::vector<FEMCondition*>* conds) { _points = points; _cond_vec = conds; @@ -54,29 +55,34 @@ void VtkConditionSource::PrintSelf( ostream& os, vtkIndent indent ) os << indent << "== VtkConditionSource ==" << "\n"; } -int VtkConditionSource::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkConditionSource::RequestData( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; - if ( _points ) + if ( _points ) { if (_points->empty()) { - std::cout << "ERROR in VtkConditionSource::RequestData : Size of point vector is 0" << std::endl; + std::cout << + "ERROR in VtkConditionSource::RequestData : Size of point vector is 0" << + std::endl; return 0; } } - else return 0; - + else + return 0; vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); - vtkSmartPointer<vtkPolyData> output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkSmartPointer<vtkPolyData> output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkDoubleArray> scalars = vtkSmartPointer<vtkDoubleArray>::New(); - scalars->SetNumberOfComponents(1); - scalars->SetName("Scalars"); + scalars->SetNumberOfComponents(1); + scalars->SetName("Scalars"); //std::map<size_t, size_t> idx_map; vtkSmartPointer<vtkCellArray> newVerts = vtkSmartPointer<vtkCellArray>::New(); @@ -86,27 +92,25 @@ int VtkConditionSource::RequestData( vtkInformation* request, vtkInformationVect if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) return 1; - size_t n_pnts = _points->size(); double value(-9999); /* - if (!_cond_vec->empty()) - { - const std::vector<double> dv = (*_cond_vec)[0]->getDisValue(); - value = dv[dv.size()-1]; // get an existing value for the distribution so scaling on point data will be correct during rendering process! - } - */ - - for (size_t i=0; i<n_pnts; i++) + if (!_cond_vec->empty()) + { + const std::vector<double> dv = (*_cond_vec)[0]->getDisValue(); + value = dv[dv.size()-1]; // get an existing value for the distribution so scaling on point data will be correct during rendering process! + } + */ + + for (size_t i = 0; i < n_pnts; i++) { double coords[3] = {(*(*_points)[i])[0], (*(*_points)[i])[1], (*(*_points)[i])[2]}; newPoints->InsertNextPoint(coords); scalars->InsertNextValue(value); } - size_t nCond = _cond_vec->size(); - for (size_t n=0; n<nCond; n++) + for (size_t n = 0; n < nCond; n++) { FiniteElement::DistributionType type = (*_cond_vec)[n]->getProcessDistributionType(); const std::vector<double> dis_values = (*_cond_vec)[n]->getDisValue(); @@ -114,41 +118,44 @@ int VtkConditionSource::RequestData( vtkInformation* request, vtkInformationVect if ((*_cond_vec)[n]->getGeoType() == GEOLIB::POINT) { size_t nPoints = _points->size(); - const GEOLIB::Point* pnt = static_cast<const GEOLIB::Point*>((*_cond_vec)[n]->getGeoObj()); + const GEOLIB::Point* pnt = + static_cast<const GEOLIB::Point*>((*_cond_vec)[n]->getGeoObj()); int id(-1); - for (size_t i=0; i<nPoints; i++) - { - if ((*_points)[i] == pnt) + for (size_t i = 0; i < nPoints; i++) + if ((*_points)[i] == pnt) { - id = static_cast<int>(i);//(this->getIndex(i, newPoints, scalars, idx_map)); + id = static_cast<int>(i); //(this->getIndex(i, newPoints, scalars, idx_map)); vtkIdType vtk_id = static_cast<vtkIdType>(id); newVerts->InsertNextCell(1, &vtk_id); if (type == FiniteElement::CONSTANT) scalars->SetValue(id, dis_values[0]); break; } - } - if (id==-1) std::cout << "Error in VtkConditionSource::RequestData() - Point object not found ..." << std::endl; + if (id == -1) + std::cout << + "Error in VtkConditionSource::RequestData() - Point object not found ..." + << std::endl; } else if ((*_cond_vec)[n]->getGeoType() == GEOLIB::POLYLINE) { - const GEOLIB::Polyline* ply = static_cast<const GEOLIB::Polyline*>((*_cond_vec)[n]->getGeoObj()); + const GEOLIB::Polyline* ply = + static_cast<const GEOLIB::Polyline*>((*_cond_vec)[n]->getGeoObj()); const int nPoints = ply->getNumberOfPoints(); newLines->InsertNextCell(nPoints); for (int i = 0; i < nPoints; i++) { - size_t pnt_id = ply->getPointID(i);//this->getIndex(ply->getPointID(i), newPoints, scalars, idx_map); + size_t pnt_id = ply->getPointID(i); //this->getIndex(ply->getPointID(i), newPoints, scalars, idx_map); newLines->InsertCellPoint(pnt_id); if (type == FiniteElement::CONSTANT) scalars->SetValue(pnt_id, dis_values[0]); else if (type == FiniteElement::LINEAR) { - for (size_t j=0; j<dis_values.size(); j+=2) + for (size_t j = 0; j < dis_values.size(); j += 2) if (static_cast<size_t>(dis_values[j]) == pnt_id) //if (this->getIndex(static_cast<size_t>(dis_values[j]), newPoints, scalars, idx_map) == pnt_id) { - scalars->SetValue(pnt_id, dis_values[j+1]); + scalars->SetValue(pnt_id, dis_values[j + 1]); break; } } @@ -156,30 +163,33 @@ int VtkConditionSource::RequestData( vtkInformation* request, vtkInformationVect } else if ((*_cond_vec)[n]->getGeoType() == GEOLIB::SURFACE) { - const GEOLIB::Surface* sfc = static_cast<const GEOLIB::Surface*>((*_cond_vec)[n]->getGeoObj()); - + const GEOLIB::Surface* sfc = + static_cast<const GEOLIB::Surface*>((*_cond_vec)[n]->getGeoObj()); + const size_t nTriangles = sfc->getNTriangles(); - for (size_t i=0; i<nTriangles; i++) + for (size_t i = 0; i < nTriangles; i++) { vtkPolygon* aPolygon = vtkPolygon::New(); aPolygon->GetPointIds()->SetNumberOfIds(3); const GEOLIB::Triangle* triangle = (*sfc)[i]; - for (size_t j=0; j<3; j++) + for (size_t j = 0; j < 3; j++) { - size_t pnt_id = (*triangle)[j];//this->getIndex((*triangle)[j], newPoints, scalars, idx_map); + size_t pnt_id = (*triangle)[j]; //this->getIndex((*triangle)[j], newPoints, scalars, idx_map); aPolygon->GetPointIds()->SetId(j, pnt_id); if (type == FiniteElement::CONSTANT) scalars->SetValue(pnt_id, dis_values[0]); else if (type == FiniteElement::LINEAR) { - for (size_t k=0; k<dis_values.size(); k+=2) - if (static_cast<size_t>(dis_values[j]) == pnt_id) + for (size_t k = 0; k < dis_values.size(); k += 2) + if (static_cast<size_t>(dis_values[j]) == + pnt_id) //if (this->getIndex(static_cast<size_t>(dis_values[j]), newPoints, scalars, idx_map) == pnt_id) { - scalars->SetValue(pnt_id, dis_values[j+1]); + scalars->SetValue(pnt_id, + dis_values[j + 1]); break; } } @@ -200,19 +210,25 @@ int VtkConditionSource::RequestData( vtkInformation* request, vtkInformationVect vtkIdType nPoints = newPoints->GetNumberOfPoints(); //size_t pnt_idx = _points->size(); - for (size_t i=0; i<8; i++) + for (size_t i = 0; i < 8; i++) { - double coords[3] = {box[i%2][0], box[(i>>1)%2][1], box[i>>2][2]}; + double coords[3] = + {box[i % 2][0], box[(i >> 1) % 2][1], box[i >> 2][2]}; newPoints->InsertNextPoint(coords); scalars->InsertNextValue(0.0); //idx_map.insert( std::pair<size_t,size_t>(pnt_idx+i, nPoints+i)); } - - for (size_t i=0; i<4; i++) + + for (size_t i = 0; i < 4; i++) { - vtkIdType a[2] = {nPoints+i, nPoints+i+4}; - vtkIdType b[2] = {nPoints+(i*2), nPoints+(i*2+1)}; - vtkIdType c[2] = {nPoints+(static_cast<int>(i/2)*4+(i%2)), nPoints+(static_cast<int>(i/2)*4+(i%2)+2)}; + vtkIdType a[2] = {nPoints + i, nPoints + i + 4}; + vtkIdType b[2] = {nPoints + (i * 2), nPoints + (i * 2 + 1)}; + vtkIdType c[2] = + {nPoints + + (static_cast<int>(i / + 2) * 4 + + (i % + 2)), nPoints + (static_cast<int>(i / 2) * 4 + (i % 2) + 2)}; newLines->InsertNextCell(2, &a[0]); newLines->InsertNextCell(2, &b[0]); newLines->InsertNextCell(2, &c[0]); @@ -220,7 +236,6 @@ int VtkConditionSource::RequestData( vtkInformation* request, vtkInformationVect } } - output->SetPoints(newPoints); output->GetPointData()->AddArray(scalars); output->GetPointData()->SetActiveScalars("Scalars"); @@ -231,7 +246,9 @@ int VtkConditionSource::RequestData( vtkInformation* request, vtkInformationVect return 1; } -int VtkConditionSource::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkConditionSource::RequestInformation( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; @@ -249,17 +266,17 @@ void VtkConditionSource::SetUserProperty( QString name, QVariant value ) } /* -size_t VtkConditionSource::getIndex(size_t idx, vtkSmartPointer<vtkPoints> newPoints, vtkSmartPointer<vtkDoubleArray> scalars, std::map<size_t, size_t> &idx_map) -{ - std::map<size_t,size_t>::iterator mapped_index = idx_map.find(idx); - if (mapped_index != idx_map.end()) return mapped_index->second; - - double coords[3] = {(*(*_points)[idx])[0], (*(*_points)[idx])[1], (*(*_points)[idx])[2]}; - newPoints->InsertNextPoint(coords); - scalars->InsertNextValue(0.0); - size_t new_idx = idx_map.size(); - idx_map.insert( std::pair<size_t,size_t>(idx, new_idx) ); - std::cout << idx << ", " << new_idx << std::endl; - return new_idx; -} -*/ + size_t VtkConditionSource::getIndex(size_t idx, vtkSmartPointer<vtkPoints> newPoints, vtkSmartPointer<vtkDoubleArray> scalars, std::map<size_t, size_t> &idx_map) + { + std::map<size_t,size_t>::iterator mapped_index = idx_map.find(idx); + if (mapped_index != idx_map.end()) return mapped_index->second; + + double coords[3] = {(*(*_points)[idx])[0], (*(*_points)[idx])[1], (*(*_points)[idx])[2]}; + newPoints->InsertNextPoint(coords); + scalars->InsertNextValue(0.0); + size_t new_idx = idx_map.size(); + idx_map.insert( std::pair<size_t,size_t>(idx, new_idx) ); + std::cout << idx << ", " << new_idx << std::endl; + return new_idx; + } + */ diff --git a/VtkVis/VtkConditionSource.h b/VtkVis/VtkConditionSource.h index 1f4f0084f3edf8f87c4f68dfd57248969586cad1..75cdd5065eb71e943a5c0a513119f968a0e9ee72 100644 --- a/VtkVis/VtkConditionSource.h +++ b/VtkVis/VtkConditionSource.h @@ -4,13 +4,12 @@ * */ - #ifndef VTKCONDITIONSOURCE_H #define VTKCONDITIONSOURCE_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" +#include <vtkPolyDataAlgorithm.h> #include "GEOObjects.h" //#include <vtkSmartPointer.h> @@ -25,7 +24,6 @@ class FEMCondition; */ class VtkConditionSource : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkConditionSource* New(); @@ -33,7 +31,8 @@ public: vtkTypeRevisionMacro(VtkConditionSource,vtkPolyDataAlgorithm); /// Sets the FEMCondition that need to be visualised. The geometry points array is needed because polylines and surfaces are linked to this data. - void setData(const std::vector<GEOLIB::Point*>* points, const std::vector<FEMCondition*>* conds); + void setData(const std::vector<GEOLIB::Point*>* points, + const std::vector<FEMCondition*>* conds); /// Prints its data on a stream. void PrintSelf(ostream& os, vtkIndent indent); @@ -45,15 +44,19 @@ protected: ~VtkConditionSource(); /// Computes the polygonal data object. - int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); - int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestInformation(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); private: //size_t getIndex(size_t idx, vtkSmartPointer<vtkPoints> newPoints, vtkSmartPointer<vtkDoubleArray> scalars, std::map<size_t, size_t> &idx_map); const std::vector<GEOLIB::Point*>* _points; - const std::vector<FEMCondition*> *_cond_vec; + const std::vector<FEMCondition*>* _cond_vec; }; #endif // VTKCONDITIONSOURCE_H diff --git a/VtkVis/VtkFilterFactory.cpp b/VtkVis/VtkFilterFactory.cpp index 0122b8a77184449c8da8e2d83f83632498b8d54a..bcd9c656da1fd0b9fa9eb9ed4966e00c9b13f56d 100644 --- a/VtkVis/VtkFilterFactory.cpp +++ b/VtkVis/VtkFilterFactory.cpp @@ -1,103 +1,104 @@ /** * \file VtkFilterFactory.cpp * 20/10/2010 LB Initial implementation - * + * * Implementation of VtkFilterFactory class */ // ** INCLUDES ** #include "VtkFilterFactory.h" +#include "VtkCompositeColorByHeightFilter.h" +#include "VtkCompositeColormapToImageFilter.h" +#include "VtkCompositeContourFilter.h" #include "VtkCompositeImageToCylindersFilter.h" -#include "VtkImageDataToLinePolyDataFilter.h" -#include "VtkCompositePointToGlyphFilter.h" #include "VtkCompositeLineToTubeFilter.h" -#include "VtkCompositeColormapToImageFilter.h" +#include "VtkCompositePointToGlyphFilter.h" +#include "VtkCompositeSelectionFilter.h" #include "VtkCompositeTextureOnSurfaceFilter.h" #include "VtkCompositeThresholdFilter.h" -#include "VtkCompositeColorByHeightFilter.h" -#include "VtkCompositeSelectionFilter.h" -#include "VtkCompositeContourFilter.h" +#include "VtkImageDataToLinePolyDataFilter.h" #include <vtkDataSetSurfaceFilter.h> const QVector<VtkFilterInfo> VtkFilterFactory::GetFilterList() { QVector<VtkFilterInfo> filterList; - + // Composite filters filterList.push_back(VtkFilterInfo( - "VtkCompositeImageToCylindersFilter", - "Image to bar chart", - "This filter converts the red pixel values of the image into a bar graph.", - VTK_IMAGE_DATA, VTK_POLY_DATA)); + "VtkCompositeImageToCylindersFilter", + "Image to bar chart", + "This filter converts the red pixel values of the image into a bar graph.", + VTK_IMAGE_DATA, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositePointToGlyphFilter", - "Points to spheres", - "This filter generates spheres on point data that can be scaled and colored by scalar data.", - VTK_POLY_DATA, VTK_POLY_DATA)); + "VtkCompositePointToGlyphFilter", + "Points to spheres", + "This filter generates spheres on point data that can be scaled and colored by scalar data.", + VTK_POLY_DATA, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeLineToTubeFilter", - "Lines to tubes", - "This filter will convert lines to tubes that can be colored by scalar data.", - VTK_POLY_DATA, VTK_POLY_DATA)); + "VtkCompositeLineToTubeFilter", + "Lines to tubes", + "This filter will convert lines to tubes that can be colored by scalar data.", + VTK_POLY_DATA, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeColormapToImageFilter", - "Apply lookup table to image", - "This filter will take an input image of any valid scalar type, and map the first component of the image through a lookup table.", - VTK_IMAGE_DATA, VTK_IMAGE_DATA)); + "VtkCompositeColormapToImageFilter", + "Apply lookup table to image", + "This filter will take an input image of any valid scalar type, and map the first component of the image through a lookup table.", + VTK_IMAGE_DATA, VTK_IMAGE_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeTextureOnSurfaceFilter", - "Apply texture to surface", - "This filter assigns an image or raster file as a texture for the given surface.", - VTK_POINT_SET, VTK_POLY_DATA)); + "VtkCompositeTextureOnSurfaceFilter", + "Apply texture to surface", + "This filter assigns an image or raster file as a texture for the given surface.", + VTK_POINT_SET, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeThresholdFilter", - "Extract cells by threshold", - "This filter extracts cells from any dataset type that satisfy a threshold criterion. A cell satisfies the criterion if the (first) scalar value of (every or any) point satisfies the criterion. For example this can be used to show only certain material groups in a mesh.", - VTK_POINT_SET, VTK_UNSTRUCTURED_GRID)); + "VtkCompositeThresholdFilter", + "Extract cells by threshold", + "This filter extracts cells from any dataset type that satisfy a threshold criterion. A cell satisfies the criterion if the (first) scalar value of (every or any) point satisfies the criterion. For example this can be used to show only certain material groups in a mesh.", + VTK_POINT_SET, VTK_UNSTRUCTURED_GRID)); filterList.push_back(VtkFilterInfo( - "VtkCompositeColorByHeightFilter", - "Elevation-based colouring", - "This filter will generate scalar values based on the elevation of each point in the dataset.", - VTK_POINT_SET, VTK_POLY_DATA)); + "VtkCompositeColorByHeightFilter", + "Elevation-based colouring", + "This filter will generate scalar values based on the elevation of each point in the dataset.", + VTK_POINT_SET, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeContourFilter", - "Generate contours based on scalar fields", - "Visualisation of contour-lines/-planes within dense scalar fields.", - VTK_UNSTRUCTURED_GRID, VTK_UNSTRUCTURED_GRID)); + "VtkCompositeContourFilter", + "Generate contours based on scalar fields", + "Visualisation of contour-lines/-planes within dense scalar fields.", + VTK_UNSTRUCTURED_GRID, VTK_UNSTRUCTURED_GRID)); // Simple filters filterList.push_back(VtkFilterInfo( - "VtkImageDataToLinePolyDataFilter", - "Image to vertical lines", - "This filter converts the red pixel values of the image to lines with length of the value.", - VTK_IMAGE_DATA, VTK_POLY_DATA)); + "VtkImageDataToLinePolyDataFilter", + "Image to vertical lines", + "This filter converts the red pixel values of the image to lines with length of the value.", + VTK_IMAGE_DATA, VTK_POLY_DATA)); // Standard VTK filter without properties filterList.push_back(VtkFilterInfo( - "vtkDataSetSurfaceFilter", - "Surface filter", - "Extracts outer (polygonal) surface.", - VTK_UNSTRUCTURED_GRID, VTK_POLY_DATA)); + "vtkDataSetSurfaceFilter", + "Surface filter", + "Extracts outer (polygonal) surface.", + VTK_UNSTRUCTURED_GRID, VTK_POLY_DATA)); -// filterList.push_back(VtkFilterInfo( -// "VtkCompositeSelectionFilter", -// "Mesh Quality Filter", -// "This filter calculates the quality of meshes and highlights deformed elements.", -// VTK_UNSTRUCTURED_GRID, VTK_UNSTRUCTURED_GRID)); +// filterList.push_back(VtkFilterInfo( +// "VtkCompositeSelectionFilter", +// "Mesh Quality Filter", +// "This filter calculates the quality of meshes and highlights deformed elements.", +// VTK_UNSTRUCTURED_GRID, VTK_UNSTRUCTURED_GRID)); return filterList; } -VtkCompositeFilter* VtkFilterFactory::CreateCompositeFilter( QString type, vtkAlgorithm* inputAlgorithm ) +VtkCompositeFilter* VtkFilterFactory::CreateCompositeFilter( QString type, + vtkAlgorithm* inputAlgorithm ) { if (type.compare(QString("VtkCompositeImageToCylindersFilter")) == 0) return new VtkCompositeImageToCylindersFilter(inputAlgorithm); @@ -118,7 +119,8 @@ VtkCompositeFilter* VtkFilterFactory::CreateCompositeFilter( QString type, vtkAl else if (type.compare(QString("VtkCompositeContourFilter")) == 0) return new VtkCompositeContourFilter(inputAlgorithm); - else return NULL; + else + return NULL; } vtkAlgorithm* VtkFilterFactory::CreateSimpleFilter( QString type ) @@ -127,6 +129,6 @@ vtkAlgorithm* VtkFilterFactory::CreateSimpleFilter( QString type ) return VtkImageDataToLinePolyDataFilter::New(); if (type.compare(QString("vtkDataSetSurfaceFilter")) == 0) return vtkDataSetSurfaceFilter::New(); - + return NULL; } diff --git a/VtkVis/VtkFilterFactory.h b/VtkVis/VtkFilterFactory.h index aa625990afac4025a5dd3d5fc7b5026079f07693..1c5f093fca9ad8cbb51ed9de9b567cb4f67fbcfe 100644 --- a/VtkVis/VtkFilterFactory.h +++ b/VtkVis/VtkFilterFactory.h @@ -6,8 +6,8 @@ #ifndef VTKFILTERFACTORY_H #define VTKFILTERFACTORY_H -#include <QVector> #include <QString> +#include <QVector> #include <vtkSetGet.h> class VtkCompositeFilter; @@ -31,11 +31,10 @@ public: /// @brief Creates a normal filter name. static vtkAlgorithm* CreateSimpleFilter(QString type); - }; /// @brief Holds meta information about a filter -struct VtkFilterInfo +struct VtkFilterInfo { /// @brief Constructor. /// @param name The name of the filter (the class name) @@ -44,7 +43,7 @@ struct VtkFilterInfo /// @param inputDataObjectType The input data type (see OutputDataObjectTypeAsString()) /// @param outputDataObjectType The output data type (see OutputDataObjectTypeAsString()) VtkFilterInfo(QString name, QString readableName, QString description, - int inputDataObjectType, int outputDataObjectType) + int inputDataObjectType, int outputDataObjectType) { this->name = name; this->readableName = readableName; @@ -52,7 +51,7 @@ struct VtkFilterInfo this->inputDataObjectType = inputDataObjectType; this->outputDataObjectType = outputDataObjectType; } - + /// @brief Default constructor. VtkFilterInfo() { @@ -77,7 +76,6 @@ struct VtkFilterInfo case VTK_DATA_SET: return QString("vtkDataSet"); default: return QString("Data type not defined!"); } - } QString name; diff --git a/VtkVis/VtkGeoImageSource.cpp b/VtkVis/VtkGeoImageSource.cpp index 30abb215279cd3c2e1fc36094f5dd948e1d2f18c..22fa8a204615e0920a3059361dade43b26f3cc78 100644 --- a/VtkVis/VtkGeoImageSource.cpp +++ b/VtkVis/VtkGeoImageSource.cpp @@ -1,7 +1,7 @@ /** * \file VtkGeoImageSource.cpp * 28/09/2010 LB Initial implementation - * + * * Implementation of VtkGeoImageSource class */ @@ -10,17 +10,17 @@ #include "OGSRaster.h" -#include <vtkObjectFactory.h> -#include <vtkQImageToImageSource.h> +#include <vtkFloatArray.h> #include <vtkImageChangeInformation.h> -#include <vtkImageShiftScale.h> #include <vtkImageData.h> -#include <vtkFloatArray.h> +#include <vtkImageShiftScale.h> +#include <vtkObjectFactory.h> #include <vtkPointData.h> +#include <vtkQImageToImageSource.h> -#include <QString> -#include <QPointF> #include <QImage> +#include <QPointF> +#include <QString> vtkStandardNewMacro(VtkGeoImageSource); @@ -39,14 +39,14 @@ void vtkSimpleImageFilterExampleExecute(vtkImageData* input, input->GetDimensions(dims); if (input->GetScalarType() != output->GetScalarType()) { - vtkGenericWarningMacro(<< "Execute: input ScalarType, " << input->GetScalarType() - << ", must match out ScalarType " << output->GetScalarType()); + vtkGenericWarningMacro(<< "Execute: input ScalarType, " << input->GetScalarType() + << ", must match out ScalarType " << output->GetScalarType()); return; } // HACK LB Multiply by number of scalar components due to RGBA values ????? - int size = dims[0]*dims[1]*dims[2]*input->GetNumberOfScalarComponents(); + int size = dims[0] * dims[1] * dims[2] * input->GetNumberOfScalarComponents(); - for(int i=0; i<size; i++) + for(int i = 0; i < size; i++) outPtr[i] = inPtr[i]; } @@ -55,7 +55,7 @@ VtkGeoImageSource::VtkGeoImageSource() _imageSource = vtkQImageToImageSource::New(); _imageInfo = vtkImageChangeInformation::New(); _imageShift = vtkImageShiftScale::New(); - + _imageInfo->SetInputConnection(_imageSource->GetOutputPort()); _imageShift->SetInputConnection(_imageInfo->GetOutputPort()); _imageShift->SetOutputScalarTypeToUnsignedChar(); @@ -133,46 +133,46 @@ void VtkGeoImageSource::SimpleExecute(vtkImageData* input, vtkImageData* output) // This is simply a #define for a big case list. // It handles all data types that VTK supports. vtkTemplateMacro(vtkSimpleImageFilterExampleExecute( - input, output, (VTK_TT*)(inPtr), (VTK_TT*)(outPtr))); - default: - vtkGenericWarningMacro("Execute: Unknown input ScalarType"); - return; + input, output, (VTK_TT*)(inPtr), (VTK_TT*)(outPtr))); + default: + vtkGenericWarningMacro("Execute: Unknown input ScalarType"); + return; } /* - // Create normals - vtkFloatArray* normals = vtkFloatArray::New(); - int numPoints = input->GetNumberOfPoints(); - normals->SetNumberOfComponents(3); - normals->Allocate(3*numPoints); - float normal[3] = {0.f, 0.f, 1.f}; - - // vector data - std::cout << input->GetScalarTypeAsString() << std::endl; - vtkFloatArray* vectors = vtkFloatArray::New(); - vectors->SetNumberOfComponents(3); - vectors->Allocate(3*numPoints); - int numScalarComponents = input->GetNumberOfScalarComponents(); - - for (int i = 0; i < numPoints; i++) - { - normals->InsertTuple(i, normal); - float vector[3]; - vector[0] = 1; - vector[1] = 1; - vector[2] = ((unsigned char*)inPtr)[i * numScalarComponents] * 0.1; - //std::cout << vector[2] << " "; - vectors->InsertTuple(i, vector); - } - - normals->SetName("Normals"); - output->GetPointData()->SetNormals(normals); - normals->Delete(); - - vectors->SetName("Vectors"); - output->GetPointData()->SetVectors(vectors); - vectors->Delete(); -*/ + // Create normals + vtkFloatArray* normals = vtkFloatArray::New(); + int numPoints = input->GetNumberOfPoints(); + normals->SetNumberOfComponents(3); + normals->Allocate(3*numPoints); + float normal[3] = {0.f, 0.f, 1.f}; + + // vector data + std::cout << input->GetScalarTypeAsString() << std::endl; + vtkFloatArray* vectors = vtkFloatArray::New(); + vectors->SetNumberOfComponents(3); + vectors->Allocate(3*numPoints); + int numScalarComponents = input->GetNumberOfScalarComponents(); + + for (int i = 0; i < numPoints; i++) + { + normals->InsertTuple(i, normal); + float vector[3]; + vector[0] = 1; + vector[1] = 1; + vector[2] = ((unsigned char*)inPtr)[i * numScalarComponents] * 0.1; + //std::cout << vector[2] << " "; + vectors->InsertTuple(i, vector); + } + + normals->SetName("Normals"); + output->GetPointData()->SetNormals(normals); + normals->Delete(); + + vectors->SetName("Vectors"); + output->GetPointData()->SetVectors(vectors); + vectors->Delete(); + */ } void VtkGeoImageSource::SetUserProperty( QString name, QVariant value ) diff --git a/VtkVis/VtkGeoImageSource.h b/VtkVis/VtkGeoImageSource.h index e7df4e19f4525180fcab096aeff4e4aa55c58fe8..1338488a92f1069c9c4187bff50658f054a41368 100644 --- a/VtkVis/VtkGeoImageSource.h +++ b/VtkVis/VtkGeoImageSource.h @@ -6,8 +6,8 @@ #ifndef VTKGEOIMAGESOURCE_H #define VTKGEOIMAGESOURCE_H -#include <vtkSimpleImageToImageFilter.h> #include "VtkAlgorithmProperties.h" +#include <vtkSimpleImageToImageFilter.h> class QString; class QPointF; @@ -27,7 +27,7 @@ public: /// @brief Prints information about itself. void PrintSelf(ostream& os, vtkIndent indent); - + vtkImageData* getImageData(); std::pair<double, double> getOrigin(); @@ -35,11 +35,11 @@ public: double getSpacing(); void setImageFilename(QString filename); - + void setImage(QImage& image); - + void setOrigin(QPointF origin); - + void setSpacing(double spacing); virtual void SetUserProperty(QString name, QVariant value); @@ -50,14 +50,14 @@ protected: /// @brief Destructor. virtual ~VtkGeoImageSource(); - + /// @brief Filter execution. virtual void SimpleExecute(vtkImageData* input, vtkImageData* output); private: - VtkGeoImageSource(const VtkGeoImageSource&); // Not implemented. - void operator=(const VtkGeoImageSource&); // Not implemented - + VtkGeoImageSource(const VtkGeoImageSource&); // Not implemented. + void operator=(const VtkGeoImageSource&); // Not implemented + vtkQImageToImageSource* _imageSource; vtkImageChangeInformation* _imageInfo; vtkImageShiftScale* _imageShift; diff --git a/VtkVis/VtkImageDataToLinePolyDataFilter.cpp b/VtkVis/VtkImageDataToLinePolyDataFilter.cpp index b6e47ea91fac11204502dfac14683239eac8cad1..5a2b79485f6ad71774058f53788bddc02eab1b99 100644 --- a/VtkVis/VtkImageDataToLinePolyDataFilter.cpp +++ b/VtkVis/VtkImageDataToLinePolyDataFilter.cpp @@ -1,22 +1,22 @@ /** * \file VtkImageDataToLinePolyDataFilter.cpp * 06/10/2010 LB Initial implementation - * + * * Implementation of VtkImageDataToLinePolyDataFilter class */ // ** INCLUDES ** #include "VtkImageDataToLinePolyDataFilter.h" -#include <vtkObjectFactory.h> +#include <vtkIdList.h> +#include <vtkImageData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> +#include <vtkLine.h> +#include <vtkObjectFactory.h> +#include <vtkPointData.h> #include <vtkPolyData.h> -#include <vtkImageData.h> #include <vtkSmartPointer.h> -#include <vtkIdList.h> -#include <vtkPointData.h> -#include <vtkLine.h> vtkStandardNewMacro(VtkImageDataToLinePolyDataFilter); @@ -42,21 +42,22 @@ int VtkImageDataToLinePolyDataFilter::FillInputPortInformation(int, vtkInformati } int VtkImageDataToLinePolyDataFilter::RequestData(vtkInformation*, - vtkInformationVector** inputVector, vtkInformationVector* outputVector) + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { vtkDebugMacro(<< "Executing VtkImageDataToPolyDataFilter"); - + vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkImageData* input = vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - + void* inScalarPtr = input->GetScalarPointer(); int numScalarComponents = input->GetNumberOfScalarComponents(); double spacing[3]; input->GetSpacing(spacing); - this->ImageSpacing = spacing[0]; - + this->ImageSpacing = spacing[0]; + // Skip execution if there are no points vtkIdType numPts = input->GetNumberOfPoints(); if (numPts < 1) @@ -64,76 +65,75 @@ int VtkImageDataToLinePolyDataFilter::RequestData(vtkInformation*, vtkDebugMacro("No data to extract lines!"); return 1; } - + // Allocate memory for olds and new cell point lists vtkSmartPointer<vtkIdList> ptIds = vtkSmartPointer<vtkIdList>::New(); ptIds->Allocate(VTK_CELL_SIZE); vtkSmartPointer<vtkIdList> newPtIds = vtkSmartPointer<vtkIdList>::New(); newPtIds->Allocate(VTK_CELL_SIZE); - + // Allocate the space needed for the output cells. output->Allocate(numPts); - + // Allocate space for a new set of points vtkSmartPointer<vtkPoints> newPts = vtkSmartPointer<vtkPoints>::New(); newPts->Allocate(numPts * 2, numPts); - + // Allocate space for the data associated with the new set of points vtkPointData* inPD = input->GetPointData(); vtkPointData* outPD = output->GetPointData(); outPD->CopyAllocate(inPD, numPts * 16, numPts); - + double dir[3] = {0, 0, 1}; - + // Traverse all points creating another point with scalar distance in Z direction for (vtkIdType ptId = 0; ptId < numPts; ++ptId) { // Compute length of the new line (scalar * LengthScaleFactor) float length = ((unsigned char*)inScalarPtr)[ptId * numScalarComponents] - * this->LengthScaleFactor; + * this->LengthScaleFactor; //float length = (((unsigned char*)inScalarPtr)[ptId * numScalarComponents]* this->LengthScaleFactor > 50000) ? 50000 : ((unsigned char*)inScalarPtr)[ptId * numScalarComponents]* this->LengthScaleFactor; - // Skip this line if length is zero if (length < 0.00000001f) continue; - + // Get the old point location double p[3]; input->GetPoint(ptId, p); - + // Compute the new point location double newPt[3]; for(size_t i = 0; i < 3; ++i) newPt[i] = p[i] + dir[i] * length; - + // Copy the old point vtkIdType newOldId = newPts->InsertNextPoint(p); newPtIds->InsertId(ptId * 2, ptId); outPD->CopyData(inPD, ptId, newOldId); - + // Create the new point vtkIdType newId = newPts->InsertNextPoint(newPt); newPtIds->InsertId(ptId * 2 + 1, newId); outPD->CopyData(inPD, ptId, newId); - + // Create the line vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New(); line->GetPointIds()->SetId(0, newOldId); line->GetPointIds()->SetId(1, newId); output->InsertNextCell(line->GetCellType(), line->GetPointIds()); } - + // Store the new set of points in the output output->SetPoints(newPts); output->GetPointData()->GetArray(0)->SetName("Colours"); // Avoid keeping extra memory around output->Squeeze(); - + vtkDebugMacro(<< "Created: " - << newPts->GetNumberOfPoints() << " points, " - << output->GetNumberOfCells() << " lines"); - + << newPts->GetNumberOfPoints() << " points, " + << output->GetNumberOfCells() << " lines"); + return 1; } diff --git a/VtkVis/VtkImageDataToLinePolyDataFilter.h b/VtkVis/VtkImageDataToLinePolyDataFilter.h index 8d67f84393bbffdf7333ef6d4f133f099ff284db..18792b5d1999ddca8f57f4b66725b6eb608c137e 100644 --- a/VtkVis/VtkImageDataToLinePolyDataFilter.h +++ b/VtkVis/VtkImageDataToLinePolyDataFilter.h @@ -6,8 +6,8 @@ #ifndef VTKIMAGEDATATOLINEPOLYDATAFILTER_H #define VTKIMAGEDATATOLINEPOLYDATAFILTER_H -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" +#include <vtkPolyDataAlgorithm.h> class vtkInformation; class vtkInformationVector; @@ -25,7 +25,7 @@ public: /// @brief Prints information about itself. void PrintSelf(ostream& os, vtkIndent indent); - + /// @brief Sets the scaling of the length of the lines. ogsUserPropertyMacro(LengthScaleFactor,double); @@ -45,20 +45,20 @@ protected: /// @brief Destructor. virtual ~VtkImageDataToLinePolyDataFilter(); - + /// @brief Sets input port to vtkImageData. virtual int FillInputPortInformation(int port, vtkInformation* info); - + /// @brief Converts the image data to lines virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, - vtkInformationVector* outputVector); - + vtkInformationVector* outputVector); + /// @brief The spacing of the image double ImageSpacing; private: - VtkImageDataToLinePolyDataFilter(const VtkImageDataToLinePolyDataFilter&); // Not implemented. - void operator=(const VtkImageDataToLinePolyDataFilter&); // Not implemented + VtkImageDataToLinePolyDataFilter(const VtkImageDataToLinePolyDataFilter&); // Not implemented. + void operator=(const VtkImageDataToLinePolyDataFilter&); // Not implemented }; #endif // VTKIMAGEDATATOLINEPOLYDATAFILTER_H diff --git a/VtkVis/VtkMeshConverter.cpp b/VtkVis/VtkMeshConverter.cpp index eb547774c0b56b8959b13350f375c27d99f3e062..70e2efe9ce9e9a51d341db1e3c40f6d40b1905d3 100644 --- a/VtkVis/VtkMeshConverter.cpp +++ b/VtkVis/VtkMeshConverter.cpp @@ -15,52 +15,55 @@ #include <vtkUnsignedCharArray.h> // Conversion from vtkUnstructuredGrid -#include <vtkUnstructuredGrid.h> #include <vtkCell.h> #include <vtkCellData.h> +#include <vtkUnstructuredGrid.h> -MeshLib::CFEMesh* VtkMeshConverter::convertImgToMesh(vtkImageData* img, const std::pair<double,double> &origin, const double &scalingFactor) +MeshLib::CFEMesh* VtkMeshConverter::convertImgToMesh(vtkImageData* img, + const std::pair<double,double> &origin, + const double &scalingFactor) { - vtkSmartPointer<vtkUnsignedCharArray> pixelData = vtkSmartPointer<vtkUnsignedCharArray>(vtkUnsignedCharArray::SafeDownCast(img->GetPointData()->GetScalars())); + vtkSmartPointer<vtkUnsignedCharArray> pixelData = vtkSmartPointer<vtkUnsignedCharArray>( + vtkUnsignedCharArray::SafeDownCast(img->GetPointData()->GetScalars())); int* dims = img->GetDimensions(); MeshLib::CFEMesh* mesh(new MeshLib::CFEMesh()); size_t imgHeight = dims[0]; size_t imgWidth = dims[1]; - std::vector<size_t> visNodes(imgWidth*imgHeight); + std::vector<size_t> visNodes(imgWidth * imgHeight); - for (size_t i=0; i<imgWidth; i++) - { - for (size_t j=0; j<imgHeight; j++) + for (size_t i = 0; i < imgWidth; i++) + for (size_t j = 0; j < imgHeight; j++) { - size_t index = i*imgHeight+j; + size_t index = i * imgHeight + j; const double* colour = pixelData->GetTuple4(index); - double pixcol = 0.3*colour[0] + 0.6*colour[1] + 0.1*colour[2]; - double coords[3] = { origin.first+(scalingFactor*j), origin.second+(scalingFactor*i), pixcol }; - visNodes[index] = (colour[3]>0); + double pixcol = 0.3 * colour[0] + 0.6 * colour[1] + 0.1 * colour[2]; + double coords[3] = + { origin.first + (scalingFactor * j), origin.second + (scalingFactor * i), + pixcol }; + visNodes[index] = (colour[3] > 0); MeshLib::CNode* node(new MeshLib::CNode(index)); node->SetCoordinates(coords); mesh->nod_vector.push_back(node); } - } // set mesh elements - for (size_t i=0; i<imgWidth-1; i++) - { - for (size_t j=0; j<imgHeight-1; j++) + for (size_t i = 0; i < imgWidth - 1; i++) + for (size_t j = 0; j < imgHeight - 1; j++) { - int index = i*imgHeight+j; + int index = i * imgHeight + j; // if node is visible if (visNodes[index]) { - - mesh->ele_vector.push_back(createElement(index, index+1, index+imgHeight)); // upper left triangle - mesh->ele_vector.push_back(createElement(index+1, index+imgHeight+1, index+imgHeight)); // lower right triangle + mesh->ele_vector.push_back(createElement(index, index + 1, index + + imgHeight)); // upper left triangle + mesh->ele_vector.push_back(createElement(index + 1, index + + imgHeight + 1, index + + imgHeight)); // lower right triangle } } - } mesh->ConstructGrid(); return mesh; } @@ -80,7 +83,8 @@ MeshLib::CElem* VtkMeshConverter::createElement(size_t node1, size_t node2, size MeshLib::CFEMesh* VtkMeshConverter::convertUnstructuredGrid(vtkUnstructuredGrid* grid) { - if (!grid) return NULL; + if (!grid) + return NULL; MeshLib::CFEMesh* mesh(new MeshLib::CFEMesh()); @@ -89,7 +93,7 @@ MeshLib::CFEMesh* VtkMeshConverter::convertUnstructuredGrid(vtkUnstructuredGrid* // set mesh nodes double* coords = NULL; - for (size_t i=0; i<nNodes; i++) + for (size_t i = 0; i < nNodes; i++) { coords = grid->GetPoints()->GetPoint(i); MeshLib::CNode* node(new MeshLib::CNode(i, coords[0], coords[1], coords[2])); @@ -99,7 +103,7 @@ MeshLib::CFEMesh* VtkMeshConverter::convertUnstructuredGrid(vtkUnstructuredGrid* // set mesh elements vtkCell* cell(NULL); vtkDataArray* scalars = grid->GetCellData()->GetScalars("MaterialIDs"); - for (size_t i=0; i<nElems; i++) + for (size_t i = 0; i < nElems; i++) { MeshLib::CElem* elem(new MeshLib::CElem()); @@ -108,22 +112,30 @@ MeshLib::CFEMesh* VtkMeshConverter::convertUnstructuredGrid(vtkUnstructuredGrid* switch (cell_type) { - case VTK_TRIANGLE: elem_type=MshElemType::TRIANGLE; break; - case VTK_QUAD: elem_type=MshElemType::QUAD; break; - case VTK_TETRA: elem_type=MshElemType::TETRAHEDRON; break; - case VTK_HEXAHEDRON: elem_type=MshElemType::HEXAHEDRON; break; - case VTK_WEDGE: elem_type=MshElemType::PRISM; break; + case VTK_TRIANGLE: elem_type = MshElemType::TRIANGLE; + break; + case VTK_QUAD: elem_type = MshElemType::QUAD; + break; + case VTK_TETRA: elem_type = MshElemType::TETRAHEDRON; + break; + case VTK_HEXAHEDRON: elem_type = MshElemType::HEXAHEDRON; + break; + case VTK_WEDGE: elem_type = MshElemType::PRISM; + break; } if (elem_type != MshElemType::INVALID) { //elem->SetElementType(elem_type); elem->setElementProperties(elem_type); - if (scalars) elem->SetPatchIndex(static_cast<int>(scalars->GetComponent(i,0))); // HACK the name of the correct scalar array of the vtk file should probably be passed as an argument?! + if (scalars) + elem->SetPatchIndex(static_cast<int>(scalars->GetComponent(i,0))); // HACK the name of the correct scalar array of the vtk file should probably be passed as an argument?! } else { - std::cout << "Error in GridAdapter::convertUnstructuredGrid() - Unknown mesh element type ..." << std::endl; + std::cout << + "Error in GridAdapter::convertUnstructuredGrid() - Unknown mesh element type ..." + << std::endl; return NULL; } @@ -132,10 +144,8 @@ MeshLib::CFEMesh* VtkMeshConverter::convertUnstructuredGrid(vtkUnstructuredGrid* elem->SetNodesNumber(nElemNodes); elem->nodes_index.resize(nElemNodes); - for (size_t j=0; j<nElemNodes; j++) - { + for (size_t j = 0; j < nElemNodes; j++) elem->SetNodeIndex(j, cell->GetPointId(j)); - } mesh->ele_vector.push_back(elem); } diff --git a/VtkVis/VtkMeshConverter.h b/VtkVis/VtkMeshConverter.h index 3bcc93186adc675d00ab7f339f9498793b22c301..f76ac4f5e435a8b66f87a8ae31d7526f038e77af 100644 --- a/VtkVis/VtkMeshConverter.h +++ b/VtkVis/VtkMeshConverter.h @@ -4,7 +4,6 @@ * */ - #ifndef VTKMESHCONVERTER_H #define VTKMESHCONVERTER_H @@ -16,8 +15,8 @@ class vtkUnstructuredGrid; // For conversion vom vtk to ogs mesh namespace MeshLib { - class CFEMesh; - class CNode; +class CFEMesh; +class CNode; } /** @@ -27,7 +26,9 @@ class VtkMeshConverter { public: /// Converts greyscale image to quad mesh - static MeshLib::CFEMesh* convertImgToMesh(vtkImageData* img, const std::pair<double,double> &origin, const double &scalingFactor); + static MeshLib::CFEMesh* convertImgToMesh(vtkImageData* img, + const std::pair<double,double> &origin, + const double &scalingFactor); /// Converts a vtkUnstructuredGrid object to a CFEMesh static MeshLib::CFEMesh* convertUnstructuredGrid(vtkUnstructuredGrid* grid); diff --git a/VtkVis/VtkMeshSource.cpp b/VtkVis/VtkMeshSource.cpp index c2be8b3071035bd290508fc8fd78e2a80aa071e7..c561268cba6993c80d36334dd73576f161d3fdb5 100644 --- a/VtkVis/VtkMeshSource.cpp +++ b/VtkVis/VtkMeshSource.cpp @@ -4,16 +4,15 @@ * */ - -#include "VtkMeshSource.h" #include "VtkColorLookupTable.h" +#include "VtkMeshSource.h" // ** VTK INCLUDES ** +#include "vtkObjectFactory.h" #include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkIntArray.h> -#include "vtkObjectFactory.h" #include <vtkPoints.h> #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> @@ -28,7 +27,6 @@ #include <vtkTriangle.h> #include <vtkWedge.h> // == Prism - vtkStandardNewMacro(VtkMeshSource); vtkCxxRevisionMacro(VtkMeshSource, "$Revision$"); @@ -40,7 +38,7 @@ VtkMeshSource::VtkMeshSource() : _matName("MaterialIDs") const GEOLIB::Color* c = GEOLIB::getRandomColor(); vtkProperty* vtkProps = GetProperties(); - vtkProps->SetColor((*c)[0]/255.0,(*c)[1]/255.0,(*c)[2]/255.0); + vtkProps->SetColor((*c)[0] / 255.0,(*c)[1] / 255.0,(*c)[2] / 255.0); vtkProps->SetEdgeVisibility(1); } @@ -53,28 +51,30 @@ void VtkMeshSource::PrintSelf( ostream& os, vtkIndent indent ) { this->Superclass::PrintSelf(os,indent); - if (_grid == NULL) return; - const std::vector<GEOLIB::Point*> *nodes = _grid->getNodes(); - const std::vector<GridAdapter::Element*> *elems = _grid->getElements(); - if (nodes->empty() || elems->empty() ) return; + if (_grid == NULL) + return; + const std::vector<GEOLIB::Point*>* nodes = _grid->getNodes(); + const std::vector<GridAdapter::Element*>* elems = _grid->getElements(); + if (nodes->empty() || elems->empty() ) + return; os << indent << "== VtkMeshSource ==" << "\n"; int i = 0; for (std::vector<GEOLIB::Point*>::const_iterator it = nodes->begin(); - it != nodes->end(); ++it) + it != nodes->end(); ++it) { - os << indent << "Point " << i <<" (" << (*it)[0] << ", " << (*it)[1] << ", " << (*it)[2] << ")" << std::endl; + os << indent << "Point " << i << " (" << (*it)[0] << ", " << (*it)[1] << ", " << + (*it)[2] << ")" << std::endl; i++; } i = 0; for (std::vector<GridAdapter::Element*>::const_iterator it = elems->begin(); - it != elems->end(); ++it) + it != elems->end(); ++it) { - - os << indent << "Element " << i <<": "; - for (size_t t=0; t<(*it)->nodes.size(); t++) + os << indent << "Element " << i << ": "; + for (size_t t = 0; t < (*it)->nodes.size(); t++) os << (*it)->nodes[t] << " "; os << std::endl; i++; @@ -82,15 +82,16 @@ void VtkMeshSource::PrintSelf( ostream& os, vtkIndent indent ) } int VtkMeshSource::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; - if (_grid == NULL) return 0; - const std::vector<GEOLIB::Point*> *nodes = _grid->getNodes(); - const std::vector<GridAdapter::Element*> *elems = _grid->getElements(); + if (_grid == NULL) + return 0; + const std::vector<GEOLIB::Point*>* nodes = _grid->getNodes(); + const std::vector<GridAdapter::Element*>* elems = _grid->getElements(); size_t nPoints = nodes->size(); size_t nElems = elems->size(); @@ -99,59 +100,65 @@ int VtkMeshSource::RequestData( vtkInformation* request, return 0; vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); - vtkSmartPointer<vtkUnstructuredGrid> output = vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - output->Allocate(nElems); + vtkSmartPointer<vtkUnstructuredGrid> output = vtkUnstructuredGrid::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + output->Allocate(nElems); if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) return 1; // Insert grid points vtkSmartPointer<vtkPoints> gridPoints = vtkSmartPointer<vtkPoints>::New(); - gridPoints->Allocate(nPoints); - // Generate mesh nodes - for (size_t i=0; i<nPoints; i++) - gridPoints->InsertPoint(i, (*(*nodes)[i])[0], (*(*nodes)[i])[1], (*(*nodes)[i])[2]); + gridPoints->Allocate(nPoints); + // Generate mesh nodes + for (size_t i = 0; i < nPoints; i++) + gridPoints->InsertPoint(i, (*(*nodes)[i])[0], (*(*nodes)[i])[1], (*(*nodes)[i])[2]); // Generate attribute vector for material groups - vtkSmartPointer<vtkIntArray> materialIDs = vtkSmartPointer<vtkIntArray>::New(); - materialIDs->SetName(_matName); - materialIDs->SetNumberOfComponents(1); - //materialIDs->SetNumberOfTuples(nElems); + vtkSmartPointer<vtkIntArray> materialIDs = vtkSmartPointer<vtkIntArray>::New(); + materialIDs->SetName(_matName); + materialIDs->SetNumberOfComponents(1); + //materialIDs->SetNumberOfTuples(nElems); // Generate mesh elements - for (size_t i=0; i<nElems; i++) + for (size_t i = 0; i < nElems; i++) { vtkCell* newCell; switch ((*elems)[i]->type) { - case MshElemType::TRIANGLE: - newCell = vtkTriangle::New(); break; - case MshElemType::LINE: - newCell = vtkLine::New(); break; - case MshElemType::QUAD: - newCell = vtkQuad::New(); break; - case MshElemType::HEXAHEDRON: - newCell = vtkHexahedron::New(); break; - case MshElemType::TETRAHEDRON: - newCell = vtkTetra::New(); break; - case MshElemType::PRISM: - newCell = vtkWedge::New(); break; - default: // if none of the above can be applied - return 0; + case MshElemType::TRIANGLE: + newCell = vtkTriangle::New(); + break; + case MshElemType::LINE: + newCell = vtkLine::New(); + break; + case MshElemType::QUAD: + newCell = vtkQuad::New(); + break; + case MshElemType::HEXAHEDRON: + newCell = vtkHexahedron::New(); + break; + case MshElemType::TETRAHEDRON: + newCell = vtkTetra::New(); + break; + case MshElemType::PRISM: + newCell = vtkWedge::New(); + break; + default: // if none of the above can be applied + return 0; } materialIDs->InsertNextValue((*elems)[i]->material); nElemNodes = (*elems)[i]->nodes.size(); - for (size_t j=0; j<nElemNodes; j++) - newCell->GetPointIds()->SetId(j, (*elems)[i]->nodes[nElemNodes-1-j]); + for (size_t j = 0; j < nElemNodes; j++) + newCell->GetPointIds()->SetId(j, (*elems)[i]->nodes[nElemNodes - 1 - j]); output->InsertNextCell(newCell->GetCellType(), newCell->GetPointIds()); newCell->Delete(); } - output->SetPoints(gridPoints); output->GetCellData()->AddArray(materialIDs); diff --git a/VtkVis/VtkMeshSource.h b/VtkVis/VtkMeshSource.h index 9c81c91a1044b152549b8266809efed7d127d5f6..c85e1ccc31a0a7fa4f9a1228194a4484207bf823 100644 --- a/VtkVis/VtkMeshSource.h +++ b/VtkVis/VtkMeshSource.h @@ -4,16 +4,15 @@ * */ - #ifndef VTKMESHSOURCE_H #define VTKMESHSOURCE_H // ** INCLUDES ** #include <map> -#include <vtkUnstructuredGridAlgorithm.h> #include "GridAdapter.h" #include "VtkAlgorithmProperties.h" +#include <vtkUnstructuredGridAlgorithm.h> class VtkColorLookupTable; @@ -22,7 +21,6 @@ class VtkColorLookupTable; */ class VtkMeshSource : public vtkUnstructuredGridAlgorithm, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkMeshSource* New(); @@ -32,10 +30,10 @@ public: const char* GetMaterialArrayName() const { return _matName; } /// Returns the base object of this grid - const GridAdapter* GetGrid() { return this->_grid; }; + const GridAdapter* GetGrid() { return this->_grid; } /// Sets the grid object that should be visualized - void SetGrid(const GridAdapter* grid) { _grid = grid; }; + void SetGrid(const GridAdapter* grid) { _grid = grid; } /// Prints the mesh data to an output stream. void PrintSelf(ostream& os, vtkIndent indent); @@ -55,16 +53,13 @@ protected: /// Computes the unstructured grid data object. int RequestData(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector); - - + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); const GridAdapter* _grid; private: const char* _matName; - }; #endif // VTKMESHSOURCE_H diff --git a/VtkVis/VtkPointsSource.cpp b/VtkVis/VtkPointsSource.cpp index d6dcae1ae103cebf281d37d7bb8d4b837f9562f4..2528d2eb00615d35cdf7241bceaf0069a3d60856 100644 --- a/VtkVis/VtkPointsSource.cpp +++ b/VtkVis/VtkPointsSource.cpp @@ -12,22 +12,22 @@ #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> -#include <vtkSmartPointer.h> -#include <vtkStreamingDemandDrivenPipeline.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPolyData.h> +#include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> vtkStandardNewMacro(VtkPointsSource); vtkCxxRevisionMacro(VtkPointsSource, "$Revision$"); VtkPointsSource::VtkPointsSource() -: _points(NULL) + : _points(NULL) { this->SetNumberOfInputPorts(0); const GEOLIB::Color* c = GEOLIB::getRandomColor(); - GetProperties()->SetColor((*c)[0]/255.0,(*c)[1]/255.0,(*c)[2]/255.0); + GetProperties()->SetColor((*c)[0] / 255.0,(*c)[1] / 255.0,(*c)[2] / 255.0); } void VtkPointsSource::PrintSelf( ostream& os, vtkIndent indent ) @@ -41,15 +41,18 @@ void VtkPointsSource::PrintSelf( ostream& os, vtkIndent indent ) int i = 0; for (std::vector<GEOLIB::Point*>::const_iterator it = _points->begin(); - it != _points->end(); ++it) + it != _points->end(); ++it) { const double* coords = (*it)->getData(); - os << indent << "Point " << i <<" (" << coords[0] << ", " << coords[1] << ", " << coords[2] << ")\n"; + os << indent << "Point " << i << " (" << coords[0] << ", " << coords[1] << ", " << + coords[2] << ")\n"; i++; } } -int VtkPointsSource::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkPointsSource::RequestData( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; @@ -59,12 +62,14 @@ int VtkPointsSource::RequestData( vtkInformation* request, vtkInformationVector* int numPoints = _points->size(); if (numPoints == 0) { - std::cout << "ERROR in VtkPointsSource::RequestData : Size of point vector is 0" << std::endl; + std::cout << "ERROR in VtkPointsSource::RequestData : Size of point vector is 0" << + std::endl; return 0; } vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); - vtkSmartPointer<vtkPolyData> output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkSmartPointer<vtkPolyData> output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkCellArray> newVerts = vtkSmartPointer<vtkCellArray>::New(); @@ -76,7 +81,7 @@ int VtkPointsSource::RequestData( vtkInformation* request, vtkInformationVector* // Generate points and vertices for (std::vector<GEOLIB::Point*>::const_iterator it = _points->begin(); - it != _points->end(); ++it) + it != _points->end(); ++it) { double coords[3] = {(*(*it))[0], (*(*it))[1], (*(*it))[2]}; vtkIdType pid = newPoints->InsertNextPoint(coords); @@ -89,7 +94,9 @@ int VtkPointsSource::RequestData( vtkInformation* request, vtkInformationVector* return 1; } -int VtkPointsSource::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkPointsSource::RequestInformation( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; diff --git a/VtkVis/VtkPointsSource.h b/VtkVis/VtkPointsSource.h index 920e0496b3a6d03c71ae01025f6935cd4b97b61f..4ac56bacfe66d6bb497a0ee4706bac27a6b61aca 100644 --- a/VtkVis/VtkPointsSource.h +++ b/VtkVis/VtkPointsSource.h @@ -4,13 +4,12 @@ * */ - #ifndef VTKPOINTSSOURCE_H #define VTKPOINTSSOURCE_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" +#include <vtkPolyDataAlgorithm.h> #include "GEOObjects.h" @@ -20,7 +19,6 @@ */ class VtkPointsSource : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkPointsSource* New(); @@ -28,7 +26,7 @@ public: vtkTypeRevisionMacro(VtkPointsSource,vtkPolyDataAlgorithm); /// Sets the points as a vector - void setPoints(const std::vector<GEOLIB::Point*>* points) { _points = points; }; + void setPoints(const std::vector<GEOLIB::Point*>* points) { _points = points; } /// Prints its data on a stream. void PrintSelf(ostream& os, vtkIndent indent); @@ -37,18 +35,21 @@ public: protected: VtkPointsSource(); - ~VtkPointsSource() {}; + ~VtkPointsSource() {} /// Computes the polygonal data object. - int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); - int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestInformation(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); /// The points to visualize const std::vector<GEOLIB::Point*>* _points; private: - }; #endif // VTKPOINTSSOURCE_H diff --git a/VtkVis/VtkPolylinesSource.cpp b/VtkVis/VtkPolylinesSource.cpp index 240cf60cbbbed4bfb3c32898371e0dc3a7b6a674..b8d880c9dcb6af80acd0e717c538d1fc931acc88 100644 --- a/VtkVis/VtkPolylinesSource.cpp +++ b/VtkVis/VtkPolylinesSource.cpp @@ -8,30 +8,30 @@ // ** INCLUDES ** #include "VtkPolylinesSource.h" -#include <vtkSmartPointer.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> -#include <vtkStreamingDemandDrivenPipeline.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPolyData.h> +#include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> vtkStandardNewMacro(VtkPolylinesSource); vtkCxxRevisionMacro(VtkPolylinesSource, "$Revision$"); VtkPolylinesSource::VtkPolylinesSource() -: _polylines(NULL) + : _polylines(NULL) { - this->SetNumberOfInputPorts(0); + this->SetNumberOfInputPorts(0); const GEOLIB::Color* c = GEOLIB::getRandomColor(); - GetProperties()->SetColor((*c)[0]/255.0,(*c)[1]/255.0,(*c)[2]/255.0); + GetProperties()->SetColor((*c)[0] / 255.0,(*c)[1] / 255.0,(*c)[2] / 255.0); } -VtkPolylinesSource::~VtkPolylinesSource() +VtkPolylinesSource::~VtkPolylinesSource() { } @@ -43,7 +43,7 @@ void VtkPolylinesSource::PrintSelf( ostream& os, vtkIndent indent ) return; for (std::vector<GEOLIB::Polyline*>::const_iterator it = _polylines->begin(); - it != _polylines->end(); ++it) + it != _polylines->end(); ++it) { os << indent << "== Polyline ==" << "\n"; int numPoints = (*it)->getNumberOfPoints(); @@ -51,13 +51,15 @@ void VtkPolylinesSource::PrintSelf( ostream& os, vtkIndent indent ) { const GEOLIB::Point* point = (**it)[i]; const double* coords = point->getData(); - os << indent << "Point " << i <<" (" << coords[0] << ", " << coords[1] << ", " << coords[2] << ")\n"; + os << indent << "Point " << i << " (" << coords[0] << ", " << coords[1] << + ", " << coords[2] << ")\n"; } } - } -int VtkPolylinesSource::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkPolylinesSource::RequestData( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; @@ -66,12 +68,15 @@ int VtkPolylinesSource::RequestData( vtkInformation* request, vtkInformationVect return 0; if (_polylines->size() == 0) { - std::cout << "ERROR in VtkPolylineSource::RequestData : Size of polyline vector is 0" << std::endl; + std::cout << + "ERROR in VtkPolylineSource::RequestData : Size of polyline vector is 0" << + std::endl; return 0; } vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); - vtkSmartPointer<vtkPolyData> output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkSmartPointer<vtkPolyData> output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkCellArray> newLines = vtkSmartPointer<vtkCellArray>::New(); @@ -83,13 +88,13 @@ int VtkPolylinesSource::RequestData( vtkInformation* request, vtkInformationVect return 1; vtkSmartPointer<vtkIntArray> plyIDs = vtkSmartPointer<vtkIntArray>::New(); - plyIDs->SetNumberOfComponents(1); - plyIDs->SetName("PolylineIDs"); + plyIDs->SetNumberOfComponents(1); + plyIDs->SetName("PolylineIDs"); int lastMaxIndex = 0; //for (std::vector<GEOLIB::Polyline*>::const_iterator it = _polylines->begin(); // it != _polylines->end(); ++it) - for (size_t j=0; j<_polylines->size(); j++) + for (size_t j = 0; j < _polylines->size(); j++) { const int numPoints = (*_polylines)[j]->getNumberOfPoints(); //const int numLines = numPoints - 1; @@ -119,7 +124,9 @@ int VtkPolylinesSource::RequestData( vtkInformation* request, vtkInformationVect return 1; } -int VtkPolylinesSource::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkPolylinesSource::RequestInformation( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; diff --git a/VtkVis/VtkPolylinesSource.h b/VtkVis/VtkPolylinesSource.h index 7b19f6f2a5f61eb56b02812d088eff2083a93725..888f0b1297c2a447a36c6a7f344b43333afb4804 100644 --- a/VtkVis/VtkPolylinesSource.h +++ b/VtkVis/VtkPolylinesSource.h @@ -4,13 +4,12 @@ * */ - #ifndef VTKPOLYLINESSOURCE_H #define VTKPOLYLINESSOURCE_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" +#include <vtkPolyDataAlgorithm.h> #include "GEOObjects.h" @@ -20,7 +19,6 @@ */ class VtkPolylinesSource : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkPolylinesSource* New(); @@ -28,7 +26,7 @@ public: vtkTypeRevisionMacro(VtkPolylinesSource,vtkPolyDataAlgorithm); /// Sets the polyline vector. - void setPolylines(const std::vector<GEOLIB::Polyline*> *polylines) { _polylines = polylines; }; + void setPolylines(const std::vector<GEOLIB::Polyline*>* polylines) { _polylines = polylines; } /// Prints its data on a stream. void PrintSelf(ostream& os, vtkIndent indent); @@ -40,15 +38,18 @@ protected: ~VtkPolylinesSource(); /// Computes the polygonal data object. - int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); - int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestInformation(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); /// The polylines to visualize. - const std::vector<GEOLIB::Polyline*> *_polylines; + const std::vector<GEOLIB::Polyline*>* _polylines; private: - }; #endif // VTKPOLYLINESSOURCE_H diff --git a/VtkVis/VtkSelectionFilter.cpp b/VtkVis/VtkSelectionFilter.cpp index 90d6701ebe10b9a6e429a1f9ad110923b5408594..48ccb562d942ea5d66ce832c5e74b6b8ec98b0ae 100644 --- a/VtkVis/VtkSelectionFilter.cpp +++ b/VtkVis/VtkSelectionFilter.cpp @@ -7,22 +7,21 @@ // ** VTK INCLUDES ** #include "VtkSelectionFilter.h" +#include <vtkCellData.h> +#include <vtkDoubleArray.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> +#include <vtkPointData.h> +#include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> #include <vtkUnstructuredGrid.h> -#include <vtkSmartPointer.h> -#include <vtkPointData.h> -#include <vtkCellData.h> -#include <vtkDoubleArray.h> vtkStandardNewMacro(VtkSelectionFilter); vtkCxxRevisionMacro(VtkSelectionFilter, "$Revision: 6995 $"); - VtkSelectionFilter::VtkSelectionFilter() -: _thresholdLower(0.0), _thresholdUpper(1.0) + : _thresholdLower(0.0), _thresholdUpper(1.0) { } @@ -36,44 +35,48 @@ void VtkSelectionFilter::PrintSelf( ostream& os, vtkIndent indent ) os << indent << "== VtkSelectionFilter ==" << endl; } -int VtkSelectionFilter::RequestData( vtkInformation*, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkSelectionFilter::RequestData( vtkInformation*, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { - if (this->_selection.empty()) + if (this->_selection.empty()) { std::cout << "VtkSelectionFilter - Error: Selection array is empty..." << std::endl; return 0; } vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkUnstructuredGrid *input = vtkUnstructuredGrid::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - + vtkUnstructuredGrid* input = + vtkUnstructuredGrid::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkSmartPointer<vtkDoubleArray> colors = vtkSmartPointer<vtkDoubleArray>::New(); - colors->SetNumberOfComponents(1); - colors->SetName("Selection"); + colors->SetNumberOfComponents(1); + colors->SetName("Selection"); size_t nCells = input->GetNumberOfCells(); size_t arrayLength = this->_selection.size(); - if (nCells>arrayLength) - std::cout << "VtkSelectionFilter - Warning: Number of cells exceeds selection array length. Surplus cells won't be examined." << std::endl; + if (nCells > arrayLength) + std::cout << + "VtkSelectionFilter - Warning: Number of cells exceeds selection array length. Surplus cells won't be examined." + << std::endl; - for (size_t i=0; i<arrayLength; i++) - { + for (size_t i = 0; i < arrayLength; i++) colors->InsertNextValue(_selection[i]); - } vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - output->CopyStructure(input); - output->GetPointData()->PassData(input->GetPointData()); - output->GetCellData()->PassData(input->GetCellData()); - output->GetCellData()->AddArray(colors); - output->GetCellData()->SetActiveScalars("Selection"); + vtkUnstructuredGrid* output = + vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + output->CopyStructure(input); + output->GetPointData()->PassData(input->GetPointData()); + output->GetCellData()->PassData(input->GetCellData()); + output->GetCellData()->AddArray(colors); + output->GetCellData()->SetActiveScalars("Selection"); return 1; } -void VtkSelectionFilter::SetSelectionArray(std::vector<double> selection, double thresholdLower, double thresholdUpper) +void VtkSelectionFilter::SetSelectionArray(std::vector<double> selection, + double thresholdLower, + double thresholdUpper) { this->_selection = selection; this->_thresholdLower = thresholdLower; diff --git a/VtkVis/VtkSelectionFilter.h b/VtkVis/VtkSelectionFilter.h index 16ac539bc61c856c27b6f151fc8f4fa1089576fa..41df9e5bea3b170527a4c1636c2f184015e9f2fc 100644 --- a/VtkVis/VtkSelectionFilter.h +++ b/VtkVis/VtkSelectionFilter.h @@ -4,19 +4,15 @@ * */ - #ifndef VTKSELECTIONFILTER_H #define VTKSELECTIONFILTER_H // ** INCLUDES ** -#include <vtkUnstructuredGridAlgorithm.h> #include "VtkAlgorithmProperties.h" - - +#include <vtkUnstructuredGridAlgorithm.h> class VtkSelectionFilter : public vtkUnstructuredGridAlgorithm, public VtkAlgorithmProperties { - public: /// @brief Create new objects with New() because of VTKs object reference counting. static VtkSelectionFilter* New(); @@ -27,23 +23,24 @@ public: void PrintSelf(ostream& os, vtkIndent indent); /// @brief Sets user properties. - void SetUserProperty(QString name, QVariant value) - { + void SetUserProperty(QString name, QVariant value) + { Q_UNUSED(name); Q_UNUSED(value); - } - - void SetSelectionArray(std::vector<double> selection, double thresholdLower, double thresholdUpper); + } + void SetSelectionArray(std::vector<double> selection, + double thresholdLower, + double thresholdUpper); protected: VtkSelectionFilter(); ~VtkSelectionFilter(); /// @brief The filter logic. - int RequestData(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); private: std::vector<double> _selection; diff --git a/VtkVis/VtkStationSource.cpp b/VtkVis/VtkStationSource.cpp index c0885551d5d3891af9cdded47eefca078657de81..62075c54982d20bed01f822765da308834ec704a 100644 --- a/VtkVis/VtkStationSource.cpp +++ b/VtkVis/VtkStationSource.cpp @@ -4,43 +4,42 @@ * */ -#include "Station.h" #include "Color.h" +#include "Station.h" // ** VTK INCLUDES ** #include "VtkStationSource.h" -#include <vtkSmartPointer.h> +#include "vtkObjectFactory.h" #include <vtkCellArray.h> +#include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> -#include "vtkObjectFactory.h" -#include <vtkStreamingDemandDrivenPipeline.h> +#include <vtkLine.h> #include <vtkPointData.h> #include <vtkPoints.h> -#include <vtkLine.h> #include <vtkPolyData.h> -#include <vtkCellData.h> +#include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> vtkStandardNewMacro(VtkStationSource); vtkCxxRevisionMacro(VtkStationSource, "$Revision$"); VtkStationSource::VtkStationSource() -: _stations(NULL) + : _stations(NULL) { this->SetNumberOfInputPorts(0); const GEOLIB::Color* c = GEOLIB::getRandomColor(); - GetProperties()->SetColor((*c)[0]/255.0,(*c)[1]/255.0,(*c)[2]/255.0); + GetProperties()->SetColor((*c)[0] / 255.0,(*c)[1] / 255.0,(*c)[2] / 255.0); delete c; } VtkStationSource::~VtkStationSource() { std::map<std::string, GEOLIB::Color*>::iterator it; - for (it = _colorLookupTable.begin(); it != _colorLookupTable.end(); ++it) { + for (it = _colorLookupTable.begin(); it != _colorLookupTable.end(); ++it) delete it->second; - } } void VtkStationSource::PrintSelf( ostream& os, vtkIndent indent ) @@ -54,17 +53,19 @@ void VtkStationSource::PrintSelf( ostream& os, vtkIndent indent ) int i = 0; for (std::vector<GEOLIB::Point*>::const_iterator it = _stations->begin(); - it != _stations->end(); ++it) + it != _stations->end(); ++it) { const double* coords = (*it)->getData(); - os << indent << "Station " << i <<" (" << coords[0] << ", " << coords[1] << ", " << coords[2] << ")\n"; + os << indent << "Station " << i << " (" << coords[0] << ", " << coords[1] << + ", " << coords[2] << ")\n"; i++; } } - /// Create 3d Station objects -int VtkStationSource::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkStationSource::RequestData( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; @@ -75,53 +76,56 @@ int VtkStationSource::RequestData( vtkInformation* request, vtkInformationVector if (nStations == 0) return 0; - bool isBorehole = (static_cast<GEOLIB::Station*>((*_stations)[0])->type() == GEOLIB::Station::BOREHOLE) ? true : false; + bool isBorehole = + (static_cast<GEOLIB::Station*>((*_stations)[0])->type() == + GEOLIB::Station::BOREHOLE) ? true : false; vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); - vtkSmartPointer<vtkPolyData> output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkSmartPointer<vtkPolyData> output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkPoints> newStations = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkCellArray> newVerts = vtkSmartPointer<vtkCellArray>::New(); - newVerts->Allocate(nStations); + newVerts->Allocate(nStations); vtkSmartPointer<vtkCellArray> newLines; - if (isBorehole) + if (isBorehole) newLines = vtkSmartPointer<vtkCellArray>::New(); if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) return 1; vtkSmartPointer<vtkIntArray> station_ids = vtkSmartPointer<vtkIntArray>::New(); - station_ids->SetNumberOfComponents(1); - station_ids->SetName("SiteIDs"); + station_ids->SetNumberOfComponents(1); + station_ids->SetName("SiteIDs"); vtkSmartPointer<vtkIntArray> strat_ids = vtkSmartPointer<vtkIntArray>::New(); - strat_ids->SetNumberOfComponents(1); - strat_ids->SetName("Stratigraphies"); + strat_ids->SetNumberOfComponents(1); + strat_ids->SetName("Stratigraphies"); size_t lastMaxIndex(0); size_t site_count(0); // Generate graphic objects for (std::vector<GEOLIB::Point*>::const_iterator it = _stations->begin(); - it != _stations->end(); ++it) + it != _stations->end(); ++it) { double coords[3] = { (*(*it))[0], (*(*it))[1], (*(*it))[2] }; vtkIdType sid = newStations->InsertNextPoint(coords); station_ids->InsertNextValue(site_count); if (!isBorehole) - { newVerts->InsertNextCell(1, &sid); - } else { - std::vector<GEOLIB::Point*> profile = static_cast<GEOLIB::StationBorehole*>(*it)->getProfile(); - std::vector<std::string> soilNames = static_cast<GEOLIB::StationBorehole*>(*it)->getSoilNames(); + std::vector<GEOLIB::Point*> profile = + static_cast<GEOLIB::StationBorehole*>(*it)->getProfile(); + std::vector<std::string> soilNames = + static_cast<GEOLIB::StationBorehole*>(*it)->getSoilNames(); const size_t nLayers = profile.size(); - for (size_t i=1; i<nLayers; i++) + for (size_t i = 1; i < nLayers; i++) { double* pCoords = const_cast<double*>(profile[i]->getData()); double loc[3] = { pCoords[0], pCoords[1], pCoords[2] }; @@ -129,8 +133,8 @@ int VtkStationSource::RequestData( vtkInformation* request, vtkInformationVector station_ids->InsertNextValue(site_count); newLines->InsertNextCell(2); - newLines->InsertCellPoint(lastMaxIndex); // start of borehole-layer - newLines->InsertCellPoint(lastMaxIndex+1); //end of boreholelayer + newLines->InsertCellPoint(lastMaxIndex); // start of borehole-layer + newLines->InsertCellPoint(lastMaxIndex + 1); //end of boreholelayer lastMaxIndex++; strat_ids->InsertNextValue(this->GetIndexByName(soilNames[i])); } @@ -144,25 +148,28 @@ int VtkStationSource::RequestData( vtkInformation* request, vtkInformationVector if (!isBorehole) { output->SetVerts(newVerts); - output->GetPointData()->AddArray(station_ids); + output->GetPointData()->AddArray(station_ids); } else { output->SetLines(newLines); output->GetCellData()->AddArray(strat_ids); - output->GetCellData()->SetActiveAttribute("Stratigraphies", vtkDataSetAttributes::SCALARS); + output->GetCellData()->SetActiveAttribute("Stratigraphies", + vtkDataSetAttributes::SCALARS); } return 1; } -int VtkStationSource::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkStationSource::RequestInformation( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; vtkInformation* outInfo = outputVector->GetInformationObject(0); - outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); + outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); return 1; } @@ -176,13 +183,15 @@ void VtkStationSource::SetUserProperty( QString name, QVariant value ) size_t VtkStationSource::GetIndexByName( std::string name ) { vtkIdType max_key(0); - for (std::map<std::string, vtkIdType>::const_iterator it=_id_map.begin(); it != _id_map.end(); ++it) + for (std::map<std::string, vtkIdType>::const_iterator it = _id_map.begin(); + it != _id_map.end(); ++it) { if (name.compare(it->first) == 0) return it->second; - if (it->second > max_key) max_key = it->second; + if (it->second > max_key) + max_key = it->second; } - vtkIdType new_index(max_key+1); + vtkIdType new_index(max_key + 1); std::cout << "Key \"" << name << "\" not found in color lookup table..." << std::endl; _id_map.insert(std::pair<std::string, vtkIdType>(name, new_index)); return new_index; diff --git a/VtkVis/VtkStationSource.h b/VtkVis/VtkStationSource.h index 6732200b5a1f0b6504b45be2a2d4cf136aa79140..41fa39f4f8886ba552613ab35284aec0f07c7094 100644 --- a/VtkVis/VtkStationSource.h +++ b/VtkVis/VtkStationSource.h @@ -4,13 +4,12 @@ * */ - #ifndef VTKSTATIONSOURCE_H #define VTKSTATIONSOURCE_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" +#include <vtkPolyDataAlgorithm.h> #include "GEOObjects.h" @@ -19,7 +18,6 @@ */ class VtkStationSource : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkStationSource* New(); @@ -28,13 +26,16 @@ public: /// Returns the colour lookup table generated for boreholes. /// This method should only be called after the colour lookup table has actually been build (via RequestData() or setColorLookupTable()). - const std::map<std::string, GEOLIB::Color*>& getColorLookupTable() const { return _colorLookupTable; }; + const std::map<std::string, + GEOLIB::Color*>& getColorLookupTable() const { return _colorLookupTable; } /// Sets a predefined color lookup table for the colouring of borehole stratigraphies - int setColorLookupTable(const std::string &filename) { return readColorLookupTable(_colorLookupTable, filename); }; + int setColorLookupTable(const std::string &filename) { return readColorLookupTable( + _colorLookupTable, + filename); } /// Sets the stations as a vector - void setStations(const std::vector<GEOLIB::Point*> *stations) { _stations = stations; }; + void setStations(const std::vector<GEOLIB::Point*>* stations) { _stations = stations; } /// Prints its data on a stream. void PrintSelf(ostream& os, vtkIndent indent); @@ -46,12 +47,16 @@ protected: ~VtkStationSource(); /// Computes the polygonal data object. - int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); - int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestInformation(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); /// The stations to visualize - const std::vector<GEOLIB::Point*> *_stations; + const std::vector<GEOLIB::Point*>* _stations; /// The colour table for stratigraphic data. This table is either set using the setColorLookupTable() method or is generated /// automatically with random colours while creating the VtkStationSource-object. @@ -61,7 +66,6 @@ private: size_t GetIndexByName( std::string name ); std::map<std::string, vtkIdType> _id_map; - }; #endif // VTKSTATIONSOURCE_H diff --git a/VtkVis/VtkSurfacesSource.cpp b/VtkVis/VtkSurfacesSource.cpp index bce54056bde53258082fc24c68e29038c0917679..3e0a92165089ecf43b5b604a2f05475be4cdec60 100644 --- a/VtkVis/VtkSurfacesSource.cpp +++ b/VtkVis/VtkSurfacesSource.cpp @@ -7,32 +7,32 @@ */ // ** INCLUDES ** -#include <limits> #include "Color.h" #include "VtkSurfacesSource.h" +#include <limits> -#include <vtkPolygon.h> #include <vtkCellArray.h> -#include <vtkPolyData.h> #include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> -#include <vtkStreamingDemandDrivenPipeline.h> +#include <vtkPolyData.h> +#include <vtkPolygon.h> #include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> vtkStandardNewMacro(VtkSurfacesSource); vtkCxxRevisionMacro(VtkSurfacesSource, "$Revision$"); VtkSurfacesSource::VtkSurfacesSource() -: _surfaces(NULL) + : _surfaces(NULL) { this->SetNumberOfInputPorts(0); //this->SetColorBySurface(true); const GEOLIB::Color* c = GEOLIB::getRandomColor(); vtkProperty* vtkProps = GetProperties(); - vtkProps->SetColor((*c)[0]/255.0,(*c)[1]/255.0,(*c)[2]/255.0); + vtkProps->SetColor((*c)[0] / 255.0,(*c)[1] / 255.0,(*c)[2] / 255.0); vtkProps->SetEdgeVisibility(0); } @@ -46,7 +46,9 @@ void VtkSurfacesSource::PrintSelf( ostream& os, vtkIndent indent ) os << indent << "== VtkSurfacesSource ==" << "\n"; } -int VtkSurfacesSource::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkSurfacesSource::RequestData( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; @@ -55,25 +57,26 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, vtkInformationVecto if (nSurfaces == 0) return 0; - const std::vector<GEOLIB::Point*> *surfacePoints = (*_surfaces)[0]->getPointVec(); + const std::vector<GEOLIB::Point*>* surfacePoints = (*_surfaces)[0]->getPointVec(); size_t nPoints = surfacePoints->size(); vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); - vtkSmartPointer<vtkPolyData> output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkSmartPointer<vtkPolyData> output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) return 1; vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); - newPoints->Allocate(nPoints); + newPoints->Allocate(nPoints); vtkSmartPointer<vtkCellArray> newPolygons = vtkSmartPointer<vtkCellArray>::New(); - //newPolygons->Allocate(nSurfaces); + //newPolygons->Allocate(nSurfaces); vtkSmartPointer<vtkIntArray> sfcIDs = vtkSmartPointer<vtkIntArray>::New(); - sfcIDs->SetNumberOfComponents(1); - sfcIDs->SetName("SurfaceIDs"); + sfcIDs->SetNumberOfComponents(1); + sfcIDs->SetName("SurfaceIDs"); - for (size_t i=0; i<nPoints; i++) + for (size_t i = 0; i < nPoints; i++) { double* coords = const_cast<double*>((*surfacePoints)[i]->getData()); newPoints->InsertNextPoint(coords); @@ -81,7 +84,7 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, vtkInformationVecto vtkIdType count(0); for (std::vector<GEOLIB::Surface*>::const_iterator it = _surfaces->begin(); - it != _surfaces->end(); ++it) + it != _surfaces->end(); ++it) { const size_t nTriangles = (*it)->getNTriangles(); @@ -91,10 +94,8 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, vtkInformationVecto aPolygon->GetPointIds()->SetNumberOfIds(3); const GEOLIB::Triangle* triangle = (**it)[i]; - for (size_t j=0; j<3; j++) - { - aPolygon->GetPointIds()->SetId(j, ((*triangle)[2-j])); - } + for (size_t j = 0; j < 3; j++) + aPolygon->GetPointIds()->SetId(j, ((*triangle)[2 - j])); newPolygons->InsertNextCell(aPolygon); sfcIDs->InsertNextValue(count); aPolygon->Delete(); @@ -110,7 +111,9 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, vtkInformationVecto return 1; } -int VtkSurfacesSource::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ) +int VtkSurfacesSource::RequestInformation( vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; (void)inputVector; diff --git a/VtkVis/VtkSurfacesSource.h b/VtkVis/VtkSurfacesSource.h index 0de2efd457f9161a21a29e266e2b7185a41fe416..f9e57ad04cf2c91db95a33d509e5b6010e36cac1 100644 --- a/VtkVis/VtkSurfacesSource.h +++ b/VtkVis/VtkSurfacesSource.h @@ -5,13 +5,12 @@ * */ - #ifndef VTKSURFACESSOURCE_H #define VTKSURFACESSOURCE_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> #include "VtkAlgorithmProperties.h" +#include <vtkPolyDataAlgorithm.h> #include "Surface.h" @@ -21,7 +20,6 @@ */ class VtkSurfacesSource : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties { - public: /// Create new objects with New() because of VTKs object reference counting. static VtkSurfacesSource* New(); @@ -29,7 +27,7 @@ public: vtkTypeRevisionMacro(VtkSurfacesSource,vtkPolyDataAlgorithm); /// Sets the surfaces vector - void setSurfaces(const std::vector<GEOLIB::Surface*> *surfaces) { _surfaces = surfaces; }; + void setSurfaces(const std::vector<GEOLIB::Surface*>* surfaces) { _surfaces = surfaces; } /// Prints its data on a stream. void PrintSelf(ostream& os, vtkIndent indent); @@ -43,18 +41,21 @@ public: protected: VtkSurfacesSource(); - ~VtkSurfacesSource() {}; + ~VtkSurfacesSource() {} /// Computes the polygonal data object. - int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); - int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + int RequestInformation(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); /// The surfaces to visualize - const std::vector<GEOLIB::Surface*> *_surfaces; + const std::vector<GEOLIB::Surface*>* _surfaces; private: - }; #endif // VTKSURFACESSOURCE_H diff --git a/VtkVis/VtkTextureOnSurfaceFilter.cpp b/VtkVis/VtkTextureOnSurfaceFilter.cpp index 4963dd61bc368432b952ec29d90c6f215b022af9..a7fe3d3086c09c0b64f1fd102b6828ec8f7fa855 100644 --- a/VtkVis/VtkTextureOnSurfaceFilter.cpp +++ b/VtkVis/VtkTextureOnSurfaceFilter.cpp @@ -7,14 +7,14 @@ */ // ** INCLUDES ** +#include <vtkCellData.h> +#include <vtkFloatArray.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> -#include <vtkStreamingDemandDrivenPipeline.h> -#include <vtkSmartPointer.h> #include <vtkPointData.h> -#include <vtkCellData.h> -#include <vtkFloatArray.h> +#include <vtkSmartPointer.h> +#include <vtkStreamingDemandDrivenPipeline.h> #include "MathTools.h" #include "VtkTextureOnSurfaceFilter.h" @@ -22,7 +22,6 @@ #include <QImage> - vtkStandardNewMacro(VtkTextureOnSurfaceFilter); vtkCxxRevisionMacro(VtkTextureOnSurfaceFilter, "$Revision$"); @@ -40,54 +39,63 @@ void VtkTextureOnSurfaceFilter::PrintSelf( ostream& os, vtkIndent indent ) } int VtkTextureOnSurfaceFilter::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) + vtkInformationVector** inputVector, + vtkInformationVector* outputVector ) { (void)request; if (this->GetTexture() == NULL) { - std::cout << "Error in VtkTextureOnSurfaceFilter::RequestData() - No texture specified ..." << std::endl; + std::cout << + "Error in VtkTextureOnSurfaceFilter::RequestData() - No texture specified ..." << + std::endl; return 0; } vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkPolyData *input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData* input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); int dims[3]; this->GetTexture()->GetInput()->GetDimensions(dims); - size_t imgWidth=dims[0]; size_t imgHeight=dims[1]; + size_t imgWidth = dims[0]; + size_t imgHeight = dims[1]; std::pair<int, int> min((int)_origin.first, (int)_origin.second); - std::pair<int, int> max((int)(_origin.first+(imgWidth * _scalingFactor)), (int)(_origin.second+(imgHeight * _scalingFactor))); + std::pair<int, int> max((int)(_origin.first + (imgWidth * _scalingFactor)), + (int)(_origin.second + (imgHeight * _scalingFactor))); //calculate texture coordinates vtkPoints* points = input->GetPoints(); vtkSmartPointer<vtkFloatArray> textureCoordinates = vtkSmartPointer<vtkFloatArray>::New(); - textureCoordinates->SetNumberOfComponents(3); - textureCoordinates->SetName("TextureCoordinates"); - size_t nPoints = points->GetNumberOfPoints(); - for (size_t i=0; i<nPoints; i++) - { - double coords[3]; - points->GetPoint(i, coords); - float newcoords[3] = {MathLib::normalize(min.first, max.first, coords[0]), MathLib::normalize(min.second, max.second, coords[1]), 0 /*coords[2]*/ }; - textureCoordinates->InsertNextTuple(newcoords); - } + textureCoordinates->SetNumberOfComponents(3); + textureCoordinates->SetName("TextureCoordinates"); + size_t nPoints = points->GetNumberOfPoints(); + for (size_t i = 0; i < nPoints; i++) + { + double coords[3]; + points->GetPoint(i, coords); + float newcoords[3] = + {MathLib::normalize(min.first, max.first, coords[0]), MathLib::normalize(min.second, + max.second, + coords[1]), + 0 /*coords[2]*/ }; + textureCoordinates->InsertNextTuple(newcoords); + } // put it all together vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkPolyData *output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - output->CopyStructure(input); - output->GetPointData()->PassData(input->GetPointData()); - output->GetCellData()->PassData(input->GetCellData()); - output->GetPointData()->SetTCoords(textureCoordinates); - + vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + output->CopyStructure(input); + output->GetPointData()->PassData(input->GetPointData()); + output->GetCellData()->PassData(input->GetCellData()); + output->GetPointData()->SetTCoords(textureCoordinates); return 1; } -void VtkTextureOnSurfaceFilter::SetRaster(QImage &img, std::pair<float, float> origin, double scalingFactor) +void VtkTextureOnSurfaceFilter::SetRaster(QImage &img, + std::pair<float, float> origin, + double scalingFactor) { _origin = origin; _scalingFactor = scalingFactor; diff --git a/VtkVis/VtkTextureOnSurfaceFilter.h b/VtkVis/VtkTextureOnSurfaceFilter.h index 2e60739bb14d2829428076b79c4743de5cb668cf..ad47c1b55f66f9ed8607bbace3a6980b40952be3 100644 --- a/VtkVis/VtkTextureOnSurfaceFilter.h +++ b/VtkVis/VtkTextureOnSurfaceFilter.h @@ -4,14 +4,13 @@ * */ - #ifndef VTKOGSPOLYDATAALGORITHM_H #define VTKOGSPOLYDATAALGORITHM_H // ** INCLUDES ** -#include <vtkPolyDataAlgorithm.h> -#include <vtkImageData.h> #include "VtkAlgorithmProperties.h" +#include <vtkImageData.h> +#include <vtkPolyDataAlgorithm.h> class QImage; @@ -24,7 +23,7 @@ class QImage; * the texture will also be saved in the VtkAlgorithmProperties object from which this class is * derived (i.e. the texture can be returned by VtkAlgorithmProperties::GetTexture()). * - * For convenience this class also has a converter function ConvertImageToTexture() which uses + * For convenience this class also has a converter function ConvertImageToTexture() which uses * a QImage as input. */ class VtkTextureOnSurfaceFilter : public vtkPolyDataAlgorithm, public VtkAlgorithmProperties @@ -36,7 +35,7 @@ public: vtkTypeRevisionMacro(VtkTextureOnSurfaceFilter,vtkPolyDataAlgorithm); /// Prints the object data to an output stream. - void PrintSelf(ostream& os, vtkIndent indent); + void PrintSelf(ostream& os, vtkIndent indent); /// Sets the raster/image to be used as a texture map void SetRaster(QImage &img, std::pair<float, float> origin, double scalingFactor); @@ -49,9 +48,9 @@ protected: /// Copies the input data and calculates texture coordinates (this requires that SetRaster() has /// been called before this method is executed. - int RequestData(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector); + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); private: std::pair<float, float> _origin; diff --git a/VtkVis/VtkTrackedCamera.cpp b/VtkVis/VtkTrackedCamera.cpp index 285ced56dfc0dfebabfba149a6130e401aacc6fe..d58cbf45fb6b771a4f2cdc990b1f2a37201006fd 100644 --- a/VtkVis/VtkTrackedCamera.cpp +++ b/VtkVis/VtkTrackedCamera.cpp @@ -1,7 +1,7 @@ /** * \file VtkTrackedCamera.cpp * 25/08/2010 LB Initial implementation - * + * * Implementation of VtkTrackedCamera class */ @@ -14,7 +14,7 @@ #include <QSettings> VtkTrackedCamera::VtkTrackedCamera(QObject* parent) -: QObject(parent), vtkOpenGLCamera() + : QObject(parent), vtkOpenGLCamera() { QSettings settings("UFZ", "OpenGeoSys-5"); settings.beginGroup("Tracking"); @@ -107,7 +107,7 @@ void VtkTrackedCamera::updateView() double y = _trackedPosition[1] * _realToVirtualScale; double z = _trackedPosition[2] * _realToVirtualScale; double angle = vtkMath::DegreesFromRadians( - 2*atan(0.5*_screenHeight*_realToVirtualScale / y)); + 2 * atan(0.5 * _screenHeight * _realToVirtualScale / y)); //double newfocal[3] = {_x + x, _y, _z + z}; //double newpos[3] = {_x + x, _y + y, _z + z}; @@ -118,7 +118,7 @@ void VtkTrackedCamera::updateView() //SetViewUp(viewup); //SetClippingRange(_zNear, _zFar); SetViewShear(x / y, z / y, 1); // see http://www.vtk.org/pipermail/vtkusers/2005-March/078735.html - + emit viewUpdated(); } @@ -127,16 +127,16 @@ void VtkTrackedCamera::updatedFromOutside() double pos[3], dir[3]; GetPosition(pos); GetDirectionOfProjection(dir); - - vtkMath::Normalize(dir); // Get the view direction - dir[0] = dir[0] * _trackedPosition[1]; // Multiplying the view direction - dir[1] = dir[1] * _trackedPosition[1]; // with the tracked distance to the - dir[2] = dir[2] * _trackedPosition[1]; // display results in the vector - _focalPoint[0] = dir[0] + pos[0]; // from the position to the new - _focalPoint[1] = dir[1] + pos[1]; // focal point. + + vtkMath::Normalize(dir); // Get the view direction + dir[0] = dir[0] * _trackedPosition[1]; // Multiplying the view direction + dir[1] = dir[1] * _trackedPosition[1]; // with the tracked distance to the + dir[2] = dir[2] * _trackedPosition[1]; // display results in the vector + _focalPoint[0] = dir[0] + pos[0]; // from the position to the new + _focalPoint[1] = dir[1] + pos[1]; // focal point. _focalPoint[2] = dir[2] + pos[2]; - + updateView(); - + //std::cout << "Camera slot" << std::endl; } diff --git a/VtkVis/VtkTrackedCamera.h b/VtkVis/VtkTrackedCamera.h index 0dd1d4b6afe9e454648a2214a79190f53967eeb7..6a04167d08cc408613d8bd9ad8090e8250f34cbb 100644 --- a/VtkVis/VtkTrackedCamera.h +++ b/VtkVis/VtkTrackedCamera.h @@ -14,14 +14,14 @@ class VtkTrackedCamera : public QObject, public vtkOpenGLCamera { Q_OBJECT - + public: /// @brief Constructor. VtkTrackedCamera(QObject* parent); - + /// @brief Destructor virtual ~VtkTrackedCamera(); - + /// Sets the scaling from real meters to virtual meters. void setRealToVirtualScale(double scale) { _realToVirtualScale = scale; } double realToVirtualScale () const { return _realToVirtualScale; } @@ -38,44 +38,48 @@ public slots: /// @brief Sets the tracked position. The coordinate origin must be the center /// of the projection wall. See also setTrackingOffset(). void setTrackingData(double x, double y, double z); - + /// Sets the focal point in world coordinates. This point corresponds to the /// center of the projection wall. void setFocalPoint(double x, double y, double z); - + /// @brief Sets an offset of the tracked position. This must be used to setup /// the origin of the calibrated tracking space. void setTrackingOffset(double x, double y, double z); - + void setTrackingOffsetX(double val) { _trackedPositionOffset[0] = val; } void setTrackingOffsetY(double val) { _trackedPositionOffset[1] = val; } void setTrackingOffsetZ(double val) { _trackedPositionOffset[2] = val; } - + /// Move the camera by the given vector. void translate(double x, double y, double z); - + /// Rotate the camera by the given angles. void rotate(double yaw, double elevation, double roll); - + /// Updates the view. void updateView(); - + /// Must be called to update the view after the camera was modified from the /// outside, e.g. from the vtkRenderWindowInteractor. void updatedFromOutside(); - + /// @brief Sets the screen properties. /// @param aspectRatio width / height /// @param height The screen height in meter. - void setScreenProperties(double aspectRatio, double height) { + void setScreenProperties(double aspectRatio, double height) + { _screenAspectRatio = aspectRatio; - _screenHeight = height; } - + _screenHeight = height; + } + /// @brief Sets the screen aspect ratio (width / height). - void setScreenAspectRatio(double ratio) { _screenAspectRatio = ratio; updateView(); } - + void setScreenAspectRatio(double ratio) { _screenAspectRatio = ratio; + updateView(); } + /// @brief Sets the screen height in meter. - void setScreenHeight(double height) { _screenHeight = height; updateView(); } + void setScreenHeight(double height) { _screenHeight = height; + updateView(); } private: double _focalPoint[3]; @@ -84,7 +88,7 @@ private: double _realToVirtualScale; double _screenAspectRatio; double _screenHeight; - + signals: /// Is emitted from updateView(). void viewUpdated(); diff --git a/VtkVis/VtkVisHelper.cpp b/VtkVis/VtkVisHelper.cpp index bc519e6f0329abb9076ebbf375f75e76b2318944..406746ad870525b62f80a44e19cd1120eb698b3f 100644 --- a/VtkVis/VtkVisHelper.cpp +++ b/VtkVis/VtkVisHelper.cpp @@ -9,10 +9,10 @@ #include "VtkVisHelper.h" #include <vtkImageData.h> -#include <vtkTexture.h> +#include <vtkPointData.h> #include <vtkSmartPointer.h> +#include <vtkTexture.h> #include <vtkUnsignedCharArray.h> -#include <vtkPointData.h> #include <QImage> @@ -21,18 +21,18 @@ vtkImageData* VtkVisHelper::QImageToVtkImageData(QImage &img) size_t imgWidth = img.width(), imgHeight = img.height(); vtkSmartPointer<vtkUnsignedCharArray> data = vtkSmartPointer<vtkUnsignedCharArray>::New(); data->SetNumberOfComponents(3); - data->SetNumberOfTuples( imgWidth*imgHeight ); + data->SetNumberOfTuples( imgWidth * imgHeight ); - for (size_t j=0; j<imgHeight; j++) { - for (size_t i=0; i<imgWidth; i++) { + for (size_t j = 0; j < imgHeight; j++) + for (size_t i = 0; i < imgWidth; i++) + { QRgb pix = img.pixel(i,j); const float color[3] = { qRed(pix), qGreen(pix), qBlue(pix) }; - data->SetTuple(j*imgWidth+i, color); + data->SetTuple(j * imgWidth + i, color); } - } vtkImageData* imgData = vtkImageData::New(); - imgData->SetExtent(0, imgWidth-1, 0, imgHeight-1, 0, 0); + imgData->SetExtent(0, imgWidth - 1, 0, imgHeight - 1, 0, 0); imgData->SetOrigin(0, 0, 0); imgData->SetNumberOfScalarComponents(3); imgData->GetPointData()->SetScalars(data); @@ -42,7 +42,6 @@ vtkImageData* VtkVisHelper::QImageToVtkImageData(QImage &img) vtkTexture* VtkVisHelper::QImageToVtkTexture(QImage &img) { - vtkSmartPointer<vtkImageData> imgData = QImageToVtkImageData(img); vtkTexture* texture = vtkTexture::New(); diff --git a/VtkVis/VtkVisHelper.h b/VtkVis/VtkVisHelper.h index 426a3f60b2338de002420b949a416f35e1e22e5a..088bd54aa46a3f5d0861246bb3b1853ef5fd5c83 100644 --- a/VtkVis/VtkVisHelper.h +++ b/VtkVis/VtkVisHelper.h @@ -15,11 +15,9 @@ class VtkVisHelper public: /// @brief Converts a QImage to vtkImageData. static vtkImageData* QImageToVtkImageData(QImage &img); - + /// @brief Converts a QImage-object into a vtkTexture-object static vtkTexture* QImageToVtkTexture(QImage &img); - - }; #endif // VTKVISHELPER_H diff --git a/VtkVis/VtkVisImageItem.cpp b/VtkVis/VtkVisImageItem.cpp index 49bf6243cf2d4b654409720382940a928784904a..2a896458b1c5329134a06cf084c628a6470b6796 100644 --- a/VtkVis/VtkVisImageItem.cpp +++ b/VtkVis/VtkVisImageItem.cpp @@ -4,32 +4,31 @@ */ // ** INCLUDES ** -#include "VtkVisImageItem.h" #include "VtkAlgorithmProperties.h" +#include "VtkVisImageItem.h" +#include "QVtkDataSetMapper.h" #include <vtkActor.h> #include <vtkDataSetMapper.h> -#include "QVtkDataSetMapper.h" #include <vtkImageAlgorithm.h> #include <vtkRenderer.h> #include <vtkSmartPointer.h> // export test -#include <vtkXMLImageDataWriter.h> #include <vtkImageActor.h> - +#include <vtkXMLImageDataWriter.h> VtkVisImageItem::VtkVisImageItem( - vtkAlgorithm* algorithm, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) -: VtkVisPipelineItem(algorithm, parentItem, data) + vtkAlgorithm* algorithm, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : VtkVisPipelineItem(algorithm, parentItem, data) { } VtkVisImageItem::VtkVisImageItem( - VtkCompositeFilter* compositeFilter, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) -: VtkVisPipelineItem(compositeFilter, parentItem, data) + VtkCompositeFilter* compositeFilter, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : VtkVisPipelineItem(compositeFilter, parentItem, data) { } @@ -55,26 +54,27 @@ void VtkVisImageItem::Initialize(vtkRenderer* renderer) if (vtkProps) setVtkProperties(vtkProps); /* - // Copy properties from parent - else + // Copy properties from parent + else + { + */ + VtkVisPipelineItem* parentItem = dynamic_cast<VtkVisPipelineItem*>(this->parentItem()); + while (parentItem) { -*/ - VtkVisPipelineItem* parentItem = dynamic_cast<VtkVisPipelineItem*>(this->parentItem()); - while (parentItem) + VtkAlgorithmProperties* parentProps = + dynamic_cast<VtkAlgorithmProperties*>(parentItem->algorithm()); + if (parentProps) { - VtkAlgorithmProperties* parentProps = dynamic_cast<VtkAlgorithmProperties*>(parentItem->algorithm()); - if (parentProps) - { - VtkAlgorithmProperties* newProps = new VtkAlgorithmProperties(); - newProps->SetScalarVisibility(parentProps->GetScalarVisibility()); - newProps->SetTexture(parentProps->GetTexture()); - setVtkProperties(newProps); - vtkProps = newProps; - parentItem = NULL; - } - else - parentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem->parentItem()); + VtkAlgorithmProperties* newProps = new VtkAlgorithmProperties(); + newProps->SetScalarVisibility(parentProps->GetScalarVisibility()); + newProps->SetTexture(parentProps->GetTexture()); + setVtkProperties(newProps); + vtkProps = newProps; + parentItem = NULL; } + else + parentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem->parentItem()); + } // } // Set active scalar to the desired one from VtkAlgorithmProperties @@ -82,12 +82,11 @@ void VtkVisImageItem::Initialize(vtkRenderer* renderer) if (vtkProps) { if (vtkProps->GetActiveAttribute().length() > 0) - { this->SetActiveAttribute(vtkProps->GetActiveAttribute()); - } else { - VtkVisPipelineItem* visParentItem = dynamic_cast<VtkVisPipelineItem*>(this->parentItem()); + VtkVisPipelineItem* visParentItem = + dynamic_cast<VtkVisPipelineItem*>(this->parentItem()); if (visParentItem) this->SetActiveAttribute(visParentItem->GetActiveAttribute()); if (vtkProps->GetTexture() != NULL) @@ -107,7 +106,8 @@ int VtkVisImageItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string &f vtkImageAlgorithm* algID = dynamic_cast<vtkImageAlgorithm*>(algorithm); if (algID) { - vtkSmartPointer<vtkXMLImageDataWriter> iWriter = vtkSmartPointer<vtkXMLImageDataWriter>::New(); + vtkSmartPointer<vtkXMLImageDataWriter> iWriter = + vtkSmartPointer<vtkXMLImageDataWriter>::New(); iWriter->SetInput(algID->GetOutputDataObject(0)); std::string filenameWithExt = filename; filenameWithExt.append(".vti"); diff --git a/VtkVis/VtkVisImageItem.h b/VtkVis/VtkVisImageItem.h index e83a72643238227ca95b3be13bf7050d954e6eeb..481bc91f36c101a021550460724c2e3920a3b079 100644 --- a/VtkVis/VtkVisImageItem.h +++ b/VtkVis/VtkVisImageItem.h @@ -4,7 +4,6 @@ * */ - #ifndef VTKVISIMAGEITEM_H #define VTKVISIMAGEITEM_H @@ -28,16 +27,15 @@ class VtkCompositeFilter; */ class VtkVisImageItem : public VtkVisPipelineItem { - public: /// @brief Constructor for a source/filter object. VtkVisImageItem(vtkAlgorithm* algorithm, - TreeItem* parentItem, - const QList<QVariant> data = QList<QVariant>()); + TreeItem* parentItem, + const QList<QVariant> data = QList<QVariant>()); /// @brief Constructor for composite filter VtkVisImageItem(VtkCompositeFilter* compositeFilter, TreeItem* parentItem, - const QList<QVariant> data = QList<QVariant>()); + const QList<QVariant> data = QList<QVariant>()); ~VtkVisImageItem(); @@ -50,7 +48,6 @@ protected: void setVtkProperties(VtkAlgorithmProperties* vtkProps); private: - }; #endif // VTKVISIMAGEITEM_H diff --git a/VtkVis/VtkVisPipeline.cpp b/VtkVis/VtkVisPipeline.cpp index d0442d10c9994e12fbfe3bfdd3693982031e8b77..0c12e4878ffaee64637ec4088829273489d4e67e 100644 --- a/VtkVis/VtkVisPipeline.cpp +++ b/VtkVis/VtkVisPipeline.cpp @@ -9,54 +9,54 @@ #include "VtkVisPipeline.h" //#include "Model.h" -#include "TreeModel.h" -#include "MshModel.h" -#include "MshItem.h" -#include "GeoTreeModel.h" #include "ConditionModel.h" -#include "StationTreeModel.h" -#include "VtkVisPipelineItem.h" -#include "VtkVisImageItem.h" -#include "VtkVisPointSetItem.h" -#include "VtkMeshSource.h" -#include "VtkAlgorithmProperties.h" -#include "VtkTrackedCamera.h" -#include "VtkFilterFactory.h" -#include "MeshQualityShortestLongestRatio.h" +#include "GeoTreeModel.h" +#include "MeshQualityEquiAngleSkew.h" #include "MeshQualityNormalisedArea.h" #include "MeshQualityNormalisedVolumes.h" -#include "MeshQualityEquiAngleSkew.h" +#include "MeshQualityShortestLongestRatio.h" +#include "MshItem.h" +#include "MshModel.h" +#include "StationTreeModel.h" +#include "TreeModel.h" +#include "VtkAlgorithmProperties.h" #include "VtkCompositeSelectionFilter.h" +#include "VtkFilterFactory.h" +#include "VtkMeshSource.h" +#include "VtkTrackedCamera.h" +#include "VtkVisImageItem.h" +#include "VtkVisPipelineItem.h" +#include "VtkVisPointSetItem.h" -#include <vtkSmartPointer.h> -#include <vtkRenderer.h> #include <vtkAlgorithm.h> -#include <vtkPointSet.h> -#include <vtkProp3D.h> -#include <vtkLight.h> -#include <vtkGenericDataObjectReader.h> -#include <vtkImageReader2.h> #include <vtkCamera.h> +#include <vtkGenericDataObjectReader.h> #include <vtkImageActor.h> -#include <vtkXMLPolyDataReader.h> +#include <vtkImageReader2.h> +#include <vtkLight.h> +#include <vtkPointSet.h> +#include <vtkProp3D.h> +#include <vtkRenderer.h> +#include <vtkSmartPointer.h> +#include <vtkTransformFilter.h> #include <vtkXMLImageDataReader.h> +#include <vtkXMLPolyDataReader.h> #include <vtkXMLRectilinearGridReader.h> #include <vtkXMLStructuredGridReader.h> #include <vtkXMLUnstructuredGridReader.h> -#include <vtkTransformFilter.h> +#include <vtkCellData.h> #include <vtkFieldData.h> #include <vtkPointData.h> -#include <vtkCellData.h> -#include <QString> -#include <QTime> -#include <QFileInfo> #include <QColor> +#include <QFileInfo> #include <QSettings> +#include <QString> +#include <QTime> VtkVisPipeline::VtkVisPipeline( vtkRenderer* renderer, QObject* parent /*= 0*/ ) -: TreeModel(parent), _renderer(renderer) + : TreeModel(parent), _renderer(renderer) { QList<QVariant> rootData; rootData << "Object name" << "Visible"; @@ -72,7 +72,7 @@ VtkVisPipeline::VtkVisPipeline( vtkRenderer* renderer, QObject* parent /*= 0*/ ) } bool VtkVisPipeline::setData( const QModelIndex &index, const QVariant &value, - int role /* = Qt::EditRole */ ) + int role /* = Qt::EditRole */ ) { emit vtkVisPipelineChanged(); @@ -85,7 +85,8 @@ void VtkVisPipeline::addLight(const GEOLIB::Point &pos) for (std::list<vtkLight*>::iterator it = _lights.begin(); it != _lights.end(); ++it) { (*it)->GetPosition(lightPos); - if (pos[0] == lightPos[0] && pos[1] == lightPos[1] && pos[2] == lightPos[2]) return; + if (pos[0] == lightPos[0] && pos[1] == lightPos[1] && pos[2] == lightPos[2]) + return; } vtkLight* l = vtkLight::New(); l->SetPosition(pos[0], pos[1], pos[2]); @@ -99,7 +100,8 @@ vtkLight* VtkVisPipeline::getLight(const GEOLIB::Point &pos) const for (std::list<vtkLight*>::const_iterator it = _lights.begin(); it != _lights.end(); ++it) { (*it)->GetPosition(lightPos); - if (pos[0] == lightPos[0] && pos[1] == lightPos[1] && pos[2] == lightPos[2]) return (*it); + if (pos[0] == lightPos[0] && pos[1] == lightPos[1] && pos[2] == lightPos[2]) + return *it; } return NULL; } @@ -123,7 +125,9 @@ void VtkVisPipeline::removeLight(const GEOLIB::Point &pos) const QColor VtkVisPipeline::getBGColor() const { double* color = _renderer->GetBackground(); - QColor c(static_cast<int>(color[0]*255), static_cast<int>(color[1]*255), static_cast<int>(color[2]*255)); + QColor c(static_cast<int>(color[0] * 255), + static_cast<int>(color[1] * 255), + static_cast<int>(color[2] * 255)); return c; } @@ -154,12 +158,12 @@ Qt::ItemFlags VtkVisPipeline::flags( const QModelIndex &index ) const void VtkVisPipeline::loadFromFile(QString filename) { - #ifndef NDEBUG - QTime myTimer; - myTimer.start(); - std::cout << "VTK Read: " << filename.toStdString() << - std::endl << std::flush; - #endif +#ifndef NDEBUG + QTime myTimer; + myTimer.start(); + std::cout << "VTK Read: " << filename.toStdString() << + std::endl << std::flush; +#endif if (filename.size() > 0) { @@ -176,7 +180,8 @@ void VtkVisPipeline::loadFromFile(QString filename) reader = vtkXMLUnstructuredGridReader::New(); else if (filename.endsWith("vtk")) { - vtkGenericDataObjectReader* oldStyleReader = vtkGenericDataObjectReader::New(); + vtkGenericDataObjectReader* oldStyleReader = + vtkGenericDataObjectReader::New(); oldStyleReader->SetFileName(filename.toStdString().c_str()); oldStyleReader->ReadAllFieldsOn(); oldStyleReader->ReadAllScalarsOn(); @@ -188,7 +193,8 @@ void VtkVisPipeline::loadFromFile(QString filename) addPipelineItem(oldStyleReader); } else - std::cout << "Error loading vtk file: not a valid vtkDataSet." << std::endl; + std::cout << "Error loading vtk file: not a valid vtkDataSet." << + std::endl; return; } @@ -213,9 +219,9 @@ void VtkVisPipeline::loadFromFile(QString filename) //reader->Delete(); } - #ifndef NDEBUG - std::cout << myTimer.elapsed() << " ms" << std::endl; - #endif +#ifndef NDEBUG + std::cout << myTimer.elapsed() << " ms" << std::endl; +#endif } void VtkVisPipeline::setGlobalSuperelevation(double factor) const @@ -233,7 +239,9 @@ void VtkVisPipeline::setGlobalSuperelevation(double factor) const emit vtkVisPipelineChanged(); } -void VtkVisPipeline::addPipelineItem(GeoTreeModel* model, const std::string &name, GEOLIB::GEOTYPE type) +void VtkVisPipeline::addPipelineItem(GeoTreeModel* model, + const std::string &name, + GEOLIB::GEOTYPE type) { addPipelineItem(model->vtkSource(name, type)); } @@ -243,7 +251,9 @@ void VtkVisPipeline::addPipelineItem(StationTreeModel* model, const std::string addPipelineItem(model->vtkSource(name)); } -void VtkVisPipeline::addPipelineItem(ConditionModel* model, const std::string &name, FEMCondition::CondType type) +void VtkVisPipeline::addPipelineItem(ConditionModel* model, + const std::string &name, + FEMCondition::CondType type) { addPipelineItem(model->vtkSource(name, type)); } @@ -259,11 +269,12 @@ void VtkVisPipeline::addPipelineItem(VtkVisPipelineItem* item, const QModelIndex TreeItem* parentItem = item->parentItem(); parentItem->appendChild(item); - if (!parent.isValid()) // Set global superelevation on source objects + if (!parent.isValid()) // Set global superelevation on source objects { QSettings settings("UFZ, OpenGeoSys-5"); if (dynamic_cast<vtkImageAlgorithm*>(item->algorithm()) == NULL) // if not an image - item->setScale(1.0, 1.0, settings.value("globalSuperelevation", 1.0).toDouble()); + item->setScale(1.0, 1.0, settings.value("globalSuperelevation", + 1.0).toDouble()); } int parentChildCount = parentItem->childCount(); @@ -284,7 +295,7 @@ void VtkVisPipeline::addPipelineItem(VtkVisPipelineItem* item, const QModelIndex } void VtkVisPipeline::addPipelineItem( vtkAlgorithm* source, - QModelIndex parent /* = QModelindex() */) + QModelIndex parent /* = QModelindex() */) { TreeItem* parentItem = getItem(parent); @@ -294,9 +305,10 @@ void VtkVisPipeline::addPipelineItem( vtkAlgorithm* source, QList<QVariant> itemData; QString itemName; - if (!parent.isValid()) // if source object + if (!parent.isValid()) // if source object { - vtkGenericDataObjectReader* reader = dynamic_cast<vtkGenericDataObjectReader*>(source); + vtkGenericDataObjectReader* reader = + dynamic_cast<vtkGenericDataObjectReader*>(source); vtkImageReader2* imageReader = dynamic_cast<vtkImageReader2*>(source); VtkAlgorithmProperties* props = dynamic_cast<VtkAlgorithmProperties*>(source); if (reader) @@ -323,12 +335,16 @@ void VtkVisPipeline::addPipelineItem( vtkAlgorithm* source, VtkVisPipelineItem* item(NULL); vtkImageAlgorithm* alg = dynamic_cast<vtkImageAlgorithm*>(source); - if (alg) item = new VtkVisImageItem(source, parentItem, itemData); - else item = new VtkVisPointSetItem(source, parentItem, itemData); + if (alg) + item = new VtkVisImageItem(source, parentItem, itemData); + else + item = new VtkVisPointSetItem(source, parentItem, itemData); this->addPipelineItem(item, parent); } -void VtkVisPipeline::removeSourceItem(GeoTreeModel* model, const std::string &name, GEOLIB::GEOTYPE type) +void VtkVisPipeline::removeSourceItem(GeoTreeModel* model, + const std::string &name, + GEOLIB::GEOTYPE type) { for (int i = 0; i < _rootItem->childCount(); i++) { @@ -341,7 +357,9 @@ void VtkVisPipeline::removeSourceItem(GeoTreeModel* model, const std::string &na } } -void VtkVisPipeline::removeSourceItem(ConditionModel* model, const std::string &name, FEMCondition::CondType type) +void VtkVisPipeline::removeSourceItem(ConditionModel* model, + const std::string &name, + FEMCondition::CondType type) { for (int i = 0; i < _rootItem->childCount(); i++) { @@ -412,7 +430,8 @@ void VtkVisPipeline::listArrays(vtkDataSet* dataSet) if (dataSet) { vtkPointData* pointData = dataSet->GetPointData(); - std::cout << " #point data arrays: " << pointData->GetNumberOfArrays() << std::endl; + std::cout << " #point data arrays: " << pointData->GetNumberOfArrays() << + std::endl; for (int i = 0; i < pointData->GetNumberOfArrays(); i++) std::cout << " Name: " << pointData->GetArrayName(i) << std::endl; @@ -427,7 +446,8 @@ void VtkVisPipeline::listArrays(vtkDataSet* dataSet) void VtkVisPipeline::checkMeshQuality(VtkMeshSource* source, MshQualityType::type t) { - if (source) { + if (source) + { const MeshLib::CFEMesh* mesh = source->GetGrid()->getCFEMesh(); MeshLib::MeshQualityChecker* checker (NULL); if (t == MshQualityType::EDGERATIO) @@ -438,8 +458,12 @@ void VtkVisPipeline::checkMeshQuality(VtkMeshSource* source, MshQualityType::typ checker = new MeshLib::MeshQualityNormalisedVolumes(mesh); else if (t == MshQualityType::EQUIANGLESKEW) checker = new MeshLib::MeshQualityEquiAngleSkew(mesh); - else { - std::cout << "Error in VtkVisPipeline::checkMeshQuality() - Unknown MshQualityType..." << std::endl; + else + { + std::cout << + "Error in VtkVisPipeline::checkMeshQuality() - Unknown MshQualityType..." + << + std::endl; delete checker; return; } @@ -448,17 +472,25 @@ void VtkVisPipeline::checkMeshQuality(VtkMeshSource* source, MshQualityType::typ std::vector<double> const &quality (checker->getMeshQuality()); int nSources = this->_rootItem->childCount(); - for (int i=0; i<nSources; i++) + for (int i = 0; i < nSources; i++) { - VtkVisPipelineItem* parentItem = static_cast<VtkVisPipelineItem*>(_rootItem->child(i)); + VtkVisPipelineItem* parentItem = + static_cast<VtkVisPipelineItem*>(_rootItem->child(i)); if (parentItem->algorithm() == source) { QList<QVariant> itemData; - itemData << "MeshQuality: " + QString::fromStdString(MshQualityType2String(t)) << true; - - VtkCompositeFilter* filter = VtkFilterFactory::CreateCompositeFilter("VtkCompositeSelectionFilter", parentItem->transformFilter()); - static_cast<VtkCompositeSelectionFilter*>(filter)->setSelectionArray(quality); - VtkVisPointSetItem* item = new VtkVisPointSetItem(filter, parentItem, itemData); + itemData << "MeshQuality: " + QString::fromStdString( + MshQualityType2String(t)) << true; + + VtkCompositeFilter* filter = + VtkFilterFactory::CreateCompositeFilter( + "VtkCompositeSelectionFilter", + parentItem->transformFilter()); + static_cast<VtkCompositeSelectionFilter*>(filter)-> + setSelectionArray(quality); + VtkVisPointSetItem* item = new VtkVisPointSetItem(filter, + parentItem, + itemData); this->addPipelineItem(item, this->createIndex(i, 0, item)); } } @@ -474,9 +506,9 @@ void VtkVisPipeline::checkMeshQuality(VtkMeshSource* source, MshQualityType::typ checker->getHistogramm(histogramm); std::ofstream out ("mesh_histogramm.txt"); const size_t histogramm_size (histogramm.size()); - for (size_t k(0); k<histogramm_size; k++) { - out << k/static_cast<double>(histogramm_size) << " " << histogramm[k] << std::endl; - } + for (size_t k(0); k < histogramm_size; k++) + out << k / static_cast<double>(histogramm_size) << " " << histogramm[k] << + std::endl; out.close (); delete checker; diff --git a/VtkVis/VtkVisPipeline.h b/VtkVis/VtkVisPipeline.h index 6dc5e04b6c3f4a08ae08a072b03e303c56f95fd1..6218aca0798aa5f804f4f90147c787b299aeab30 100644 --- a/VtkVis/VtkVisPipeline.h +++ b/VtkVis/VtkVisPipeline.h @@ -4,21 +4,20 @@ * */ - #ifndef VTKVISPIPELINE_H #define VTKVISPIPELINE_H // ** INCLUDES ** -#include "Configure.h" -#include "TreeModel.h" #include "Color.h" -#include "Point.h" +#include "Configure.h" +#include "FEMCondition.h" #include "GeoType.h" #include "MSHEnums.h" -#include "FEMCondition.h" +#include "Point.h" +#include "TreeModel.h" -#include <QVector> #include <QMap> +#include <QVector> class vtkAlgorithm; class vtkDataSet; @@ -77,7 +76,7 @@ public: /// \brief Defaults to on. void resetCameraOnAddOrRemove(bool reset) { _resetCameraOnAddOrRemove = reset; } - + /// \brief Sets a global superelevation factor on all source items and resets /// the factor on other items to 1. void setGlobalSuperelevation(double factor) const; @@ -86,7 +85,9 @@ public slots: /// \brief Adds the given Model to the pipeline. void addPipelineItem(MshModel* model, const QModelIndex &idx); void addPipelineItem(GeoTreeModel* model, const std::string &name, GEOLIB::GEOTYPE type); - void addPipelineItem(ConditionModel* model, const std::string &name, FEMCondition::CondType type); + void addPipelineItem(ConditionModel* model, + const std::string &name, + FEMCondition::CondType type); void addPipelineItem(StationTreeModel* model, const std::string &name); void addPipelineItem(VtkVisPipelineItem* item, const QModelIndex &parent); @@ -96,7 +97,9 @@ public slots: /// \brief Removes the given Model (and all attached vtkAlgorithms) from the pipeline. void removeSourceItem(MshModel* model, const QModelIndex &idx); void removeSourceItem(GeoTreeModel* model, const std::string &name, GEOLIB::GEOTYPE type); - void removeSourceItem(ConditionModel* model, const std::string &name, FEMCondition::CondType type); + void removeSourceItem(ConditionModel* model, + const std::string &name, + FEMCondition::CondType type); void removeSourceItem(StationTreeModel* model, const std::string &name); /// \brief Removes the vtkAlgorithm at the given QModelIndex (and all attached @@ -118,7 +121,6 @@ private: signals: /// \brief Is emitted when a pipeline item was added or removed. void vtkVisPipelineChanged() const; - }; #endif // VTKVISPIPELINE_H diff --git a/VtkVis/VtkVisPipelineItem.cpp b/VtkVis/VtkVisPipelineItem.cpp index 0d592d333ae7333db954d77546a9f63b1fcae2ad..2e889ef8878cb436644974d04b1c4b0b8a83852b 100644 --- a/VtkVis/VtkVisPipelineItem.cpp +++ b/VtkVis/VtkVisPipelineItem.cpp @@ -6,16 +6,16 @@ */ // ** INCLUDES ** -#include "VtkVisPipelineItem.h" #include "VtkAlgorithmProperties.h" +#include "VtkVisPipelineItem.h" -#include <vtkAlgorithm.h> -#include <vtkPointSet.h> -#include <vtkDataSetMapper.h> #include "QVtkDataSetMapper.h" #include <vtkActor.h> -#include <vtkRenderer.h> +#include <vtkAlgorithm.h> +#include <vtkDataSetMapper.h> +#include <vtkPointSet.h> #include <vtkProperty.h> +#include <vtkRenderer.h> #include <vtkSmartPointer.h> #include <vtkTextureMapToPlane.h> @@ -25,32 +25,31 @@ #include "VtkCompositeFilter.h" -#include <vtkPointData.h> #include <vtkCellData.h> +#include <vtkPointData.h> #ifdef OGS_USE_OPENSG #include "vtkOsgConverter.h" #include <OpenSG/OSGSceneFileHandler.h> #endif - VtkVisPipelineItem::VtkVisPipelineItem( - vtkAlgorithm* algorithm, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) -: TreeItem(data, parentItem), _actor(NULL), _algorithm(algorithm), _mapper(NULL), _renderer(NULL), + vtkAlgorithm* algorithm, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : TreeItem(data, + parentItem), _actor(NULL), _algorithm(algorithm), _mapper(NULL), + _renderer(NULL), _compositeFilter(NULL) { VtkVisPipelineItem* visParentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem); if (parentItem->parentItem()) - { _algorithm->SetInputConnection(visParentItem->algorithm()->GetOutputPort()); - } } VtkVisPipelineItem::VtkVisPipelineItem( - VtkCompositeFilter* compositeFilter, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) -: TreeItem(data, parentItem), _actor(NULL), _mapper(NULL), _renderer(NULL), + VtkCompositeFilter* compositeFilter, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : TreeItem(data, parentItem), _actor(NULL), _mapper(NULL), _renderer(NULL), _compositeFilter(compositeFilter) { _algorithm = _compositeFilter->GetOutputAlgorithm(); @@ -76,9 +75,7 @@ VtkVisPipelineItem* VtkVisPipelineItem::child( int row ) const QVariant VtkVisPipelineItem::data( int column ) const { if (column == 1) - { return isVisible(); - } else return TreeItem::data(column); } @@ -92,7 +89,6 @@ bool VtkVisPipelineItem::setData( int column, const QVariant &value ) } else return TreeItem::setData(column, value); - } bool VtkVisPipelineItem::isVisible() const { @@ -112,14 +108,17 @@ int VtkVisPipelineItem::writeToFile(const std::string &filename) const { if (filename.substr(filename.size() - 4).find("os") != std::string::npos) { - #ifdef OGS_USE_OPENSG +#ifdef OGS_USE_OPENSG vtkOsgConverter osgConverter(static_cast<vtkActor*>(_actor)); if(osgConverter.WriteAnActor()) - OSG::SceneFileHandler::the().write(osgConverter.GetOsgNode(), filename.c_str()); - #else - QMessageBox::warning(NULL, "Functionality not implemented", - "Sorry but this program was not compiled with OpenSG support."); - #endif + OSG::SceneFileHandler::the().write( + osgConverter.GetOsgNode(), filename.c_str()); +#else + QMessageBox::warning( + NULL, + "Functionality not implemented", + "Sorry but this program was not compiled with OpenSG support."); +#endif return 0; } @@ -148,12 +147,14 @@ void VtkVisPipelineItem::SetScalarVisibility( bool on ) void VtkVisPipelineItem::setScale(double x, double y, double z) const { - (void)x; (void)y, (void)z; + (void)x; + (void)y, (void)z; } void VtkVisPipelineItem::setTranslation(double x, double y, double z) const { - (void)x; (void)y, (void)z; + (void)x; + (void)y, (void)z; } void VtkVisPipelineItem::setScaleOnChildren(double x, double y, double z) const diff --git a/VtkVis/VtkVisPipelineItem.h b/VtkVis/VtkVisPipelineItem.h index f14fda743ea2ce344e656de05c731092c331c511..9067eccebeb9633090cbc909a6f31a0df552dd4e 100644 --- a/VtkVis/VtkVisPipelineItem.h +++ b/VtkVis/VtkVisPipelineItem.h @@ -4,13 +4,12 @@ * */ - #ifndef VTKVISPIPELINEITEM_H #define VTKVISPIPELINEITEM_H // ** INCLUDES ** -#include "TreeItem.h" #include "Configure.h" +#include "TreeItem.h" #include <QList> #include <QMap> @@ -42,12 +41,12 @@ class VtkVisPipelineItem : /*public QObject,*/ public TreeItem public: /// @brief Constructor for a source/filter object. VtkVisPipelineItem(vtkAlgorithm* algorithm, - TreeItem* parentItem, - const QList<QVariant> data = QList<QVariant>()); + TreeItem* parentItem, + const QList<QVariant> data = QList<QVariant>()); /// @brief Constructor for composite filter VtkVisPipelineItem(VtkCompositeFilter* compositeFilter, TreeItem* parentItem, - const QList<QVariant> data = QList<QVariant>()); + const QList<QVariant> data = QList<QVariant>()); ~VtkVisPipelineItem(); @@ -71,7 +70,7 @@ public: virtual const QString GetActiveAttribute() const { return QString(""); } // Dummy for implementation in derived classes - virtual void SetActiveAttribute(const QString& str) { (void)str; }; + virtual void SetActiveAttribute(const QString& str) { (void)str; } /// @brief Returns the mapper QVtkDataSetMapper* mapper() const { return _mapper; } @@ -99,7 +98,7 @@ public: /// @brief Sets the geometry and date scaling recursively on all children of /// this item. void setScaleOnChildren(double x, double y, double z) const; - + protected: vtkProp3D* _actor; vtkAlgorithm* _algorithm; @@ -110,9 +109,8 @@ protected: virtual int callVTKWriter(vtkAlgorithm* algorithm, const std::string &filename) const; void SetScalarVisibility(bool on); - -private: +private: }; #endif // VTKVISPIPELINEITEM_H diff --git a/VtkVis/VtkVisPipelineView.cpp b/VtkVis/VtkVisPipelineView.cpp index 88eff2250610002f579a93ddaced22d5e32266e2..e55ab82370671bd3824dd77a55d88b6ba8375b87 100644 --- a/VtkVis/VtkVisPipelineView.cpp +++ b/VtkVis/VtkVisPipelineView.cpp @@ -8,36 +8,36 @@ // ** INCLUDES ** #include "VtkVisPipelineView.h" -#include "VtkVisPipelineItem.h" -#include "VtkVisPipeline.h" #include "CheckboxDelegate.h" +#include "VtkVisPipeline.h" +#include "VtkVisPipelineItem.h" -#include <vtkProp3D.h> #include <vtkDataSetMapper.h> +#include <vtkProp3D.h> -#include <QMenu> +#include <QAbstractItemModel> #include <QContextMenuEvent> #include <QFileDialog> -#include <QSettings> #include <QHeaderView> -#include <QAbstractItemModel> +#include <QMenu> +#include <QSettings> //image to mesh conversion +#include "VtkGeoImageSource.h" #include "VtkMeshConverter.h" #include <vtkDataObject.h> #include <vtkImageData.h> #include <vtkSmartPointer.h> -#include "VtkGeoImageSource.h" #include "msh_mesh.h" -#include <vtkUnstructuredGrid.h> -#include <vtkXMLUnstructuredGridReader.h> #include <vtkGenericDataObjectReader.h> -#include <vtkUnstructuredGridAlgorithm.h> #include <vtkTransformFilter.h> +#include <vtkUnstructuredGrid.h> +#include <vtkUnstructuredGridAlgorithm.h> +#include <vtkXMLUnstructuredGridReader.h> VtkVisPipelineView::VtkVisPipelineView( QWidget* parent /*= 0*/ ) -: QTreeView(parent) + : QTreeView(parent) { this->setItemsExpandable(false); //setEditTriggers(QAbstractItemView::AllEditTriggers); @@ -50,7 +50,7 @@ VtkVisPipelineView::VtkVisPipelineView( QWidget* parent /*= 0*/ ) void VtkVisPipelineView::setModel(QAbstractItemModel* model) { QTreeView::setModel(model); - + // Move Visisble checkbox to the left. // This is done here because at constructor time there arent any sections. this->header()->moveSection(1, 0); @@ -62,21 +62,27 @@ void VtkVisPipelineView::contextMenuEvent( QContextMenuEvent* event ) if (index.isValid()) { // check object type - vtkAlgorithm* algorithm = static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())->getItem(this->selectionModel()->currentIndex()))->algorithm(); + vtkAlgorithm* algorithm = + static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model()) + -> + getItem(this->selectionModel()-> + currentIndex()))->algorithm(); int objectType = algorithm->GetOutputDataObject(0)->GetDataObjectType(); VtkAlgorithmProperties* vtkProps = dynamic_cast<VtkAlgorithmProperties*>(algorithm); - bool isSourceItem = (this->selectionModel()->currentIndex().parent().isValid()) ? 0 : 1; + bool isSourceItem = + (this->selectionModel()->currentIndex().parent().isValid()) ? 0 : 1; QMenu menu; QAction* addFilterAction = menu.addAction("Add filter..."); QAction* addLUTAction(NULL); QAction* addMeshingAction(NULL); - if (objectType == VTK_IMAGE_DATA) + if (objectType == VTK_IMAGE_DATA) { isSourceItem = false; // this exception is needed as image object are only displayed in the vis-pipeline addMeshingAction = menu.addAction("Convert Image to Mesh..."); - connect(addMeshingAction, SIGNAL(triggered()), this, SLOT(convertImageToMesh())); + connect(addMeshingAction, SIGNAL(triggered()), this, + SLOT(convertImageToMesh())); } else { @@ -85,24 +91,28 @@ void VtkVisPipelineView::contextMenuEvent( QContextMenuEvent* event ) } QAction* addConvertToCFEMeshAction(NULL); - if (objectType == VTK_UNSTRUCTURED_GRID) + if (objectType == VTK_UNSTRUCTURED_GRID) { addConvertToCFEMeshAction = menu.addAction("Convert to Mesh..."); - connect(addConvertToCFEMeshAction, SIGNAL(triggered()), this, SLOT(convertVTKToOGSMesh())); + connect(addConvertToCFEMeshAction, SIGNAL(triggered()), this, + SLOT(convertVTKToOGSMesh())); } menu.addSeparator(); QAction* exportVtkAction = menu.addAction("Export as VTK"); QAction* exportOsgAction = menu.addAction("Export as OpenSG"); QAction* removeAction = NULL; - if (!isSourceItem || vtkProps==NULL) + if (!isSourceItem || vtkProps == NULL) { removeAction = menu.addAction("Remove"); - connect(removeAction, SIGNAL(triggered()), this, SLOT(removeSelectedPipelineItem())); + connect(removeAction, SIGNAL(triggered()), this, + SLOT(removeSelectedPipelineItem())); } connect(addFilterAction, SIGNAL(triggered()), this, SLOT(addPipelineFilterItem())); - connect(exportVtkAction, SIGNAL(triggered()), this, SLOT(exportSelectedPipelineItemAsVtk())); - connect(exportOsgAction, SIGNAL(triggered()), this, SLOT(exportSelectedPipelineItemAsOsg())); + connect(exportVtkAction, SIGNAL(triggered()), this, + SLOT(exportSelectedPipelineItemAsVtk())); + connect(exportOsgAction, SIGNAL(triggered()), this, + SLOT(exportSelectedPipelineItemAsOsg())); menu.exec(event->globalPos()); } @@ -113,10 +123,13 @@ void VtkVisPipelineView::exportSelectedPipelineItemAsVtk() QSettings settings("UFZ", "OpenGeoSys-5"); QModelIndex idx = this->selectionModel()->currentIndex(); QString filename = QFileDialog::getSaveFileName(this, "Export object to vtk-file", - settings.value("lastExportedFileDirectory").toString(),"(*.*)"); + settings.value( + "lastExportedFileDirectory"). + toString(),"(*.*)"); if (!filename.isEmpty()) { - static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())->getItem(idx))->writeToFile(filename.toStdString()); + static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> + getItem(idx))->writeToFile(filename.toStdString()); QDir dir = QDir(filename); settings.setValue("lastExportedFileDirectory", dir.absolutePath()); } @@ -127,10 +140,13 @@ void VtkVisPipelineView::exportSelectedPipelineItemAsOsg() QSettings settings("UFZ", "OpenGeoSys-5"); QModelIndex idx = this->selectionModel()->currentIndex(); QString filename = QFileDialog::getSaveFileName(this, "Export object to OpenSG file", - settings.value("lastExportedFileDirectory").toString(), "OpenSG file (*.osb)"); + settings.value( + "lastExportedFileDirectory"). + toString(), "OpenSG file (*.osb)"); if (!filename.isEmpty()) { - static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())->getItem(idx))->writeToFile(filename.toStdString()); + static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> + getItem(idx))->writeToFile(filename.toStdString()); QDir dir = QDir(filename); settings.setValue("lastExportedFileDirectory", dir.absolutePath()); } @@ -148,12 +164,18 @@ void VtkVisPipelineView::addPipelineFilterItem() void VtkVisPipelineView::convertImageToMesh() { - vtkSmartPointer<vtkAlgorithm> algorithm = static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())->getItem(this->selectionModel()->currentIndex()))->algorithm(); + vtkSmartPointer<vtkAlgorithm> algorithm = + static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> + getItem(this-> + selectionModel() + ->currentIndex()))->algorithm(); vtkSmartPointer<VtkGeoImageSource> imageSource = VtkGeoImageSource::SafeDownCast(algorithm); vtkSmartPointer<vtkImageData> image = imageSource->GetOutput(); - MeshLib::CFEMesh* mesh = VtkMeshConverter::convertImgToMesh(image, imageSource->getOrigin(), imageSource->getSpacing()); + MeshLib::CFEMesh* mesh = VtkMeshConverter::convertImgToMesh(image, + imageSource->getOrigin(), + imageSource->getSpacing()); // now do something with the mesh (save, display, whatever... ) std::string msh_name("NewMesh"); emit meshAdded(mesh, msh_name); @@ -161,18 +183,26 @@ void VtkVisPipelineView::convertImageToMesh() void VtkVisPipelineView::convertVTKToOGSMesh() { - vtkSmartPointer<vtkAlgorithm> algorithm = static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())->getItem(this->selectionModel()->currentIndex()))->algorithm(); - + vtkSmartPointer<vtkAlgorithm> algorithm = + static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> + getItem(this-> + selectionModel() + ->currentIndex()))->algorithm(); + vtkUnstructuredGrid* grid(NULL); vtkUnstructuredGridAlgorithm* ugAlg = vtkUnstructuredGridAlgorithm::SafeDownCast(algorithm); - if (ugAlg) grid = ugAlg->GetOutput(); + if (ugAlg) + grid = ugAlg->GetOutput(); else { - vtkGenericDataObjectReader* dataReader = vtkGenericDataObjectReader::SafeDownCast(algorithm); // for old filetypes - if (dataReader) grid = vtkUnstructuredGrid::SafeDownCast(dataReader->GetOutput()); + vtkGenericDataObjectReader* dataReader = vtkGenericDataObjectReader::SafeDownCast( + algorithm); // for old filetypes + if (dataReader) + grid = vtkUnstructuredGrid::SafeDownCast(dataReader->GetOutput()); else { - vtkXMLUnstructuredGridReader* xmlReader = vtkXMLUnstructuredGridReader::SafeDownCast(algorithm); // for new filetypes + vtkXMLUnstructuredGridReader* xmlReader = + vtkXMLUnstructuredGridReader::SafeDownCast(algorithm); // for new filetypes grid = vtkUnstructuredGrid::SafeDownCast(xmlReader->GetOutput()); } } @@ -181,7 +211,8 @@ void VtkVisPipelineView::convertVTKToOGSMesh() emit meshAdded(mesh, msh_name); } -void VtkVisPipelineView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) +void VtkVisPipelineView::selectionChanged( const QItemSelection &selected, + const QItemSelection &deselected ) { QTreeView::selectionChanged(selected, deselected); @@ -191,7 +222,10 @@ void VtkVisPipelineView::selectionChanged( const QItemSelection &selected, const VtkVisPipelineItem* item = static_cast<VtkVisPipelineItem*>(index.internalPointer()); emit actorSelected(item->actor()); emit itemSelected(item); - if (item->transformFilter()) emit dataObjectSelected(vtkDataObject::SafeDownCast(item->transformFilter()->GetOutputDataObject(0))); + if (item->transformFilter()) + emit dataObjectSelected(vtkDataObject::SafeDownCast( + item->transformFilter()-> + GetOutputDataObject(0))); } else { @@ -199,7 +233,6 @@ void VtkVisPipelineView::selectionChanged( const QItemSelection &selected, const emit itemSelected(NULL); emit dataObjectSelected(NULL); } - } void VtkVisPipelineView::selectItem( vtkProp3D* actor ) @@ -217,18 +250,24 @@ void VtkVisPipelineView::selectItem( vtkProp3D* actor ) void VtkVisPipelineView::addColorTable() { - VtkVisPipelineItem* item ( static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())->getItem(this->selectionModel()->currentIndex())) ); + VtkVisPipelineItem* item ( + static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> + getItem( + this->selectionModel()->currentIndex())) ); const QString array_name = item->GetActiveAttribute(); QSettings settings("UFZ", "OpenGeoSys-5"); QString fileName = QFileDialog::getOpenFileName(this, "Select color table", - settings.value("lastOpenedTextureFileDirectory").toString(), - "Color table files (*.lut);;"); + settings.value( + "lastOpenedTextureFileDirectory"). + toString(), + "Color table files (*.lut);;"); QFileInfo fi(fileName); if (fi.suffix().toLower() == "lut") { - VtkAlgorithmProperties* props = dynamic_cast<VtkAlgorithmProperties*>(item->algorithm()); + VtkAlgorithmProperties* props = + dynamic_cast<VtkAlgorithmProperties*>(item->algorithm()); if (props) { const std::string file (fileName.toStdString()); diff --git a/VtkVis/VtkVisPipelineView.h b/VtkVis/VtkVisPipelineView.h index 15f04664d7e515699b723fbd3fb3af0dd9c8d046..67590b282e52789d177b2f949cbf66a1715d0dca 100644 --- a/VtkVis/VtkVisPipelineView.h +++ b/VtkVis/VtkVisPipelineView.h @@ -4,7 +4,6 @@ * */ - #ifndef VTKVISPIPELINEVIEW_H #define VTKVISPIPELINEVIEW_H @@ -17,8 +16,9 @@ class VtkVisPipelineItem; class vtkProp3D; class vtkDataObject; -namespace MeshLib { - class CFEMesh; +namespace MeshLib +{ +class CFEMesh; } /** @@ -31,7 +31,7 @@ class VtkVisPipelineView : public QTreeView public: /// @brief Constructor. VtkVisPipelineView(QWidget* parent = 0); - + /// @brief Overridden to set model specific header properties. virtual void setModel(QAbstractItemModel* model); @@ -47,7 +47,7 @@ private: private slots: /// Adds a color lookup table to the current scalar array of the selected pipeline item. void addColorTable(); - + /// Exports the currently selected item as a VTK file void exportSelectedPipelineItemAsVtk(); diff --git a/VtkVis/VtkVisPointSetItem.cpp b/VtkVis/VtkVisPointSetItem.cpp index e7ca0600f89a8cc8ec06434eb21d3b63d1505564..b01c5ee15c98798aecd9173ddbb72c791826a637 100644 --- a/VtkVis/VtkVisPointSetItem.cpp +++ b/VtkVis/VtkVisPointSetItem.cpp @@ -4,59 +4,62 @@ */ // ** INCLUDES ** -#include "VtkVisPointSetItem.h" #include "VtkAlgorithmProperties.h" +#include "VtkVisPointSetItem.h" +#include "QVtkDataSetMapper.h" #include <vtkActor.h> #include <vtkCellData.h> #include <vtkDataSetMapper.h> -#include "QVtkDataSetMapper.h" #include <vtkImageAlgorithm.h> #include <vtkPointData.h> #include <vtkRenderer.h> #include <vtkSmartPointer.h> -#include <vtkTransformFilter.h> #include <vtkTransform.h> +#include <vtkTransformFilter.h> #include <QObject> #include <QRegExp> // export test #include <vtkPolyDataAlgorithm.h> -#include <vtkXMLPolyDataWriter.h> +#include <vtkTriangleFilter.h> +#include <vtkTubeFilter.h> #include <vtkUnstructuredGridAlgorithm.h> +#include <vtkXMLPolyDataWriter.h> #include <vtkXMLUnstructuredGridWriter.h> -#include <vtkTubeFilter.h> -#include <vtkTriangleFilter.h> #include <vtkDataSetAttributes.h> - - VtkVisPointSetItem::VtkVisPointSetItem( - vtkAlgorithm* algorithm, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) - : VtkVisPipelineItem(algorithm, parentItem, data), _transformFilter(NULL), _activeAttribute("") +VtkVisPointSetItem::VtkVisPointSetItem( + vtkAlgorithm* algorithm, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : VtkVisPipelineItem(algorithm, parentItem, + data), _transformFilter(NULL), _activeAttribute("") +{ + VtkVisPipelineItem* visParentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem); + if (parentItem->parentItem()) { - VtkVisPipelineItem* visParentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem); - if (parentItem->parentItem()) + if (dynamic_cast<vtkImageAlgorithm*>(visParentItem->algorithm())) + _algorithm->SetInputConnection(visParentItem->algorithm()->GetOutputPort()); + else { - if (dynamic_cast<vtkImageAlgorithm*>(visParentItem->algorithm())) - _algorithm->SetInputConnection(visParentItem->algorithm()->GetOutputPort()); - else - { - VtkVisPointSetItem* pointSetItem = dynamic_cast<VtkVisPointSetItem*>(parentItem); - if (pointSetItem) _algorithm->SetInputConnection(pointSetItem->transformFilter()->GetOutputPort()); - } + VtkVisPointSetItem* pointSetItem = + dynamic_cast<VtkVisPointSetItem*>(parentItem); + if (pointSetItem) + _algorithm->SetInputConnection( + pointSetItem->transformFilter()->GetOutputPort()); } } +} - VtkVisPointSetItem::VtkVisPointSetItem( - VtkCompositeFilter* compositeFilter, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) - : VtkVisPipelineItem(compositeFilter, parentItem, data), _transformFilter(NULL), _activeAttribute("") - { - } - +VtkVisPointSetItem::VtkVisPointSetItem( + VtkCompositeFilter* compositeFilter, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : VtkVisPipelineItem(compositeFilter, parentItem, + data), _transformFilter(NULL), _activeAttribute("") +{ +} VtkVisPointSetItem::~VtkVisPointSetItem() { @@ -78,7 +81,6 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) _mapper = QVtkDataSetMapper::New(); _mapper->InterpolateScalarsBeforeMappingOff(); - // Use a special vtkImageActor instead of vtkActor _mapper->SetInputConnection(_transformFilter->GetOutputPort()); _actor = vtkActor::New(); @@ -96,7 +98,8 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) VtkVisPipelineItem* parentItem = dynamic_cast<VtkVisPipelineItem*>(this->parentItem()); while (parentItem) { - VtkAlgorithmProperties* parentProps = dynamic_cast<VtkAlgorithmProperties*>(parentItem->algorithm()); + VtkAlgorithmProperties* parentProps = + dynamic_cast<VtkAlgorithmProperties*>(parentItem->algorithm()); if (parentProps) { VtkAlgorithmProperties* newProps = new VtkAlgorithmProperties(); @@ -107,7 +110,8 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) parentItem = NULL; } else - parentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem->parentItem()); + parentItem = + dynamic_cast<VtkVisPipelineItem*>(parentItem->parentItem()); } } @@ -116,12 +120,11 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) if (vtkProps) { if (vtkProps->GetActiveAttribute().length() > 0) - { this->SetActiveAttribute(vtkProps->GetActiveAttribute()); - } else { - VtkVisPointSetItem* visParentItem = dynamic_cast<VtkVisPointSetItem*>(this->parentItem()); + VtkVisPointSetItem* visParentItem = + dynamic_cast<VtkVisPointSetItem*>(this->parentItem()); if (visParentItem) this->SetActiveAttribute(visParentItem->GetActiveAttribute()); if (vtkProps->GetTexture() != NULL) @@ -133,7 +136,7 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) void VtkVisPointSetItem::setVtkProperties(VtkAlgorithmProperties* vtkProps) { QObject::connect(vtkProps, SIGNAL(ScalarVisibilityChanged(bool)), - _mapper, SLOT(SetScalarVisibility(bool))); + _mapper, SLOT(SetScalarVisibility(bool))); this->setLookupTableForActiveScalar(); @@ -164,7 +167,8 @@ int VtkVisPointSetItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string if (algPD) { // vtkGenericDataObjectWriter* pdWriter = vtkGenericDataObjectWriter::New(); - vtkSmartPointer<vtkXMLPolyDataWriter> pdWriter = vtkSmartPointer<vtkXMLPolyDataWriter>::New(); + vtkSmartPointer<vtkXMLPolyDataWriter> pdWriter = + vtkSmartPointer<vtkXMLPolyDataWriter>::New(); pdWriter->SetInput(algPD->GetOutputDataObject(0)); //pdWriter->SetDataModeToAscii(); //pdWriter->SetCompressorTypeToNone(); @@ -175,7 +179,8 @@ int VtkVisPointSetItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string } else if (algUG) { - vtkSmartPointer<vtkXMLUnstructuredGridWriter> ugWriter = vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New(); + vtkSmartPointer<vtkXMLUnstructuredGridWriter> ugWriter = + vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New(); ugWriter->SetInput(algUG->GetOutputDataObject(0)); //ugWriter->SetDataModeToAscii(); //ugWriter->SetCompressorTypeToNone(); @@ -188,7 +193,6 @@ int VtkVisPointSetItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string return 0; } - void VtkVisPointSetItem::SetActiveAttribute( const QString& name ) { // Get type by identifier @@ -212,15 +216,21 @@ void VtkVisPointSetItem::SetActiveAttribute( const QString& name ) vtkDataSet* dataSet = vtkDataSet::SafeDownCast(this->_algorithm->GetOutputDataObject(0)); if (dataSet) - { + { if (onPointData) { vtkPointData* pointData = dataSet->GetPointData(); if(pointData) - { + { if(setActiveAttributeOnData(pointData, strippedName)) { - _algorithm->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS, charName); + _algorithm->SetInputArrayToProcess( + 0, + 0, + 0, + vtkDataObject:: + FIELD_ASSOCIATION_POINTS, + charName); _mapper->SetScalarModeToUsePointData(); } else @@ -238,7 +248,13 @@ void VtkVisPointSetItem::SetActiveAttribute( const QString& name ) { if(setActiveAttributeOnData(cellData, strippedName)) { - _algorithm->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS, charName); + _algorithm->SetInputArrayToProcess( + 0, + 0, + 0, + vtkDataObject:: + FIELD_ASSOCIATION_CELLS, + charName); _mapper->SetScalarModeToUseCellData(); } else @@ -290,9 +306,9 @@ void VtkVisPointSetItem::setLookupTableForActiveScalar() vtkProps->SetLookUpTable(GetActiveAttribute(), lut); } else // specific color table - { - _mapper->SetLookupTable(vtkProps->GetLookupTable(this->GetActiveAttribute())); - } + + _mapper->SetLookupTable(vtkProps->GetLookupTable(this-> + GetActiveAttribute())); _mapper->SetScalarRange(_transformFilter->GetOutput()->GetScalarRange()); //_mapper->Update(); KR: not necessary?! @@ -311,14 +327,13 @@ void VtkVisPointSetItem::setScale(double x, double y, double z) const if (this->transformFilter()) { vtkTransform* transform = - static_cast<vtkTransform*>(this->transformFilter()->GetTransform()); + static_cast<vtkTransform*>(this->transformFilter()->GetTransform()); double* trans = transform->GetPosition(); transform->Identity(); transform->Scale(x, y, z); - transform->Translate(trans[0]/x, trans[1]/y, trans[2]/z); + transform->Translate(trans[0] / x, trans[1] / y, trans[2] / z); this->transformFilter()->Modified(); } - } void VtkVisPointSetItem::setTranslation(double x, double y, double z) const @@ -326,13 +341,12 @@ void VtkVisPointSetItem::setTranslation(double x, double y, double z) const if (this->transformFilter()) { vtkTransform* transform = - static_cast<vtkTransform*>(this->transformFilter()->GetTransform()); + static_cast<vtkTransform*>(this->transformFilter()->GetTransform()); double* scale = transform->GetScale(); transform->Identity(); transform->Scale(scale); transform->Translate(x, y, z); this->transformFilter()->Modified(); } - } diff --git a/VtkVis/VtkVisPointSetItem.h b/VtkVis/VtkVisPointSetItem.h index c438f7321f7a0153635a4f892891811e7a216dac..843bf61bf9aee031c5a2cdcf1501d3fd593d8440 100644 --- a/VtkVis/VtkVisPointSetItem.h +++ b/VtkVis/VtkVisPointSetItem.h @@ -4,7 +4,6 @@ * */ - #ifndef VTKVISPOINTSETITEM_H #define VTKVISPOINTSETITEM_H @@ -35,12 +34,12 @@ class VtkVisPointSetItem : public VtkVisPipelineItem public: /// @brief Constructor for a source/filter object. VtkVisPointSetItem(vtkAlgorithm* algorithm, - TreeItem* parentItem, - const QList<QVariant> data = QList<QVariant>()); + TreeItem* parentItem, + const QList<QVariant> data = QList<QVariant>()); /// @brief Constructor for composite filter VtkVisPointSetItem(VtkCompositeFilter* compositeFilter, TreeItem* parentItem, - const QList<QVariant> data = QList<QVariant>()); + const QList<QVariant> data = QList<QVariant>()); ~VtkVisPointSetItem(); @@ -76,11 +75,9 @@ protected: /// @brief Sets pre-set properties on vtkActor and on vtkMapper void setVtkProperties(VtkAlgorithmProperties* vtkProps); - private: /// @see SetActiveAttribute() bool setActiveAttributeOnData(vtkDataSetAttributes* data, std::string& name); - }; #endif // VTKVISPOINTSETITEM_H diff --git a/VtkVis/VtkVisTabWidget.cpp b/VtkVis/VtkVisTabWidget.cpp index 15ff08b2b96353c4dafd0e784750134557c720a1..5b6fac538e28a9f290335e2b24c48f7a6ea76761 100644 --- a/VtkVis/VtkVisTabWidget.cpp +++ b/VtkVis/VtkVisTabWidget.cpp @@ -6,10 +6,10 @@ */ // ** INCLUDES ** -#include "VtkVisTabWidget.h" -#include "VtkVisPipelineItem.h" -#include "VtkCompositeColorByHeightFilter.h" #include "VtkColorByHeightFilter.h" +#include "VtkCompositeColorByHeightFilter.h" +#include "VtkVisPipelineItem.h" +#include "VtkVisTabWidget.h" #include <vtkActor.h> #include <vtkProperty.h> @@ -20,16 +20,16 @@ #include "ColorTableView.h" #include "VtkAlgorithmProperties.h" -#include "VtkAlgorithmPropertyLineEdit.h" -#include "VtkCompositeFilter.h" #include "VtkAlgorithmPropertyCheckbox.h" +#include "VtkAlgorithmPropertyLineEdit.h" #include "VtkAlgorithmPropertyVectorEdit.h" +#include "VtkCompositeFilter.h" -#include <vtkPointData.h> #include <vtkCellData.h> +#include <vtkPointData.h> VtkVisTabWidget::VtkVisTabWidget( QWidget* parent /*= 0*/ ) -: QWidget(parent) + : QWidget(parent) { setupUi(this); @@ -40,14 +40,13 @@ VtkVisTabWidget::VtkVisTabWidget( QWidget* parent /*= 0*/ ) this->transZ->setValidator(new QDoubleValidator(this)); connect(this->vtkVisPipelineView, SIGNAL(requestViewUpdate()), - this, SIGNAL(requestViewUpdate())); + this, SIGNAL(requestViewUpdate())); connect(this->vtkVisPipelineView, SIGNAL(itemSelected(VtkVisPipelineItem*)), - this, SLOT(setActiveItem(VtkVisPipelineItem*))); - - connect(this->activeScalarComboBox, SIGNAL(currentIndexChanged(const QString&)), - this, SLOT(SetActiveAttributeOnItem(const QString&))); + this, SLOT(setActiveItem(VtkVisPipelineItem*))); + connect(this->activeScalarComboBox, SIGNAL(currentIndexChanged(const QString &)), + this, SLOT(SetActiveAttributeOnItem(const QString &))); } void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) @@ -66,8 +65,9 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) visibleEdgesCheckBox->setChecked(vtkProps->GetEdgeVisibility()); edgeColorPickerButton->setColor(vtkProps->GetEdgeColor()); opacitySlider->setValue((int)(vtkProps->GetOpacity() * 100.0)); - - vtkTransform* transform = static_cast<vtkTransform*>(_item->transformFilter()->GetTransform()); + + vtkTransform* transform = + static_cast<vtkTransform*>(_item->transformFilter()->GetTransform()); if (transform) { double scale[3]; @@ -81,9 +81,9 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) this->transY->blockSignals(true); this->transZ->blockSignals(true); this->scaleZ->setText(QString::number(scale[2])); - this->transX->setText(QString::number(trans[0]/scale[0])); - this->transY->setText(QString::number(trans[1]/scale[1])); - this->transZ->setText(QString::number(trans[2]/scale[2])); + this->transX->setText(QString::number(trans[0] / scale[0])); + this->transY->setText(QString::number(trans[1] / scale[1])); + this->transZ->setText(QString::number(trans[2] / scale[2])); this->scaleZ->blockSignals(false); this->transX->blockSignals(false); this->transY->blockSignals(false); @@ -94,8 +94,7 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) // Set to last active attribute QString activeAttribute = _item->GetActiveAttribute(); - if (activeAttribute.length()>0) - { + if (activeAttribute.length() > 0) for (int i = 0; i < this->activeScalarComboBox->count(); i++) { QString itemText = this->activeScalarComboBox->itemText(i); @@ -105,7 +104,6 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) break; } } - } } else { @@ -114,7 +112,7 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) } this->buildProportiesDialog(item); - + // ///* Integrating colour tables into property-window (test!) */ //VtkStationSource* test = dynamic_cast<VtkStationSource*>(_item->algorithm()); @@ -142,13 +140,12 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) transformTabWidget->setEnabled(false); this->activeScalarComboBox->clear(); } - } void VtkVisTabWidget::on_diffuseColorPickerButton_colorPicked( QColor color ) { static_cast<vtkActor*>(_item->actor())->GetProperty()->SetDiffuseColor( - color.redF(), color.greenF(), color.blueF()); + color.redF(), color.greenF(), color.blueF()); emit requestViewUpdate(); } @@ -172,7 +169,7 @@ void VtkVisTabWidget::on_visibleEdgesCheckBox_stateChanged( int state ) void VtkVisTabWidget::on_edgeColorPickerButton_colorPicked( QColor color ) { static_cast<vtkActor*>(_item->actor())->GetProperty()->SetEdgeColor( - color.redF(), color.greenF(), color.blueF()); + color.redF(), color.greenF(), color.blueF()); emit requestViewUpdate(); } @@ -184,26 +181,27 @@ void VtkVisTabWidget::on_opacitySlider_sliderMoved( int value ) void VtkVisTabWidget::on_scaleZ_textChanged(const QString &text) { - bool ok=true; + bool ok = true; double scale = text.toDouble(&ok); if (ok) { _item->setScale(1.0, 1.0, scale); - + for (int i = 0; i < _item->childCount(); i++) { VtkVisPipelineItem* childItem = _item->child(i); if (childItem) { VtkCompositeColorByHeightFilter* colorFilter = - dynamic_cast<VtkCompositeColorByHeightFilter*> - (childItem->compositeFilter()); + dynamic_cast<VtkCompositeColorByHeightFilter*> + (childItem->compositeFilter()); if (colorFilter) VtkColorByHeightFilter::SafeDownCast( - colorFilter->GetOutputAlgorithm())->SetTableRangeScaling(scale); + colorFilter->GetOutputAlgorithm())-> + SetTableRangeScaling(scale); } - } + } emit requestViewUpdate(); } @@ -229,7 +227,7 @@ void VtkVisTabWidget::buildProportiesDialog(VtkVisPipelineItem* item) { QFormLayout* layout = static_cast<QFormLayout*>(this->scrollAreaWidgetContents->layout()); while(layout->count()) - delete layout->takeAt(0)->widget(); + delete layout->takeAt(0)->widget(); QMap<QString, QVariant>* propMap = NULL; QMap<QString, QList<QVariant> >* propVecMap = NULL; @@ -266,27 +264,38 @@ void VtkVisTabWidget::buildProportiesDialog(VtkVisPipelineItem* item) VtkAlgorithmPropertyCheckbox* checkbox; switch (value.type()) { - case QVariant::Double: - lineEdit = new VtkAlgorithmPropertyLineEdit(QString::number(value.toDouble()), key, QVariant::Double, algProps); - connect(lineEdit, SIGNAL(editingFinished()), this, SIGNAL(requestViewUpdate())); - layout->addRow(key, lineEdit); - break; - - case QVariant::Int: - lineEdit = new VtkAlgorithmPropertyLineEdit(QString::number(value.toInt()), key, QVariant::Int, algProps); - connect(lineEdit, SIGNAL(editingFinished()), this, SIGNAL(requestViewUpdate())); - layout->addRow(key, lineEdit); - break; - - case QVariant::Bool: - checkbox = new VtkAlgorithmPropertyCheckbox(value.toBool(), key, algProps); - connect(checkbox, SIGNAL(stateChanged(int)), this, SIGNAL(requestViewUpdate())); - layout->addRow(key, checkbox); - break; - - - default: - break; + case QVariant::Double: + lineEdit = + new VtkAlgorithmPropertyLineEdit(QString::number( + value.toDouble()), + key, QVariant::Double, + algProps); + connect(lineEdit, SIGNAL(editingFinished()), this, + SIGNAL(requestViewUpdate())); + layout->addRow(key, lineEdit); + break; + + case QVariant::Int: + lineEdit = + new VtkAlgorithmPropertyLineEdit(QString::number( + value.toInt()), + key, QVariant::Int, + algProps); + connect(lineEdit, SIGNAL(editingFinished()), this, + SIGNAL(requestViewUpdate())); + layout->addRow(key, lineEdit); + break; + + case QVariant::Bool: + checkbox = new VtkAlgorithmPropertyCheckbox( + value.toBool(), key, algProps); + connect(checkbox, SIGNAL(stateChanged(int)), this, + SIGNAL(requestViewUpdate())); + layout->addRow(key, checkbox); + break; + + default: + break; } } } @@ -305,10 +314,14 @@ void VtkVisTabWidget::buildProportiesDialog(VtkVisPipelineItem* item) { QList<QString> valuesAsString; foreach (QVariant variant, values) - valuesAsString.push_back(variant.toString()); - - vectorEdit = new VtkAlgorithmPropertyVectorEdit(valuesAsString, key, values.front().type(), algProps); - connect(vectorEdit, SIGNAL(editingFinished()), this, SIGNAL(requestViewUpdate())); + valuesAsString.push_back(variant.toString()); + + vectorEdit = new VtkAlgorithmPropertyVectorEdit(valuesAsString, + key, + values.front().type(), + algProps); + connect(vectorEdit, SIGNAL(editingFinished()), this, + SIGNAL(requestViewUpdate())); layout->addRow(key, vectorEdit); } } @@ -321,24 +334,19 @@ void VtkVisTabWidget::buildScalarArrayComboBox(VtkVisPipelineItem* item) QStringList dataSetAttributesList; if (dataSet) { - vtkPointData* pointData = dataSet->GetPointData(); //std::cout << " #point data arrays: " << pointData->GetNumberOfArrays() << std::endl; for (int i = 0; i < pointData->GetNumberOfArrays(); i++) - { //std::cout << " Name: " << pointData->GetArrayName(i) << std::endl; dataSetAttributesList.push_back(QString("P-") + pointData->GetArrayName(i)); - } vtkCellData* cellData = dataSet->GetCellData(); //std::cout << " #cell data arrays: " << cellData->GetNumberOfArrays() << std::endl; for (int i = 0; i < cellData->GetNumberOfArrays(); i++) - { //std::cout << " Name: " << cellData->GetArrayName(i) << std::endl; dataSetAttributesList.push_back(QString("C-") + cellData->GetArrayName(i)); - } - dataSetAttributesList.push_back("Solid Color"); // all scalars switched off + dataSetAttributesList.push_back("Solid Color"); // all scalars switched off } this->activeScalarComboBox->blockSignals(true); this->activeScalarComboBox->clear(); diff --git a/VtkVis/VtkVisTabWidget.h b/VtkVis/VtkVisTabWidget.h index e3d35bb872add3a924d5ee3445e7573bd4a0deb1..fb4b1a147a2eac51eb75947ca61da639cb159675 100644 --- a/VtkVis/VtkVisTabWidget.h +++ b/VtkVis/VtkVisTabWidget.h @@ -4,7 +4,6 @@ * */ - #ifndef VTKVISTABWIDGET_H #define VTKVISTABWIDGET_H @@ -38,17 +37,17 @@ protected slots: { Q_UNUSED(text); this->translateItem(); - }; + } void on_transY_textChanged(const QString &text) { Q_UNUSED(text); this->translateItem(); - }; + } void on_transZ_textChanged(const QString &text) { Q_UNUSED(text); this->translateItem(); - }; + } void SetActiveAttributeOnItem(const QString &name); @@ -66,7 +65,6 @@ private: signals: /// Is emitted when a property was changed. void requestViewUpdate(); - }; #endif // VTKVISTABWIDGET_H