text
stringlengths
54
60.6k
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Adrian Draghici <draghici.adrian.b@gmail.com> // // Self #include "GroundOverlayFrame.h" // Marble #include "GeoDataPlacemark.h" #include "GeoDataTypes.h" #include "GeoPainter.h" #include "ViewportParams.h" #include "SceneGraphicsTypes.h" namespace Marble { GroundOverlayFrame::GroundOverlayFrame( GeoDataPlacemark *placemark, GeoDataGroundOverlay *overlay, TextureLayer *textureLayer ) : SceneGraphicsItem( placemark ), m_overlay( overlay ), m_textureLayer( textureLayer ), m_movedPoint( -1 ), m_viewport( 0 ) { update(); } void GroundOverlayFrame::paint(GeoPainter *painter, const ViewportParams *viewport ) { m_viewport = viewport; m_regionList.clear(); painter->save(); painter->setBrush( Oxygen::aluminumGray4 ); if ( placemark()->geometry()->nodeType() == GeoDataTypes::GeoDataPolygonType ) { GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() ); GeoDataLinearRing &ring = polygon->outerBoundary(); for ( int i = 0; i < ring.size(); ++i ) { m_regionList.append( painter->regionFromEllipse( ring.at(i), 10, 10 ) ); } m_regionList.append( painter->regionFromPolygon( ring, Qt::OddEvenFill ) ); } painter->restore(); } bool GroundOverlayFrame::containsPoint( const QPoint &eventPos ) const { foreach ( const QRegion &region, m_regionList ) { if ( region.contains( eventPos ) ) { return true; } } return false; } void GroundOverlayFrame::dealWithItemChange( const SceneGraphicsItem *other ) { Q_UNUSED( other ); } void GroundOverlayFrame::move( const GeoDataCoordinates &source, const GeoDataCoordinates &destination ) { // not implemented yet } bool GroundOverlayFrame::mousePressEvent( QMouseEvent *event ) { // React to all ellipse as well as to the polygon. for ( int i = 0; i < m_regionList.size(); ++i ) { if ( m_regionList.at(i).contains( event->pos() ) ) { m_movedPoint = i; qreal lon, lat; m_viewport->geoCoordinates( event->pos().x(), event->pos().y(), lon, lat, GeoDataCoordinates::Radian ); m_movedPointCoordinates.set( lon, lat ); return true; } } return false; } bool GroundOverlayFrame::mouseMoveEvent( QMouseEvent *event ) { if ( !m_viewport ) { return false; } // Catch hover events. if ( m_movedPoint < 0 ) { return true; } if ( placemark()->geometry()->nodeType() == GeoDataTypes::GeoDataPolygonType ) { qreal lon, lat; m_viewport->geoCoordinates( event->pos().x(), event->pos().y(), lon, lat, GeoDataCoordinates::Radian ); qreal rotatedLon; qreal rotatedLat; rotateAroundCenter( lon, lat, rotatedLon, rotatedLat, m_overlay->latLonBox(), true ); if ( m_movedPoint == NorthWest ) { m_overlay->latLonBox().setNorth( rotatedLat ); m_overlay->latLonBox().setWest( rotatedLon ); } else if ( m_movedPoint == SouthWest ) { m_overlay->latLonBox().setSouth( rotatedLat ); m_overlay->latLonBox().setWest( rotatedLon ); } else if ( m_movedPoint == SouthEast ) { m_overlay->latLonBox().setSouth( rotatedLat ); m_overlay->latLonBox().setEast( rotatedLon ); } else if ( m_movedPoint == NorthEast ) { m_overlay->latLonBox().setNorth( rotatedLat ); m_overlay->latLonBox().setEast( rotatedLon ); } else if ( m_movedPoint == Polygon ) { qreal centerLonDiff = lon - m_movedPointCoordinates.longitude(); qreal centerLatDiff = lat - m_movedPointCoordinates.latitude(); m_overlay->latLonBox().setBoundaries( m_overlay->latLonBox().north() + centerLatDiff, m_overlay->latLonBox().south() + centerLatDiff, m_overlay->latLonBox().east() + centerLonDiff, m_overlay->latLonBox().west() + centerLonDiff ); m_movedPointCoordinates.set( lon, lat ); } update(); return true; } return false; } bool GroundOverlayFrame::mouseReleaseEvent( QMouseEvent *event ) { Q_UNUSED( event ); m_movedPoint = -1; m_textureLayer->reset(); return true; } void GroundOverlayFrame::update() { GeoDataLatLonBox overlayLatLonBox = m_overlay->latLonBox(); GeoDataPolygon *poly = dynamic_cast<GeoDataPolygon*>( placemark()->geometry() ); poly->outerBoundary().clear(); qreal rotatedLon; qreal rotatedLat; rotateAroundCenter( overlayLatLonBox.west(), overlayLatLonBox.north(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); rotateAroundCenter( overlayLatLonBox.west(), overlayLatLonBox.south(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); rotateAroundCenter( overlayLatLonBox.east(), overlayLatLonBox.south(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); rotateAroundCenter( overlayLatLonBox.east(), overlayLatLonBox.north(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); } void GroundOverlayFrame::rotateAroundCenter( qreal lon, qreal lat, qreal &rotatedLon, qreal &rotatedLat, GeoDataLatLonBox &box, bool inverse ) { const qreal angle = ( inverse ? ( -1 ) : 1 ) * box.rotation(); const qreal sinRotation = sin( angle ); const qreal cosRotation = cos( angle ); const qreal centerLat = box.center().latitude(); qreal centerLon = box.center().longitude(); if ( box.crossesDateLine() ) { if ( lon < 0 && centerLon > 0 ) { centerLon -= 2 * M_PI; } if ( lon > 0 && centerLon < 0 ) { centerLon += 2 * M_PI; } if ( box.west() > 0 && box.east() > 0 && box.west() > box.east() && lon > 0 && lon < box.west() ) { if ( ! ( lon < box.west() && lon > box.toCircumscribedRectangle().west() ) ) { centerLon -= 2 * M_PI; } } } rotatedLon = ( lon - centerLon ) * cosRotation - ( lat - centerLat ) * sinRotation + centerLon; rotatedLat = ( lon - centerLon ) * sinRotation + ( lat - centerLat ) * cosRotation + centerLat; GeoDataCoordinates::normalizeLonLat( rotatedLon, rotatedLat ); } void GroundOverlayFrame::dealWithStateChange( SceneGraphicsItem::ActionState previousState ) { Q_UNUSED( previousState ); } const char *GroundOverlayFrame::graphicType() const { return SceneGraphicsTypes::SceneGraphicGroundOverlay; } } <commit_msg>Avoid warnings saying that parameters are unused<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Adrian Draghici <draghici.adrian.b@gmail.com> // // Self #include "GroundOverlayFrame.h" // Marble #include "GeoDataPlacemark.h" #include "GeoDataTypes.h" #include "GeoPainter.h" #include "ViewportParams.h" #include "SceneGraphicsTypes.h" namespace Marble { GroundOverlayFrame::GroundOverlayFrame( GeoDataPlacemark *placemark, GeoDataGroundOverlay *overlay, TextureLayer *textureLayer ) : SceneGraphicsItem( placemark ), m_overlay( overlay ), m_textureLayer( textureLayer ), m_movedPoint( -1 ), m_viewport( 0 ) { update(); } void GroundOverlayFrame::paint(GeoPainter *painter, const ViewportParams *viewport ) { m_viewport = viewport; m_regionList.clear(); painter->save(); painter->setBrush( Oxygen::aluminumGray4 ); if ( placemark()->geometry()->nodeType() == GeoDataTypes::GeoDataPolygonType ) { GeoDataPolygon *polygon = static_cast<GeoDataPolygon*>( placemark()->geometry() ); GeoDataLinearRing &ring = polygon->outerBoundary(); for ( int i = 0; i < ring.size(); ++i ) { m_regionList.append( painter->regionFromEllipse( ring.at(i), 10, 10 ) ); } m_regionList.append( painter->regionFromPolygon( ring, Qt::OddEvenFill ) ); } painter->restore(); } bool GroundOverlayFrame::containsPoint( const QPoint &eventPos ) const { foreach ( const QRegion &region, m_regionList ) { if ( region.contains( eventPos ) ) { return true; } } return false; } void GroundOverlayFrame::dealWithItemChange( const SceneGraphicsItem *other ) { Q_UNUSED( other ); } void GroundOverlayFrame::move( const GeoDataCoordinates &source, const GeoDataCoordinates &destination ) { // not implemented yet Q_UNUSED( source ); Q_UNUSED( destination ); } bool GroundOverlayFrame::mousePressEvent( QMouseEvent *event ) { // React to all ellipse as well as to the polygon. for ( int i = 0; i < m_regionList.size(); ++i ) { if ( m_regionList.at(i).contains( event->pos() ) ) { m_movedPoint = i; qreal lon, lat; m_viewport->geoCoordinates( event->pos().x(), event->pos().y(), lon, lat, GeoDataCoordinates::Radian ); m_movedPointCoordinates.set( lon, lat ); return true; } } return false; } bool GroundOverlayFrame::mouseMoveEvent( QMouseEvent *event ) { if ( !m_viewport ) { return false; } // Catch hover events. if ( m_movedPoint < 0 ) { return true; } if ( placemark()->geometry()->nodeType() == GeoDataTypes::GeoDataPolygonType ) { qreal lon, lat; m_viewport->geoCoordinates( event->pos().x(), event->pos().y(), lon, lat, GeoDataCoordinates::Radian ); qreal rotatedLon; qreal rotatedLat; rotateAroundCenter( lon, lat, rotatedLon, rotatedLat, m_overlay->latLonBox(), true ); if ( m_movedPoint == NorthWest ) { m_overlay->latLonBox().setNorth( rotatedLat ); m_overlay->latLonBox().setWest( rotatedLon ); } else if ( m_movedPoint == SouthWest ) { m_overlay->latLonBox().setSouth( rotatedLat ); m_overlay->latLonBox().setWest( rotatedLon ); } else if ( m_movedPoint == SouthEast ) { m_overlay->latLonBox().setSouth( rotatedLat ); m_overlay->latLonBox().setEast( rotatedLon ); } else if ( m_movedPoint == NorthEast ) { m_overlay->latLonBox().setNorth( rotatedLat ); m_overlay->latLonBox().setEast( rotatedLon ); } else if ( m_movedPoint == Polygon ) { qreal centerLonDiff = lon - m_movedPointCoordinates.longitude(); qreal centerLatDiff = lat - m_movedPointCoordinates.latitude(); m_overlay->latLonBox().setBoundaries( m_overlay->latLonBox().north() + centerLatDiff, m_overlay->latLonBox().south() + centerLatDiff, m_overlay->latLonBox().east() + centerLonDiff, m_overlay->latLonBox().west() + centerLonDiff ); m_movedPointCoordinates.set( lon, lat ); } update(); return true; } return false; } bool GroundOverlayFrame::mouseReleaseEvent( QMouseEvent *event ) { Q_UNUSED( event ); m_movedPoint = -1; m_textureLayer->reset(); return true; } void GroundOverlayFrame::update() { GeoDataLatLonBox overlayLatLonBox = m_overlay->latLonBox(); GeoDataPolygon *poly = dynamic_cast<GeoDataPolygon*>( placemark()->geometry() ); poly->outerBoundary().clear(); qreal rotatedLon; qreal rotatedLat; rotateAroundCenter( overlayLatLonBox.west(), overlayLatLonBox.north(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); rotateAroundCenter( overlayLatLonBox.west(), overlayLatLonBox.south(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); rotateAroundCenter( overlayLatLonBox.east(), overlayLatLonBox.south(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); rotateAroundCenter( overlayLatLonBox.east(), overlayLatLonBox.north(), rotatedLon, rotatedLat, overlayLatLonBox ); poly->outerBoundary().append( GeoDataCoordinates( rotatedLon, rotatedLat ) ); } void GroundOverlayFrame::rotateAroundCenter( qreal lon, qreal lat, qreal &rotatedLon, qreal &rotatedLat, GeoDataLatLonBox &box, bool inverse ) { const qreal angle = ( inverse ? ( -1 ) : 1 ) * box.rotation(); const qreal sinRotation = sin( angle ); const qreal cosRotation = cos( angle ); const qreal centerLat = box.center().latitude(); qreal centerLon = box.center().longitude(); if ( box.crossesDateLine() ) { if ( lon < 0 && centerLon > 0 ) { centerLon -= 2 * M_PI; } if ( lon > 0 && centerLon < 0 ) { centerLon += 2 * M_PI; } if ( box.west() > 0 && box.east() > 0 && box.west() > box.east() && lon > 0 && lon < box.west() ) { if ( ! ( lon < box.west() && lon > box.toCircumscribedRectangle().west() ) ) { centerLon -= 2 * M_PI; } } } rotatedLon = ( lon - centerLon ) * cosRotation - ( lat - centerLat ) * sinRotation + centerLon; rotatedLat = ( lon - centerLon ) * sinRotation + ( lat - centerLat ) * cosRotation + centerLat; GeoDataCoordinates::normalizeLonLat( rotatedLon, rotatedLat ); } void GroundOverlayFrame::dealWithStateChange( SceneGraphicsItem::ActionState previousState ) { Q_UNUSED( previousState ); } const char *GroundOverlayFrame::graphicType() const { return SceneGraphicsTypes::SceneGraphicGroundOverlay; } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "communitywelcomepagewidget.h" #include "ui_communitywelcomepagewidget.h" #include "rssfetcher.h" #include <QtCore/QMap> #include <QtCore/QUrl> #include <QtGui/QDesktopServices> #include <QtGui/QTreeWidgetItem> struct Site { const char *description; const char *url; }; static const Site supportSites[] = { { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Forum Nokia</b><br /><font color='gray'>Mobile Application Support</font>"), "http://www.forum.nokia.com/I_Want_To/Develop_Mobile_Applications/Technical_Support/"}, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt GPL Support</b><br /><font color='gray'>Buy professional Qt support</font>"), "http://shop.qt.nokia.com/en/support.html"}, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Centre</b><br /><font color='gray'>Community based Qt support</font>"), "http://www.qtcentre.org" } }; static const Site sites[] = { { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Home</b><br /><font color='gray'>Qt by Nokia on the web</font>"), "http://qt.nokia.com" }, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Git Hosting</b><br /><font color='gray'>Participate in Qt development</font>"), "http://qt.gitorious.org"}, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Apps</b><br /><font color='gray'>Find free Qt-based apps</font>"), "http://www.qt-apps.org"} }; namespace Welcome { namespace Internal { static inline void populateWelcomeTreeWidget(const Site *sites, int count, Utils::WelcomeModeTreeWidget *wt) { for (int s = 0; s < count; s++) { const QString description = CommunityWelcomePageWidget::tr(sites[s].description); const QString url = QLatin1String(sites[s].url); wt->addItem(description, url, url); } } CommunityWelcomePageWidget::CommunityWelcomePageWidget(QWidget *parent) : QWidget(parent), m_rssFetcher(new RSSFetcher(7)), ui(new Ui::CommunityWelcomePageWidget) { ui->setupUi(this); ui->labsTitleLabel->setStyledText(tr("News From the Qt Labs")); ui->supportSitesTitleLabel->setStyledText(tr("Qt Support Sites")); ui->miscSitesTitleLabel->setStyledText(tr("Qt Links")); connect(ui->newsTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString))); connect(ui->miscSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString))); connect(ui->supportSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString))); connect(m_rssFetcher, SIGNAL(newsItemReady(QString, QString, QString)), ui->newsTreeWidget, SLOT(slotAddNewsItem(QString, QString, QString))); //: Add localized feed here only if one exists m_rssFetcher->fetch(QUrl(tr("http://labs.trolltech.com/blogs/feed"))); populateWelcomeTreeWidget(supportSites, sizeof(supportSites)/sizeof(Site), ui->supportSitesTreeWidget); populateWelcomeTreeWidget(sites, sizeof(sites)/sizeof(Site), ui->miscSitesTreeWidget); } CommunityWelcomePageWidget::~CommunityWelcomePageWidget() { delete m_rssFetcher; delete ui; } void CommunityWelcomePageWidget::slotUrlClicked(const QString &data) { QDesktopServices::openUrl(QUrl(data)); } } // namespace Internal } // namespace Welcome <commit_msg>Fix typo in welcome page<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "communitywelcomepagewidget.h" #include "ui_communitywelcomepagewidget.h" #include "rssfetcher.h" #include <QtCore/QMap> #include <QtCore/QUrl> #include <QtGui/QDesktopServices> #include <QtGui/QTreeWidgetItem> struct Site { const char *description; const char *url; }; static const Site supportSites[] = { { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Forum Nokia</b><br /><font color='gray'>Mobile Application Support</font>"), "http://www.forum.nokia.com/I_Want_To/Develop_Mobile_Applications/Technical_Support/"}, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt LGPL Support</b><br /><font color='gray'>Buy professional Qt support</font>"), "http://shop.qt.nokia.com/en/support.html"}, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Centre</b><br /><font color='gray'>Community based Qt support</font>"), "http://www.qtcentre.org" } }; static const Site sites[] = { { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Home</b><br /><font color='gray'>Qt by Nokia on the web</font>"), "http://qt.nokia.com" }, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Git Hosting</b><br /><font color='gray'>Participate in Qt development</font>"), "http://qt.gitorious.org"}, { QT_TRANSLATE_NOOP("Welcome::Internal::CommunityWelcomePageWidget", "<b>Qt Apps</b><br /><font color='gray'>Find free Qt-based apps</font>"), "http://www.qt-apps.org"} }; namespace Welcome { namespace Internal { static inline void populateWelcomeTreeWidget(const Site *sites, int count, Utils::WelcomeModeTreeWidget *wt) { for (int s = 0; s < count; s++) { const QString description = CommunityWelcomePageWidget::tr(sites[s].description); const QString url = QLatin1String(sites[s].url); wt->addItem(description, url, url); } } CommunityWelcomePageWidget::CommunityWelcomePageWidget(QWidget *parent) : QWidget(parent), m_rssFetcher(new RSSFetcher(7)), ui(new Ui::CommunityWelcomePageWidget) { ui->setupUi(this); ui->labsTitleLabel->setStyledText(tr("News From the Qt Labs")); ui->supportSitesTitleLabel->setStyledText(tr("Qt Support Sites")); ui->miscSitesTitleLabel->setStyledText(tr("Qt Links")); connect(ui->newsTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString))); connect(ui->miscSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString))); connect(ui->supportSitesTreeWidget, SIGNAL(activated(QString)), SLOT(slotUrlClicked(QString))); connect(m_rssFetcher, SIGNAL(newsItemReady(QString, QString, QString)), ui->newsTreeWidget, SLOT(slotAddNewsItem(QString, QString, QString))); //: Add localized feed here only if one exists m_rssFetcher->fetch(QUrl(tr("http://labs.trolltech.com/blogs/feed"))); populateWelcomeTreeWidget(supportSites, sizeof(supportSites)/sizeof(Site), ui->supportSitesTreeWidget); populateWelcomeTreeWidget(sites, sizeof(sites)/sizeof(Site), ui->miscSitesTreeWidget); } CommunityWelcomePageWidget::~CommunityWelcomePageWidget() { delete m_rssFetcher; delete ui; } void CommunityWelcomePageWidget::slotUrlClicked(const QString &data) { QDesktopServices::openUrl(QUrl(data)); } } // namespace Internal } // namespace Welcome <|endoftext|>
<commit_before><commit_msg>Call NN model and apply forces to tires (Polaris SPHnn)<commit_after><|endoftext|>
<commit_before>// RUN: %llvmgxx %s -fasm-blocks -S -o - | FileCheck %s // Complicated expression as jump target // XFAIL: * // XTARGET: x86,i386,i686 void Method3() { // CHECK: Method3 // CHECK-NOT: alignstack asm("foo:"); // CHECK: return } void Method4() { // CHECK: Method4 // CHECK: alignstack asm { bar: } // CHECK: return } <commit_msg>This is passing on Darwin PPC.<commit_after>// RUN: %llvmgxx %s -fasm-blocks -S -o - | FileCheck %s // Complicated expression as jump target // XFAIL: * // XTARGET: x86,i386,i686,darwin void Method3() { // CHECK: Method3 // CHECK-NOT: alignstack asm("foo:"); // CHECK: return } void Method4() { // CHECK: Method4 // CHECK: alignstack asm { bar: } // CHECK: return } <|endoftext|>
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved. #ifndef GUARD_top_panel_hpp #define GUARD_top_panel_hpp #include "account.hpp" #include <wx/panel.h> #include <wx/sizer.h> #include <vector> namespace phatbooks { // Begin forward declarations class OrdinaryJournal; class PhatbooksDatabaseConnection; namespace gui { class AccountListCtrl; class DraftJournalListCtrl; class Frame; class TransactionCtrl; // End forward declarations /** * Top level panel intended as immediate child of Frame. */ class TopPanel: public wxPanel { public: TopPanel ( Frame* parent, PhatbooksDatabaseConnection& p_database_connection ); /** * Populates \e out with a vector of the balance sheet Accounts currently * selected by the user in the main window. */ void selected_balance_sheet_accounts(std::vector<Account>& out) const; /** * Populates \e out with a vector of the P&L Accounts currently selected * by the user in the main window. */ void selected_pl_accounts(std::vector<Account>& out) const; /** * Update the display to reflect current state of database. */ void update(); /** * Configure the TransactionCtrl to reflect the Accounts passed in the * parameters. * * @param p_balance_sheet_accounts a possibly empty sequence of Accounts * of account_super_type::balance_sheet. * * @param p_pl_accounts a possibly empty sequence of Accounts of * account_super_type::pl. */ void configure_transaction_ctrl ( std::vector<Account> p_balance_sheet_accounts, std::vector<Account> p_pl_accounts ); private: void configure_account_lists(); /** * Configure the TransactionCtrl to reflect the currently selected * Accounts (if any). * * @todo What if fewer than 2 Accounts are selected? */ void configure_transaction_ctrl(); void configure_draft_journal_list_ctrl(); PhatbooksDatabaseConnection& m_database_connection; wxBoxSizer* m_top_sizer; wxBoxSizer* m_right_column_sizer; AccountListCtrl* m_bs_account_list; AccountListCtrl* m_pl_account_list; TransactionCtrl* m_transaction_ctrl; DraftJournalListCtrl* m_draft_journal_list; }; } // namespace gui } // namespace phatbooks #endif // GUARD_top_panel_hpp <commit_msg>Added a TODO.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved. #ifndef GUARD_top_panel_hpp #define GUARD_top_panel_hpp #include "account.hpp" #include <wx/panel.h> #include <wx/sizer.h> #include <vector> namespace phatbooks { // Begin forward declarations class OrdinaryJournal; class PhatbooksDatabaseConnection; namespace gui { class AccountListCtrl; class DraftJournalListCtrl; class Frame; class TransactionCtrl; // End forward declarations /** * Top level panel intended as immediate child of Frame. * * @todo HIGH PRIORITY Ensure DraftJournalListCtrl is updated when * required. Ensure it is updated and positioned in the correct order * relative to TransactionCtrl. */ class TopPanel: public wxPanel { public: TopPanel ( Frame* parent, PhatbooksDatabaseConnection& p_database_connection ); /** * Populates \e out with a vector of the balance sheet Accounts currently * selected by the user in the main window. */ void selected_balance_sheet_accounts(std::vector<Account>& out) const; /** * Populates \e out with a vector of the P&L Accounts currently selected * by the user in the main window. */ void selected_pl_accounts(std::vector<Account>& out) const; /** * Update the display to reflect current state of database. */ void update(); /** * Configure the TransactionCtrl to reflect the Accounts passed in the * parameters. * * @param p_balance_sheet_accounts a possibly empty sequence of Accounts * of account_super_type::balance_sheet. * * @param p_pl_accounts a possibly empty sequence of Accounts of * account_super_type::pl. */ void configure_transaction_ctrl ( std::vector<Account> p_balance_sheet_accounts, std::vector<Account> p_pl_accounts ); private: void configure_account_lists(); /** * Configure the TransactionCtrl to reflect the currently selected * Accounts (if any). * * @todo What if fewer than 2 Accounts are selected? */ void configure_transaction_ctrl(); void configure_draft_journal_list_ctrl(); PhatbooksDatabaseConnection& m_database_connection; wxBoxSizer* m_top_sizer; wxBoxSizer* m_right_column_sizer; AccountListCtrl* m_bs_account_list; AccountListCtrl* m_pl_account_list; TransactionCtrl* m_transaction_ctrl; DraftJournalListCtrl* m_draft_journal_list; }; } // namespace gui } // namespace phatbooks #endif // GUARD_top_panel_hpp <|endoftext|>
<commit_before> #include <assert.h> #include <thread> #include <boost/atomic.hpp> #include "LinkedList.hpp" void test0() { LinkedList<int> l; assert(l.empty()); l._checkSanity(); auto item = l.push_back(); item->value = 42; item = NULL; l._checkSanity(); assert(!l.empty()); assert(l.size() == 1); auto ret = l.pop_front(); assert(ret); assert(ret->value == 42); ret = NULL; assert(l.empty()); assert(l.size() == 0); l._checkSanity(); } void test1() { LinkedList<int> l; l._checkSanity(); for(int i = 0; i < 100; ++i) { auto item = l.push_back(); l._checkSanity(); item->value = i; } assert(!l.empty()); assert(l.size() == 100); for(int i = 0; i < 100; ++i) { auto ret = l.pop_front(); l._checkSanity(); assert(ret); assert(ret->value == i); } assert(l.empty()); } void test2() { LinkedList<int> l; l._checkSanity(); auto producer = [&l](){ for(int i = 0; i < 100; ++i) { LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; l.push_back(item); } }; auto consumer = [&l](){ for(int i = 0; i < 100; ++i) { while(l.empty()) {} // wait for entry auto ret = l.pop_front(); assert(ret); assert(ret->value == i); } }; for(int i = 0; i < 1000; ++i) { std::thread t1(producer), t2(consumer); t1.join(); t2.join(); assert(l.empty()); l._checkSanity(); } } void test3() { LinkedList<int> l; boost::atomic<int> state; auto producer = [&l, &state](){ for(int i = 0; i < 100; ++i) { if(i == 50) state++; LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; l.push_back(item); } state++; }; auto consumer = [&l, &state](){ while(state == 0) {} for(int i = 0; i < 40; ++i) { while(l.empty()); // wait for entry auto ret = l.pop_front(); assert(ret); assert(ret->value == i); } state++; }; auto reader = [&l, &state]() { while(state < 3) { if(state == 0) continue; int first = -1; int old = -1; int count = 0; for(auto v : l) { assert(v >= 0); if(first < 0) first = v; if(old >= 0) assert(old < v); old = v; ++count; } assert(count > 10); } }; for(int i = 0; i < 1000; ++i) { state = 0; std::thread t1(producer), t2(consumer), t3(reader); t1.join(); t2.join(); t3.join(); l._checkSanity(); l.clear(); } } void test4() { LinkedList<int> l; auto producer = [&l](){ for(int i = 3; i <= 100; ++i) { LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; if(i < 50) l.push_back(item); else l.push_front(item); } }; auto reader = [&l]() { int endCount = 0; while(true) { int old = -1; int m = 0; int count = 0; for(auto v : l) { assert(v >= 1); if(old >= 50 && v == 1) {} else if(old >= 50) assert(old - 1 == v); else if(old >= 0) assert(old + 1 == v); old = v; if(v > m) m = v; ++count; } assert(count >= 2); assert(count <= 100); assert(count == m); if(count >= 50) assert(old == 49); if(count < 100) assert(endCount == 0); if(count == 100) endCount++; if(endCount >= 10) break; } }; for(int i = 0; i < 1000; ++i) { l.push_back()->value = 1; l.push_back()->value = 2; std::thread t1(producer), t3(reader); t1.join(); t3.join(); l._checkSanity(); l.clear(); } } int main() { test0(); test1(); test2(); test3(); test4(); } <commit_msg>more testing<commit_after> #include <assert.h> #include <thread> #include <boost/atomic.hpp> #include "LinkedList.hpp" void test0() { LinkedList<int> l; assert(l.empty()); l._checkSanity(); auto item = l.push_back(); item->value = 42; item = NULL; l._checkSanity(); assert(!l.empty()); assert(l.size() == 1); auto ret = l.pop_front(); assert(ret); assert(ret->value == 42); ret = NULL; assert(l.empty()); assert(l.size() == 0); l._checkSanity(); } void test1() { LinkedList<int> l; l._checkSanity(); for(int i = 0; i < 100; ++i) { auto item = l.push_back(); l._checkSanity(); item->value = i; } assert(!l.empty()); assert(l.size() == 100); for(int i = 0; i < 100; ++i) { auto ret = l.pop_front(); l._checkSanity(); assert(ret); assert(ret->value == i); } assert(l.empty()); } void test2() { LinkedList<int> l; l._checkSanity(); auto producer = [&l](){ for(int i = 0; i < 100; ++i) { LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; l.push_back(item); } }; auto consumer = [&l](){ for(int i = 0; i < 100; ++i) { while(l.empty()) {} // wait for entry auto ret = l.pop_front(); assert(ret); assert(ret->value == i); } }; for(int i = 0; i < 1000; ++i) { std::thread t1(producer), t2(consumer); t1.join(); t2.join(); assert(l.empty()); l._checkSanity(); } } void test3() { LinkedList<int> l; boost::atomic<int> state; auto producer = [&l, &state](){ for(int i = 0; i < 100; ++i) { if(i == 50) state++; LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; l.push_back(item); } state++; }; auto consumer = [&l, &state](){ while(state == 0) {} for(int i = 0; i < 40; ++i) { while(l.empty()); // wait for entry auto ret = l.pop_front(); assert(ret); assert(ret->value == i); } state++; }; auto reader = [&l, &state]() { while(state < 3) { if(state == 0) continue; int first = -1; int old = -1; int count = 0; for(auto v : l) { assert(v >= 0); if(first < 0) first = v; if(old >= 0) assert(old < v); old = v; ++count; } assert(count > 10); } }; for(int i = 0; i < 1000; ++i) { state = 0; std::thread t1(producer), t2(consumer), t3(reader); t1.join(); t2.join(); t3.join(); l._checkSanity(); l.clear(); } } void test4() { LinkedList<int> l; auto producer = [&l](){ for(int i = 3; i <= 100; ++i) { LinkedList<int>::ItemPtr item(new LinkedList<int>::Item); item->value = i; if(i < 50) l.push_back(item); else l.push_front(item); } for(int i = 100; i >= 50; --i) { LinkedList<int>::ItemPtr item = l.pop_front(); assert(item->value == i); } }; auto reader = [&l]() { int endCount = 0; while(true) { int old = -1; int m = 0; int count = 0; for(auto v : l) { assert(v >= 1); if(old >= 50 && v == 1) {} else if(old >= 50) assert(old - 1 == v); else if(old >= 0) assert(old + 1 == v); old = v; if(v > m) m = v; ++count; } assert(count >= 2); assert(count <= 100); assert(count == m); if(count >= 50) assert(old == 49); if(count < 100) assert(endCount == 0); if(count == 100) endCount++; if(endCount >= 10) break; } }; for(int i = 0; i < 1000; ++i) { l.push_back()->value = 1; l.push_back()->value = 2; std::thread t1(producer), t3(reader); t1.join(); t3.join(); l._checkSanity(); l.clear(); } } int main() { test0(); test1(); test2(); test3(); test4(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Advanced Normalization Tools Copyright (c) ConsortiumOfANTS. All rights reserved. See accompanying COPYING.txt or https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkANTSImageTransformation_hxx_ #define _itkANTSImageTransformation_hxx_ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "ANTS_affine_registration2.h" #include "itkANTSImageTransformation.h" #include "itkIdentityTransform.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkLinearInterpolateImageFunction.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkResampleImageFilter.h" // #include "itkVectorImageFileWriter.h" #include "vnl/vnl_math.h" namespace itk { template <unsigned int TDimension, class TReal> ANTSImageTransformation<TDimension, TReal> ::ANTSImageTransformation() { this->m_DisplacementField = ITK_NULLPTR; this->m_InverseDisplacementField = ITK_NULLPTR; this->m_AffineTransform = ITK_NULLPTR; this->m_WriteComponentImages = false; m_DeformationRegionOfInterestSize.Fill(0); m_DeformationRegionSpacing.Fill(1); m_DeformationRegionOfInterestCenter.Fill(0); } template <unsigned int TDimension, class TReal> void ANTSImageTransformation<TDimension, TReal> ::Compose() { } template <unsigned int TDimension, class TReal> void ANTSImageTransformation<TDimension, TReal> ::Write() { std::cout << " begin writing " << m_NamingConvention << std::endl; std::string filePrefix = this->m_NamingConvention; std::string::size_type pos = filePrefix.rfind( "." ); std::string extension; std::string gzExtension( "" ); if( pos != std::string::npos && std::string( filePrefix, pos, pos + 2 ) != std::string( "./" ) ) { bool is_supported = false; filePrefix = std::string( filePrefix, 0, pos ); extension = std::string( this->m_NamingConvention, pos, this->m_NamingConvention.length() - 1 ); if( extension == std::string( ".gz" ) ) { gzExtension = std::string( ".gz" ); pos = filePrefix.rfind( "." ); extension = std::string( filePrefix, pos, filePrefix.length() - 1 ); filePrefix = std::string( filePrefix, 0, pos ); } // GetSupportedWriteExtensions typedef itk::ImageIOBase IOBaseType; typedef std::list<itk::LightObject::Pointer> ArrayOfImageIOType; typedef typename IOBaseType::ArrayOfExtensionsType ArrayOfExtensionsType; ArrayOfImageIOType allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); ArrayOfImageIOType::iterator itr = allobjects.begin(); while( itr != allobjects.end() ) { IOBaseType * io = dynamic_cast<IOBaseType *>( itr->GetPointer() ); if( !io ) { std::cout << "Got a null pointer in the array" << std::endl; } else { const ArrayOfExtensionsType & writeExtensions = io->GetSupportedWriteExtensions(); ArrayOfExtensionsType::const_iterator writeItr = writeExtensions.begin(); while( writeItr != writeExtensions.end() ) { std::string test_ext = *writeItr; // std::cout <<" compare " << extension << " to " << test_ext << std::endl; if( extension == test_ext ) { is_supported = true; } // else std::cout <<" not the same " << std::endl; ++writeItr; } } ++itr; } if( !is_supported ) { std::cout << " WARNING! we are guessing you want nii.gz for your image output instead of: " << extension << std::endl; filePrefix = this->m_NamingConvention; extension = std::string(".nii.gz"); } } else { extension = std::string( ".nii.gz" ); } // Added by songgang if( this->m_AffineTransform ) { std::cout << " writing " << filePrefix << " affine " << std::endl; const std::string filename = filePrefix + std::string( "Affine.txt" ); WriteAffineTransformFile<AffineTransformType>(this->m_AffineTransform, filename); } if( this->m_DisplacementField ) { std::cout << " writing " << filePrefix << " def " << std::endl; if( extension != std::string( ".mha" ) ) { std::string filename = filePrefix + std::string( "Warp" ) + extension + gzExtension; typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); std::cout << "filename " << filename << std::endl; writer->SetFileName( filename ); // writer->SetUseAvantsNamingConvention( true ); writer->SetInput( this->m_DisplacementField ); writer->Update(); } else { std::string filename = filePrefix + std::string( "Warp.nii.gz" ); typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( filename ); writer->SetInput( this->m_DisplacementField ); writer->Update(); } } if( this->m_InverseDisplacementField ) { if( extension != std::string( ".mha" ) ) { std::string filename = filePrefix + std::string( "InverseWarp" ) + extension + gzExtension; typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( filename ); // writer->SetUseAvantsNamingConvention( true ); writer->SetInput( this->m_InverseDisplacementField ); writer->Update(); } else { std::string filename = filePrefix + std::string( "InverseWarp.mha" ); typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( filename ); writer->SetInput( this->m_InverseDisplacementField ); writer->Update(); } } } /** * Standard "PrintSelf" method */ template <unsigned int TDimension, class TReal> void ANTSImageTransformation<TDimension, TReal> ::PrintSelf( std::ostream& os, Indent indent) const { Superclass::PrintSelf( os, indent ); } } // end namespace itk #endif <commit_msg>Added XFM writing ability<commit_after>/*========================================================================= Program: Advanced Normalization Tools Copyright (c) ConsortiumOfANTS. All rights reserved. See accompanying COPYING.txt or https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkANTSImageTransformation_hxx_ #define _itkANTSImageTransformation_hxx_ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "ANTS_affine_registration2.h" #include "itkANTSImageTransformation.h" #include "itkIdentityTransform.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkLinearInterpolateImageFunction.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkResampleImageFilter.h" #include "itkTransformFileWriter.h" #include "vnl/vnl_math.h" namespace itk { template <unsigned int TDimension, class TReal> ANTSImageTransformation<TDimension, TReal> ::ANTSImageTransformation() { this->m_DisplacementField = ITK_NULLPTR; this->m_InverseDisplacementField = ITK_NULLPTR; this->m_AffineTransform = ITK_NULLPTR; this->m_WriteComponentImages = false; m_DeformationRegionOfInterestSize.Fill(0); m_DeformationRegionSpacing.Fill(1); m_DeformationRegionOfInterestCenter.Fill(0); } template <unsigned int TDimension, class TReal> void ANTSImageTransformation<TDimension, TReal> ::Compose() { } template <unsigned int TDimension, class TReal> void ANTSImageTransformation<TDimension, TReal> ::Write() { std::cout << " begin writing " << m_NamingConvention << std::endl; std::string filePrefix = this->m_NamingConvention; std::string::size_type pos = filePrefix.rfind( "." ); std::string extension; std::string gzExtension( "" ); if( pos != std::string::npos && std::string( filePrefix, pos, pos + 2 ) != std::string( "./" ) ) { bool is_supported = false; filePrefix = std::string( filePrefix, 0, pos ); extension = std::string( this->m_NamingConvention, pos, this->m_NamingConvention.length() - 1 ); if( extension == std::string( ".gz" ) ) { gzExtension = std::string( ".gz" ); pos = filePrefix.rfind( "." ); extension = std::string( filePrefix, pos, filePrefix.length() - 1 ); filePrefix = std::string( filePrefix, 0, pos ); } // GetSupportedWriteExtensions typedef itk::ImageIOBase IOBaseType; typedef std::list<itk::LightObject::Pointer> ArrayOfImageIOType; typedef typename IOBaseType::ArrayOfExtensionsType ArrayOfExtensionsType; ArrayOfImageIOType allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); ArrayOfImageIOType::iterator itr = allobjects.begin(); while( itr != allobjects.end() ) { IOBaseType * io = dynamic_cast<IOBaseType *>( itr->GetPointer() ); if( !io ) { std::cout << "Got a null pointer in the array" << std::endl; } else { const ArrayOfExtensionsType & writeExtensions = io->GetSupportedWriteExtensions(); ArrayOfExtensionsType::const_iterator writeItr = writeExtensions.begin(); while( writeItr != writeExtensions.end() ) { std::string test_ext = *writeItr; // std::cout <<" compare " << extension << " to " << test_ext << std::endl; if( extension == test_ext ) { is_supported = true; } // else std::cout <<" not the same " << std::endl; ++writeItr; } } ++itr; } if( !is_supported ) { std::cout << " WARNING! we are guessing you want .mnc for your image output instead of: " << extension << std::endl; filePrefix = this->m_NamingConvention; extension = std::string(".mnc"); } } else { extension = std::string( ".mnc" ); } if( extension==std::string( ".xfm") ) { std::string fw_filename = filePrefix + extension; std::string bw_filename = filePrefix + "_inverse" + extension; //using ITKv4 functionality to write transforms typedef itk::TransformFileWriterTemplate<float> TransformFileWriterFloat; TransformFileWriterFloat::Pointer fw_writer=TransformFileWriterFloat::New(); if( this->m_AffineTransform ) fw_writer->AddTransform(this->m_AffineTransform); if(this->m_DisplacementField) fw_writer->AddTransform(this->m_DisplacementField); fw_writer->SetFileName(fw_filename); fw_writer->Update(); TransformFileWriterFloat::Pointer bw_writer=TransformFileWriterFloat::New(); if(this->m_InverseDisplacementField) bw_writer->AddTransform(this->m_InverseDisplacementField); typename AffineTransformType::Pointer tmp=AffineTransformType::New(); if( this->m_AffineTransform ) { this->m_AffineTransform->GetInverse(tmp); bw_writer->AddTransform(tmp); } bw_writer->SetFileName(bw_filename); bw_writer->Update(); } else { // Added by songgang if( this->m_AffineTransform ) { std::cout << " writing " << filePrefix << " affine " << std::endl; const std::string filename = filePrefix + std::string( "Affine.txt" ); WriteAffineTransformFile<AffineTransformType>(this->m_AffineTransform, filename); } if( this->m_DisplacementField ) { std::cout << " writing " << filePrefix << " def " << std::endl; if( extension != std::string( ".mha" ) ) { std::string filename = filePrefix + std::string( "Warp" ) + extension + gzExtension; typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); std::cout << "filename " << filename << std::endl; writer->SetFileName( filename ); // writer->SetUseAvantsNamingConvention( true ); writer->SetInput( this->m_DisplacementField ); writer->Update(); } else { std::string filename = filePrefix + std::string( "Warp.nii.gz" ); typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( filename ); writer->SetInput( this->m_DisplacementField ); writer->Update(); } } if( this->m_InverseDisplacementField ) { if( extension != std::string( ".mha" ) ) { std::string filename = filePrefix + std::string( "InverseWarp" ) + extension + gzExtension; typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( filename ); // writer->SetUseAvantsNamingConvention( true ); writer->SetInput( this->m_InverseDisplacementField ); writer->Update(); } else { std::string filename = filePrefix + std::string( "InverseWarp.mha" ); typedef ImageFileWriter<DisplacementFieldType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( filename ); writer->SetInput( this->m_InverseDisplacementField ); writer->Update(); } } } } /** * Standard "PrintSelf" method */ template <unsigned int TDimension, class TReal> void ANTSImageTransformation<TDimension, TReal> ::PrintSelf( std::ostream& os, Indent indent) const { Superclass::PrintSelf( os, indent ); } } // end namespace itk #endif <|endoftext|>
<commit_before>#include "tileManager.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include <chrono> #include <algorithm> TileManager::TileManager() { // Instantiate workers for (size_t i = 0; i < MAX_WORKERS; i++) { m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker())); } } TileManager::TileManager(TileManager&& _other) : m_view(std::move(_other.m_view)), m_tileSet(std::move(_other.m_tileSet)), m_dataSources(std::move(_other.m_dataSources)), m_workers(std::move(_other.m_workers)), m_queuedTiles(std::move(_other.m_queuedTiles)) { } TileManager::~TileManager() { for (auto& worker : m_workers) { if (!worker->isFree()) { worker->abort(); worker->getTileResult(); } // We stop all workers before we destroy the resources they use. // TODO: This will wait for any pending network requests to finish, // which could delay closing of the application. } m_dataSources.clear(); m_tileSet.clear(); } void TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, const int _dataSourceID) { std::lock_guard<std::mutex> lock(m_queueTileMutex); m_queuedTiles.push_back(std::unique_ptr<WorkerData>(new WorkerData(std::move(_rawData), _tileId, _dataSourceID))); } void TileManager::updateTileSet() { m_tileSetChanged = false; // Check if any native worker needs to be dispatched i.e. queuedTiles is not empty { auto workersIter = m_workers.begin(); auto queuedTilesIter = m_queuedTiles.begin(); while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) { auto& worker = *workersIter; if (worker->isFree()) { logMsg("Dispatched worker for processing tile: [%d, %d, %d]\n", (*queuedTilesIter)->tileID->x, (*queuedTilesIter)->tileID->y, (*queuedTilesIter)->tileID->z); worker->processTileData(std::move(*queuedTilesIter), m_dataSources, m_scene->getStyles(), *m_view); queuedTilesIter = m_queuedTiles.erase(queuedTilesIter); } ++workersIter; } } // Check if any incoming tiles are finished for (auto& worker : m_workers) { if (!worker->isFree() && worker->isFinished()) { // Get result from worker and move it into tile set auto tile = worker->getTileResult(); const TileID& id = tile->getID(); logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y); std::swap(m_tileSet[id], tile); cleanProxyTiles(id); m_tileSetChanged = true; } } if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) { // No new tiles have come into view and no tiles have finished loading, // so the tileset is unchanged return; } const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); // Loop over visibleTiles and add any needed tiles to tileSet { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (visTilesIter != visibleTiles.end()) { if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles addTile(*visTilesIter); m_tileSetChanged = true; ++visTilesIter; } else if (setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet (handled below) ++setTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } // Loop over tileSet and remove any tiles that are neither visible nor proxies { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (setTilesIter != m_tileSet.end()) { if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet if (setTilesIter->second->getProxyCounter() <= 0) { removeTile(setTilesIter); m_tileSetChanged = true; } else { ++setTilesIter; } } else if (*visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles (shouldn't occur) ++visTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } } void TileManager::addTile(const TileID& _tileID) { std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection())); m_tileSet[_tileID] = std::move(tile); for(size_t dsIndex = 0; dsIndex < m_dataSources.size(); dsIndex++) { // ByPass Network Request if data already loaded/parsed // Create workerData with empty "rawData", parsed data will be fetched in the Worker::processTileData logMsg("Initiate network request for tile: [%d, %d, %d]\n", _tileID.x, _tileID.y, _tileID.z); if(m_dataSources[dsIndex]->hasTileData(_tileID)) { addToWorkerQueue(std::move(std::vector<char>()), _tileID, dsIndex); } else if( !m_dataSources[dsIndex]->loadTileData(_tileID, dsIndex) ) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _tileID.z, _tileID.x, _tileID.y); } } //Add Proxy if corresponding proxy MapTile ready updateProxyTiles(_tileID, m_view->isZoomIn()); } void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) { const TileID& id = _tileIter->first; // Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable for(auto& dataSource : m_dataSources) { dataSource->cancelLoadingTile(id); } // Remove tile from queue, if present const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(), [&](std::unique_ptr<WorkerData>& p) { return ( *(p->tileID) == id); }); if (found != m_queuedTiles.end()) { logMsg("Erasing tile: [%d,%d,%d]\n", id.x, id.y, id.z); m_queuedTiles.erase(found); cleanProxyTiles(id); } // If a worker is processing this tile, abort it for (const auto& worker : m_workers) { if (!worker->isFree() && worker->getTileID() == id) { worker->abort(); // Proxy tiles will be cleaned in update loop } } // Remove labels for tile LabelContainer::GetInstance()->removeLabels(id); // Remove tile from set _tileIter = m_tileSet.erase(_tileIter); } void TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) { if (_zoomingIn) { // zoom in - add parent const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->incProxyCounter(); } } else { for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->incProxyCounter(); } } } } void TileManager::cleanProxyTiles(const TileID& _tileID) { // check if parent proxy is present const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->decProxyCounter(); } // check if child proxies are present for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->decProxyCounter(); } } } <commit_msg>all proxies were not being cleared on removeTile<commit_after>#include "tileManager.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include <chrono> #include <algorithm> TileManager::TileManager() { // Instantiate workers for (size_t i = 0; i < MAX_WORKERS; i++) { m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker())); } } TileManager::TileManager(TileManager&& _other) : m_view(std::move(_other.m_view)), m_tileSet(std::move(_other.m_tileSet)), m_dataSources(std::move(_other.m_dataSources)), m_workers(std::move(_other.m_workers)), m_queuedTiles(std::move(_other.m_queuedTiles)) { } TileManager::~TileManager() { for (auto& worker : m_workers) { if (!worker->isFree()) { worker->abort(); worker->getTileResult(); } // We stop all workers before we destroy the resources they use. // TODO: This will wait for any pending network requests to finish, // which could delay closing of the application. } m_dataSources.clear(); m_tileSet.clear(); } void TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, const int _dataSourceID) { std::lock_guard<std::mutex> lock(m_queueTileMutex); m_queuedTiles.push_back(std::unique_ptr<WorkerData>(new WorkerData(std::move(_rawData), _tileId, _dataSourceID))); } void TileManager::updateTileSet() { m_tileSetChanged = false; // Check if any native worker needs to be dispatched i.e. queuedTiles is not empty { auto workersIter = m_workers.begin(); auto queuedTilesIter = m_queuedTiles.begin(); while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) { auto& worker = *workersIter; if (worker->isFree()) { logMsg("Dispatched worker for processing tile: [%d, %d, %d]\n", (*queuedTilesIter)->tileID->x, (*queuedTilesIter)->tileID->y, (*queuedTilesIter)->tileID->z); worker->processTileData(std::move(*queuedTilesIter), m_dataSources, m_scene->getStyles(), *m_view); queuedTilesIter = m_queuedTiles.erase(queuedTilesIter); } ++workersIter; } } // Check if any incoming tiles are finished for (auto& worker : m_workers) { if (!worker->isFree() && worker->isFinished()) { // Get result from worker and move it into tile set auto tile = worker->getTileResult(); const TileID& id = tile->getID(); logMsg("Tile [%d, %d, %d] finished loading\n", id.z, id.x, id.y); std::swap(m_tileSet[id], tile); cleanProxyTiles(id); m_tileSetChanged = true; } } if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) { // No new tiles have come into view and no tiles have finished loading, // so the tileset is unchanged return; } const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); // Loop over visibleTiles and add any needed tiles to tileSet { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (visTilesIter != visibleTiles.end()) { if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles addTile(*visTilesIter); m_tileSetChanged = true; ++visTilesIter; } else if (setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet (handled below) ++setTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } // Loop over tileSet and remove any tiles that are neither visible nor proxies { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (setTilesIter != m_tileSet.end()) { if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) { // visibleTiles is missing an element present in tileSet if (setTilesIter->second->getProxyCounter() <= 0) { removeTile(setTilesIter); m_tileSetChanged = true; } else { ++setTilesIter; } } else if (*visTilesIter < setTilesIter->first) { // tileSet is missing an element present in visibleTiles (shouldn't occur) ++visTilesIter; } else { // tiles in both sets match, move on ++setTilesIter; ++visTilesIter; } } } } void TileManager::addTile(const TileID& _tileID) { std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection())); m_tileSet[_tileID] = std::move(tile); for(size_t dsIndex = 0; dsIndex < m_dataSources.size(); dsIndex++) { // ByPass Network Request if data already loaded/parsed // Create workerData with empty "rawData", parsed data will be fetched in the Worker::processTileData logMsg("Initiate network request for tile: [%d, %d, %d]\n", _tileID.x, _tileID.y, _tileID.z); if(m_dataSources[dsIndex]->hasTileData(_tileID)) { addToWorkerQueue(std::move(std::vector<char>()), _tileID, dsIndex); } else if( !m_dataSources[dsIndex]->loadTileData(_tileID, dsIndex) ) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", _tileID.z, _tileID.x, _tileID.y); } } //Add Proxy if corresponding proxy MapTile ready updateProxyTiles(_tileID, m_view->isZoomIn()); } void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) { const TileID& id = _tileIter->first; // Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable for(auto& dataSource : m_dataSources) { dataSource->cancelLoadingTile(id); cleanProxyTiles(id); } // Remove tile from queue, if present const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(), [&](std::unique_ptr<WorkerData>& p) { return ( *(p->tileID) == id); }); if (found != m_queuedTiles.end()) { logMsg("Erasing tile: [%d,%d,%d]\n", id.x, id.y, id.z); m_queuedTiles.erase(found); cleanProxyTiles(id); } // If a worker is processing this tile, abort it for (const auto& worker : m_workers) { if (!worker->isFree() && worker->getTileID() == id) { worker->abort(); // Proxy tiles will be cleaned in update loop } } // Remove labels for tile LabelContainer::GetInstance()->removeLabels(id); // Remove tile from set _tileIter = m_tileSet.erase(_tileIter); } void TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) { if (_zoomingIn) { // zoom in - add parent const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->incProxyCounter(); } } else { for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->incProxyCounter(); } } } } void TileManager::cleanProxyTiles(const TileID& _tileID) { // check if parent proxy is present const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentID.isValid() && parentTileIter != m_tileSet.end()) { parentTileIter->second->decProxyCounter(); } // check if child proxies are present for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) { childTileIter->second->decProxyCounter(); } } } <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests singleton dataset // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #if BOOST_PP_VARIADICS #include <boost/test/data/test_case.hpp> #include <boost/test/data/monomorphic.hpp> namespace data=boost::unit_test::data; #include "test_datasets.hpp" //____________________________________________________________________________// int samples1[] = {1,2,3}; int index1 = 0; BOOST_DATA_TEST_CASE( test_case_interface_01, samples1 ) { BOOST_TEST( sample == samples1[index1++] ); } //____________________________________________________________________________// char const* samples2[] = {"qwerty","asdfg"}; int index2 = 0; BOOST_DATA_TEST_CASE( test_case_interface_02, samples2, str ) { BOOST_TEST( str == samples2[index2++] ); } //____________________________________________________________________________// #ifndef BOOST_NO_CXX11_DECLTYPE int samples3[] = {7,9}; int index3 = 0; BOOST_DATA_TEST_CASE( test_case_interface_03, data::make(samples1)+samples3, val ) { if( index3 < 3 ) BOOST_TEST( val == samples1[index3] ); else BOOST_TEST( val == samples3[index3-3] ); ++index3; } //____________________________________________________________________________// int index4 = 0; BOOST_DATA_TEST_CASE( test_case_interface_04, data::make(samples2)^samples3, str, intval ) { BOOST_TEST( str == samples2[index4] ); BOOST_TEST( intval == samples3[index4] ); ++index4; } //____________________________________________________________________________// int index5 = 0; BOOST_DATA_TEST_CASE( test_case_interface_05, data::make(samples1) * samples2, sample0, sample1 ) { BOOST_TEST( sample0 == samples1[index5/2] ); BOOST_TEST( sample1 == samples2[index5%2] ); ++index5; } //____________________________________________________________________________// int index6 = 0; BOOST_DATA_TEST_CASE( test_case_interface_06, data::make(samples1) * samples2 * samples3, intval, str, val2 ) { BOOST_TEST( intval == samples1[index6/4] ); BOOST_TEST( str == samples2[(index6/2)%2] ); BOOST_TEST( val2 == samples3[index6%2] ); ++index6; } //____________________________________________________________________________// #endif // BOOST_NO_CXX11_DECLTYPE #endif // BOOST_PP_VARIADICS // EOF <commit_msg>Fix gcc 4.4
<commit_after>// (C) Copyright Gennadiy Rozental 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests singleton dataset // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #if BOOST_PP_VARIADICS #include <boost/test/data/test_case.hpp> #include <boost/test/data/monomorphic.hpp> namespace data=boost::unit_test::data; #include "test_datasets.hpp" //____________________________________________________________________________// int samples1[] = {1,2,3}; int index1 = 0; BOOST_DATA_TEST_CASE( test_case_interface_01, samples1 ) { BOOST_TEST( sample == samples1[index1++] ); } //____________________________________________________________________________// char const* samples2[] = {"qwerty","asdfg"}; int index2 = 0; BOOST_DATA_TEST_CASE( test_case_interface_02, samples2, str ) { BOOST_TEST( str == samples2[index2++] ); } //____________________________________________________________________________// #ifndef BOOST_NO_CXX11_DECLTYPE int samples3[] = {7,9}; int index3 = 0; BOOST_DATA_TEST_CASE( test_case_interface_03, data::make(samples1)+samples3, val ) { if( index3 < 3 ) BOOST_TEST( val == samples1[index3] ); else BOOST_TEST( val == samples3[index3-3] ); ++index3; } //____________________________________________________________________________// #ifndef BOOST_TEST_NO_ZIP_COMPOSITION_AVAILABLE int index4 = 0; BOOST_DATA_TEST_CASE( test_case_interface_04, data::make(samples2)^samples3, str, intval ) { BOOST_TEST( str == samples2[index4] ); BOOST_TEST( intval == samples3[index4] ); ++index4; } #endif //____________________________________________________________________________// #ifndef BOOST_TEST_NO_GRID_COMPOSITION_AVAILABLE int index5 = 0; BOOST_DATA_TEST_CASE( test_case_interface_05, data::make(samples1) * samples2, sample0, sample1 ) { BOOST_TEST( sample0 == samples1[index5/2] ); BOOST_TEST( sample1 == samples2[index5%2] ); ++index5; } //____________________________________________________________________________// int index6 = 0; BOOST_DATA_TEST_CASE( test_case_interface_06, data::make(samples1) * samples2 * samples3, intval, str, val2 ) { BOOST_TEST( intval == samples1[index6/4] ); BOOST_TEST( str == samples2[(index6/2)%2] ); BOOST_TEST( val2 == samples3[index6%2] ); ++index6; } #endif //____________________________________________________________________________// #endif // BOOST_PP_VARIADICS <|endoftext|>
<commit_before>#include "errors.hpp" #include "arch/arch.hpp" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <boost/scoped_array.hpp> /* head functions */ template<class metablock_t> metablock_manager_t<metablock_t>::metablock_manager_t::head_t::head_t(metablock_manager_t *manager) : mb_slot(0), saved_mb_slot(-1), wraparound(false), mgr(manager) { } template<class metablock_t> void metablock_manager_t<metablock_t>::metablock_manager_t::head_t::operator++(UNUSED int stupid_plusplus_parameter) { mb_slot++; wraparound = false; if (mb_slot >= mgr->metablock_offsets.size()) { mb_slot = 0; wraparound = true; } } template<class metablock_t> off64_t metablock_manager_t<metablock_t>::metablock_manager_t::head_t::offset() { return mgr->metablock_offsets[mb_slot]; } template<class metablock_t> void metablock_manager_t<metablock_t>::metablock_manager_t::head_t::push() { saved_mb_slot = mb_slot; } template<class metablock_t> void metablock_manager_t<metablock_t>::metablock_manager_t::head_t::pop() { guarantee(saved_mb_slot != (uint32_t) -1, "Popping without a saved state"); mb_slot = saved_mb_slot; saved_mb_slot = -1; } template<class metablock_t> metablock_manager_t<metablock_t>::metablock_manager_t(extent_manager_t *em) : head(this), extent_manager(em), state(state_unstarted), dbfile(NULL) { rassert(sizeof(crc_metablock_t) <= DEVICE_BLOCK_SIZE); mb_buffer = (crc_metablock_t *)malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE); startup_values.mb_buffer_last = (crc_metablock_t *)malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE); rassert(mb_buffer); mb_buffer_in_use = false; /* Build the list of metablock locations in the file */ for (off64_t i = 0; i < MB_NEXTENTS; i++) { off64_t extent = i * extent_manager->extent_size * MB_EXTENT_SEPARATION; /* The reason why we don't reserve extent 0 is that it has already been reserved for the static header. We can share the first extent with the static header if and only if we don't overwrite the first DEVICE_BLOCK_SIZE of it, but we musn't reserve it again. */ if (extent != 0) extent_manager->reserve_extent(extent); } initialize_metablock_offsets(extent_manager->extent_size, &metablock_offsets); } template<class metablock_t> metablock_manager_t<metablock_t>::~metablock_manager_t() { rassert(state == state_unstarted || state == state_shut_down); rassert(!mb_buffer_in_use); free(mb_buffer); free(startup_values.mb_buffer_last); startup_values.mb_buffer_last = NULL; } template<class metablock_t> void metablock_manager_t<metablock_t>::create(direct_file_t *dbfile, off64_t extent_size, metablock_t *initial) { std::vector<off64_t> metablock_offsets; initialize_metablock_offsets(extent_size, &metablock_offsets); dbfile->set_size_at_least(metablock_offsets[metablock_offsets.size() - 1] + DEVICE_BLOCK_SIZE); /* Allocate a buffer for doing our writes */ crc_metablock_t *buffer = reinterpret_cast<crc_metablock_t*>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE)); bzero(buffer, DEVICE_BLOCK_SIZE); /* Wipe the metablock slots so we don't mistake something left by a previous database for a valid metablock. */ for (unsigned i = 0; i < metablock_offsets.size(); i++) { co_write(dbfile, metablock_offsets[i], DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT); } /* Write the first metablock */ buffer->prepare(initial, MB_START_VERSION); co_write(dbfile, metablock_offsets[0], DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT); free(buffer); } template<class metablock_t> void metablock_manager_t<metablock_t>::co_start_existing(direct_file_t *file, bool *mb_found, metablock_t *mb_out) { rassert(state == state_unstarted); dbfile = file; rassert(dbfile != NULL); rassert(!mb_buffer_in_use); mb_buffer_in_use = true; startup_values.version = MB_BAD_VERSION; dbfile->set_size_at_least(metablock_offsets[metablock_offsets.size() - 1] + DEVICE_BLOCK_SIZE); co_read(dbfile, head.offset(), DEVICE_BLOCK_SIZE, mb_buffer, DEFAULT_DISK_ACCOUNT); state = state_reading; bool done_looking = false; while (!done_looking) { if (mb_buffer->check_crc()) { if (mb_buffer->version > startup_values.version) { /* this metablock is good, maybe there are more? */ startup_values.version = mb_buffer->version; head.push(); head++; /* mb_buffer_last = mb_buffer and give mb_buffer mb_buffer_last's space so no realloc */ swap_buffers(); done_looking = head.wraparound; } else { /* version smaller than the one we just had, yahtzee */ done_looking = true; } } else { head++; done_looking = head.wraparound; } if (done_looking) { if (startup_values.version == MB_BAD_VERSION) { /* no metablock found anywhere -- the DB is toast */ next_version_number = MB_START_VERSION; *mb_found = false; /* The log serializer will catastrophically fail when it sees that mb_found is false. We could catastrophically fail here, but it's a bit nicer to have the metablock manager as a standalone component that doesn't know how to behave if there is no metablock. */ } else { /* we found a metablock */ swap_buffers(); /* set everything up */ next_version_number = startup_values.version + 1; startup_values.version = MB_BAD_VERSION; /* version is now useless */ head.pop(); *mb_found = true; memcpy(mb_out, &(mb_buffer->metablock), sizeof(metablock_t)); } mb_buffer_in_use = false; state = state_ready; } else { co_read(dbfile, head.offset(), DEVICE_BLOCK_SIZE, mb_buffer, DEFAULT_DISK_ACCOUNT); } } } //The following two functions will go away in favor of the preceding one template<class metablock_t> void metablock_manager_t<metablock_t>::start_existing_callback(direct_file_t *file, bool *mb_found, metablock_t *mb_out, metablock_read_callback_t *cb) { co_start_existing(file, mb_found, mb_out); cb->on_metablock_read(); } template<class metablock_t> bool metablock_manager_t<metablock_t>::start_existing(direct_file_t *file, bool *mb_found, metablock_t *mb_out, metablock_read_callback_t *cb) { coro_t::spawn(boost::bind(&metablock_manager_t<metablock_t>::start_existing_callback, this, file, mb_found, mb_out, cb)); return false; } template<class metablock_t> void metablock_manager_t<metablock_t>::co_write_metablock(metablock_t *mb, file_t::account_t *io_account) { mutex_acquisition_t hold(&write_lock); rassert(state == state_ready); rassert(!mb_buffer_in_use); mb_buffer->prepare(mb, next_version_number++); rassert(mb_buffer->check_crc()); mb_buffer_in_use = true; state = state_writing; co_write(dbfile, head.offset(), DEVICE_BLOCK_SIZE, mb_buffer, io_account); head++; state = state_ready; mb_buffer_in_use = false; } template<class metablock_t> void metablock_manager_t<metablock_t>::write_metablock_callback(metablock_t *mb, file_t::account_t *io_account, metablock_write_callback_t *cb) { co_write_metablock(mb, io_account); cb->on_metablock_write(); } template<class metablock_t> bool metablock_manager_t<metablock_t>::write_metablock(metablock_t *mb, file_t::account_t *io_account, metablock_write_callback_t *cb) { coro_t::spawn(boost::bind(&metablock_manager_t<metablock_t>::write_metablock_callback, this, mb, io_account, cb)); return false; } template<class metablock_t> void metablock_manager_t<metablock_t>::shutdown() { rassert(state == state_ready); rassert(!mb_buffer_in_use); state = state_shut_down; } template<class metablock_t> void metablock_manager_t<metablock_t>::swap_buffers() { crc_metablock_t *tmp = startup_values.mb_buffer_last; startup_values.mb_buffer_last = mb_buffer; mb_buffer = tmp; } <commit_msg>Wipe metablock slots in parallel so that database creation is faster.<commit_after>#include "errors.hpp" #include "arch/arch.hpp" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <boost/scoped_array.hpp> /* head functions */ template<class metablock_t> metablock_manager_t<metablock_t>::metablock_manager_t::head_t::head_t(metablock_manager_t *manager) : mb_slot(0), saved_mb_slot(-1), wraparound(false), mgr(manager) { } template<class metablock_t> void metablock_manager_t<metablock_t>::metablock_manager_t::head_t::operator++(UNUSED int stupid_plusplus_parameter) { mb_slot++; wraparound = false; if (mb_slot >= mgr->metablock_offsets.size()) { mb_slot = 0; wraparound = true; } } template<class metablock_t> off64_t metablock_manager_t<metablock_t>::metablock_manager_t::head_t::offset() { return mgr->metablock_offsets[mb_slot]; } template<class metablock_t> void metablock_manager_t<metablock_t>::metablock_manager_t::head_t::push() { saved_mb_slot = mb_slot; } template<class metablock_t> void metablock_manager_t<metablock_t>::metablock_manager_t::head_t::pop() { guarantee(saved_mb_slot != (uint32_t) -1, "Popping without a saved state"); mb_slot = saved_mb_slot; saved_mb_slot = -1; } template<class metablock_t> metablock_manager_t<metablock_t>::metablock_manager_t(extent_manager_t *em) : head(this), extent_manager(em), state(state_unstarted), dbfile(NULL) { rassert(sizeof(crc_metablock_t) <= DEVICE_BLOCK_SIZE); mb_buffer = (crc_metablock_t *)malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE); startup_values.mb_buffer_last = (crc_metablock_t *)malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE); rassert(mb_buffer); mb_buffer_in_use = false; /* Build the list of metablock locations in the file */ for (off64_t i = 0; i < MB_NEXTENTS; i++) { off64_t extent = i * extent_manager->extent_size * MB_EXTENT_SEPARATION; /* The reason why we don't reserve extent 0 is that it has already been reserved for the static header. We can share the first extent with the static header if and only if we don't overwrite the first DEVICE_BLOCK_SIZE of it, but we musn't reserve it again. */ if (extent != 0) extent_manager->reserve_extent(extent); } initialize_metablock_offsets(extent_manager->extent_size, &metablock_offsets); } template<class metablock_t> metablock_manager_t<metablock_t>::~metablock_manager_t() { rassert(state == state_unstarted || state == state_shut_down); rassert(!mb_buffer_in_use); free(mb_buffer); free(startup_values.mb_buffer_last); startup_values.mb_buffer_last = NULL; } template<class metablock_t> void metablock_manager_t<metablock_t>::create(direct_file_t *dbfile, off64_t extent_size, metablock_t *initial) { std::vector<off64_t> metablock_offsets; initialize_metablock_offsets(extent_size, &metablock_offsets); dbfile->set_size_at_least(metablock_offsets[metablock_offsets.size() - 1] + DEVICE_BLOCK_SIZE); /* Allocate a buffer for doing our writes */ crc_metablock_t *buffer = reinterpret_cast<crc_metablock_t*>(malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE)); bzero(buffer, DEVICE_BLOCK_SIZE); /* Wipe the metablock slots so we don't mistake something left by a previous database for a valid metablock. */ struct : public iocallback_t, public cond_t { int refcount; void on_io_complete() { refcount--; if (refcount == 0) pulse(); } } callback; callback.refcount = metablock_offsets.size(); for (unsigned i = 0; i < metablock_offsets.size(); i++) { dbfile->write_async(metablock_offsets[i], DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT, &callback); } callback.wait(); /* Write the first metablock */ buffer->prepare(initial, MB_START_VERSION); co_write(dbfile, metablock_offsets[0], DEVICE_BLOCK_SIZE, buffer, DEFAULT_DISK_ACCOUNT); free(buffer); } template<class metablock_t> void metablock_manager_t<metablock_t>::co_start_existing(direct_file_t *file, bool *mb_found, metablock_t *mb_out) { rassert(state == state_unstarted); dbfile = file; rassert(dbfile != NULL); rassert(!mb_buffer_in_use); mb_buffer_in_use = true; startup_values.version = MB_BAD_VERSION; dbfile->set_size_at_least(metablock_offsets[metablock_offsets.size() - 1] + DEVICE_BLOCK_SIZE); co_read(dbfile, head.offset(), DEVICE_BLOCK_SIZE, mb_buffer, DEFAULT_DISK_ACCOUNT); state = state_reading; bool done_looking = false; while (!done_looking) { if (mb_buffer->check_crc()) { if (mb_buffer->version > startup_values.version) { /* this metablock is good, maybe there are more? */ startup_values.version = mb_buffer->version; head.push(); head++; /* mb_buffer_last = mb_buffer and give mb_buffer mb_buffer_last's space so no realloc */ swap_buffers(); done_looking = head.wraparound; } else { /* version smaller than the one we just had, yahtzee */ done_looking = true; } } else { head++; done_looking = head.wraparound; } if (done_looking) { if (startup_values.version == MB_BAD_VERSION) { /* no metablock found anywhere -- the DB is toast */ next_version_number = MB_START_VERSION; *mb_found = false; /* The log serializer will catastrophically fail when it sees that mb_found is false. We could catastrophically fail here, but it's a bit nicer to have the metablock manager as a standalone component that doesn't know how to behave if there is no metablock. */ } else { /* we found a metablock */ swap_buffers(); /* set everything up */ next_version_number = startup_values.version + 1; startup_values.version = MB_BAD_VERSION; /* version is now useless */ head.pop(); *mb_found = true; memcpy(mb_out, &(mb_buffer->metablock), sizeof(metablock_t)); } mb_buffer_in_use = false; state = state_ready; } else { co_read(dbfile, head.offset(), DEVICE_BLOCK_SIZE, mb_buffer, DEFAULT_DISK_ACCOUNT); } } } //The following two functions will go away in favor of the preceding one template<class metablock_t> void metablock_manager_t<metablock_t>::start_existing_callback(direct_file_t *file, bool *mb_found, metablock_t *mb_out, metablock_read_callback_t *cb) { co_start_existing(file, mb_found, mb_out); cb->on_metablock_read(); } template<class metablock_t> bool metablock_manager_t<metablock_t>::start_existing(direct_file_t *file, bool *mb_found, metablock_t *mb_out, metablock_read_callback_t *cb) { coro_t::spawn(boost::bind(&metablock_manager_t<metablock_t>::start_existing_callback, this, file, mb_found, mb_out, cb)); return false; } template<class metablock_t> void metablock_manager_t<metablock_t>::co_write_metablock(metablock_t *mb, file_t::account_t *io_account) { mutex_acquisition_t hold(&write_lock); rassert(state == state_ready); rassert(!mb_buffer_in_use); mb_buffer->prepare(mb, next_version_number++); rassert(mb_buffer->check_crc()); mb_buffer_in_use = true; state = state_writing; co_write(dbfile, head.offset(), DEVICE_BLOCK_SIZE, mb_buffer, io_account); head++; state = state_ready; mb_buffer_in_use = false; } template<class metablock_t> void metablock_manager_t<metablock_t>::write_metablock_callback(metablock_t *mb, file_t::account_t *io_account, metablock_write_callback_t *cb) { co_write_metablock(mb, io_account); cb->on_metablock_write(); } template<class metablock_t> bool metablock_manager_t<metablock_t>::write_metablock(metablock_t *mb, file_t::account_t *io_account, metablock_write_callback_t *cb) { coro_t::spawn(boost::bind(&metablock_manager_t<metablock_t>::write_metablock_callback, this, mb, io_account, cb)); return false; } template<class metablock_t> void metablock_manager_t<metablock_t>::shutdown() { rassert(state == state_ready); rassert(!mb_buffer_in_use); state = state_shut_down; } template<class metablock_t> void metablock_manager_t<metablock_t>::swap_buffers() { crc_metablock_t *tmp = startup_values.mb_buffer_last; startup_values.mb_buffer_last = mb_buffer; mb_buffer = tmp; } <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "DBCDatabaseLoader.h" #include "DatabaseEnv.h" #include "Errors.h" #include "StringFormat.h" DBCDatabaseLoader::DBCDatabaseLoader(char const* tableName, char const* dbcFormatString, std::vector<char*>& stringPool) : _sqlTableName(tableName), _dbcFormat(dbcFormatString), _sqlIndexPos(0), _recordSize(0), _stringPool(stringPool) { // Get sql index position int32 indexPos = -1; _recordSize = DBCFileLoader::GetFormatRecordSize(_dbcFormat, &indexPos); ASSERT(_recordSize); } char* DBCDatabaseLoader::Load(uint32& records, char**& indexTable) { std::string query = Acore::StringFormat("SELECT * FROM `%s` ORDER BY `ID` DESC", _sqlTableName); // no error if empty set QueryResult result = WorldDatabase.Query(query.c_str()); if (!result) return nullptr; // Check if sql index pos is valid if (int32(result->GetFieldCount() - 1) < _sqlIndexPos) { ASSERT(false, "Invalid index pos for dbc: '{}'", _sqlTableName); return nullptr; } // Resize index table // database query *MUST* contain ORDER BY `index_field` DESC clause uint32 indexTableSize = std::max(records, (*result)[_sqlIndexPos].Get<uint32>() + 1); if (indexTableSize > records) { char** tmpIdxTable = new char* [indexTableSize]; memset(tmpIdxTable, 0, indexTableSize * sizeof(char*)); memcpy(tmpIdxTable, indexTable, records * sizeof(char*)); delete[] indexTable; indexTable = tmpIdxTable; } std::unique_ptr<char[]> dataTable = std::make_unique<char[]>(result->GetRowCount() * _recordSize); std::unique_ptr<uint32[]> newIndexes = std::make_unique<uint32[]>(result->GetRowCount()); uint32 newRecords = 0; // Insert sql data into the data array do { Field* fields = result->Fetch(); uint32 indexValue = fields[_sqlIndexPos].Get<uint32>(); char* dataValue = indexTable[indexValue]; // If exist in DBC file override from DB newIndexes[newRecords] = indexValue; dataValue = &dataTable[newRecords++ * _recordSize]; uint32 dataOffset = 0; uint32 sqlColumnNumber = 0; char const* dbcFormat = _dbcFormat; for (; (*dbcFormat); ++dbcFormat) { switch (*dbcFormat) { case FT_FLOAT: *reinterpret_cast<float*>(&dataValue[dataOffset]) = fields[sqlColumnNumber].Get<float>(); dataOffset += sizeof(float); break; case FT_IND: case FT_INT: *reinterpret_cast<uint32*>(&dataValue[dataOffset]) = fields[sqlColumnNumber].Get<uint32>(); dataOffset += sizeof(uint32); break; case FT_BYTE: *reinterpret_cast<uint8*>(&dataValue[dataOffset]) = fields[sqlColumnNumber].Get<uint8>(); dataOffset += sizeof(uint8); break; case FT_STRING: *reinterpret_cast<char**>(&dataValue[dataOffset]) = CloneStringToPool(fields[sqlColumnNumber].Get<std::string>()); dataOffset += sizeof(char*); break; case FT_SORT: case FT_NA: break; default: ASSERT(false, "Unsupported data type '%c' in table '{}'", *dbcFormat, _sqlTableName); return nullptr; } ++sqlColumnNumber; } ASSERT(sqlColumnNumber == result->GetFieldCount(), "SQL format string does not match database for table: '{}'", _sqlTableName); ASSERT(dataOffset == _recordSize); } while (result->NextRow()); ASSERT(newRecords == result->GetRowCount()); // insert new records to index table for (uint32 i = 0; i < newRecords; ++i) indexTable[newIndexes[i]] = &dataTable[i * _recordSize]; records = indexTableSize; return dataTable.release(); } char* DBCDatabaseLoader::CloneStringToPool(std::string const& str) { char* buf = new char[str.size() + 1]; memcpy(buf, str.c_str(), str.size() + 1); _stringPool.push_back(buf); return buf; } <commit_msg>fix(Core/DBCLoader): Add handler for possibly unused DBC format data type (#13045)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "DBCDatabaseLoader.h" #include "DatabaseEnv.h" #include "Errors.h" #include "StringFormat.h" DBCDatabaseLoader::DBCDatabaseLoader(char const* tableName, char const* dbcFormatString, std::vector<char*>& stringPool) : _sqlTableName(tableName), _dbcFormat(dbcFormatString), _sqlIndexPos(0), _recordSize(0), _stringPool(stringPool) { // Get sql index position int32 indexPos = -1; _recordSize = DBCFileLoader::GetFormatRecordSize(_dbcFormat, &indexPos); ASSERT(_recordSize); } char* DBCDatabaseLoader::Load(uint32& records, char**& indexTable) { std::string query = Acore::StringFormat("SELECT * FROM `%s` ORDER BY `ID` DESC", _sqlTableName); // no error if empty set QueryResult result = WorldDatabase.Query(query.c_str()); if (!result) return nullptr; // Check if sql index pos is valid if (int32(result->GetFieldCount() - 1) < _sqlIndexPos) { ASSERT(false, "Invalid index pos for dbc: '{}'", _sqlTableName); return nullptr; } // Resize index table // database query *MUST* contain ORDER BY `index_field` DESC clause uint32 indexTableSize = std::max(records, (*result)[_sqlIndexPos].Get<uint32>() + 1); if (indexTableSize > records) { char** tmpIdxTable = new char* [indexTableSize]; memset(tmpIdxTable, 0, indexTableSize * sizeof(char*)); memcpy(tmpIdxTable, indexTable, records * sizeof(char*)); delete[] indexTable; indexTable = tmpIdxTable; } std::unique_ptr<char[]> dataTable = std::make_unique<char[]>(result->GetRowCount() * _recordSize); std::unique_ptr<uint32[]> newIndexes = std::make_unique<uint32[]>(result->GetRowCount()); uint32 newRecords = 0; // Insert sql data into the data array do { Field* fields = result->Fetch(); uint32 indexValue = fields[_sqlIndexPos].Get<uint32>(); char* dataValue = indexTable[indexValue]; // If exist in DBC file override from DB newIndexes[newRecords] = indexValue; dataValue = &dataTable[newRecords++ * _recordSize]; uint32 dataOffset = 0; uint32 sqlColumnNumber = 0; char const* dbcFormat = _dbcFormat; for (; (*dbcFormat); ++dbcFormat) { switch (*dbcFormat) { case FT_FLOAT: *reinterpret_cast<float*>(&dataValue[dataOffset]) = fields[sqlColumnNumber].Get<float>(); dataOffset += sizeof(float); break; case FT_IND: case FT_INT: *reinterpret_cast<uint32*>(&dataValue[dataOffset]) = fields[sqlColumnNumber].Get<uint32>(); dataOffset += sizeof(uint32); break; case FT_BYTE: *reinterpret_cast<uint8*>(&dataValue[dataOffset]) = fields[sqlColumnNumber].Get<uint8>(); dataOffset += sizeof(uint8); break; case FT_STRING: *reinterpret_cast<char**>(&dataValue[dataOffset]) = CloneStringToPool(fields[sqlColumnNumber].Get<std::string>()); dataOffset += sizeof(char*); break; case FT_SORT: case FT_NA: case FT_NA_BYTE: break; default: ASSERT(false, "Unsupported data type '{}' in table '{}'", *dbcFormat, _sqlTableName); return nullptr; } ++sqlColumnNumber; } ASSERT(sqlColumnNumber == result->GetFieldCount(), "SQL format string does not match database for table: '{}'", _sqlTableName); ASSERT(dataOffset == _recordSize); } while (result->NextRow()); ASSERT(newRecords == result->GetRowCount()); // insert new records to index table for (uint32 i = 0; i < newRecords; ++i) indexTable[newIndexes[i]] = &dataTable[i * _recordSize]; records = indexTableSize; return dataTable.release(); } char* DBCDatabaseLoader::CloneStringToPool(std::string const& str) { char* buf = new char[str.size() + 1]; memcpy(buf, str.c_str(), str.size() + 1); _stringPool.push_back(buf); return buf; } <|endoftext|>
<commit_before>#include <vector> #include <string> #include "boost/program_options.hpp" #include "boost/lexical_cast.hpp" #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-condition-variable.h" #include "vtrc-mutex.h" #include "vtrc-bind.h" #include "vtrc-ref.h" #include "lukki-db-iface.h" #include "protocol/lukkidb.pb.h" #include "vtrc-chrono.h" namespace po = boost::program_options; using namespace vtrc; struct work_time { typedef vtrc::chrono::high_resolution_clock::time_point time_point; time_point start_; time_point total_; work_time( ) :start_(vtrc::chrono::high_resolution_clock::now( )) ,total_(start_) { } void print_point( const std::string &name ) { time_point now(vtrc::chrono::high_resolution_clock::now( )); time_point::duration stop( now - start_); std::cout << "[" << name << "]"<< " call time: '" << stop << "' total: '" << (now - total_) << "'\n"; start_ = vtrc::chrono::high_resolution_clock::now( ); } ~work_time( ) { } }; void get_options( po::options_description& desc ) { desc.add_options( ) ("help,?", "help message") ("server,s", po::value<std::string>( ), "server name; <tcp address>:<port> or <pipe/file name>") ( "stat,I", "get db status") ( "set,S", po::value<std::string>( ), "set value; " "use --value options for values") ( "del,D", po::value<std::string>( ), "delete value") ( "upd,U", po::value<std::string>( ), "update value if it exist; " "use --value options for values") ( "get,G", po::value<std::string>( ), "get value") ( "value,V", po::value<std::vector< std::string> >( ), "values for " " set or upd commands;" " -V \"value1\", -V \"value2\", -V \"value3\" ...") ; } void connect_to( client::vtrc_client_sptr client, std::string const &name ) { std::vector<std::string> params; size_t delim_pos = name.find_last_of( ':' ); if( delim_pos == std::string::npos ) { /// local: <localname> params.push_back( name ); } else { /// tcp: <addres>:<port> params.push_back( std::string( name.begin( ), name.begin( ) + delim_pos ) ); params.push_back( std::string( name.begin( ) + delim_pos + 1, name.end( ) ) ); } if( params.size( ) == 1 ) { /// local name client->connect( params[0] ); } else if( params.size( ) == 2 ) { /// tcp client->connect( params[0], boost::lexical_cast<unsigned short>(params[1])); } } void on_client_ready( vtrc::condition_variable &cond ) { std::cout << "Connection is ready...\n"; cond.notify_all( ); } int start( const po::variables_map &params ) { if( params.count( "server" ) == 0 ) { throw std::runtime_error("Server is not defined;\n" "Use --help for details"); } /// will use only one thread for io operations. /// because we don't have callbacks or events from server-side common::pool_pair pp( 1 ); std::cout << "Creating client ... " ; client::vtrc_client_sptr client = client::vtrc_client::create( pp ); /// connect slot to 'on_ready' vtrc::condition_variable ready_cond; client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); std::cout << "Ok\n"; connect_to( client, params["server"].as<std::string>( ) ); std::cout << "Connected to " << params["server"].as<std::string>( ) << "\n"; vtrc::mutex ready_mutex; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &client::vtrc_client::ready, client ) ); vtrc::shared_ptr<interfaces::luki_db> impl (interfaces::create_lukki_db(client)); std::vector<std::string> values; if( params.count( "value" ) ) { values = params["value"].as< std::vector<std::string> >( ); } if( params.count( "set" ) ) { std::string name(params["set"].as<std::string>( )); std::cout << "Set '" << name << "' to " << values.size( ) << " values...\n"; work_time wt; impl->set( name, values ); wt.print_point( "set" ); std::cout << "Ok\n"; } else if( params.count( "upd" ) ) { std::string name(params["upd"].as<std::string>( )); std::cout << "Update '" << name << "' to " << values.size( ) << " values...\n"; work_time wt; impl->upd( name, values ); wt.print_point( "update" ); std::cout << "Ok\n"; } else if( params.count( "get" ) ) { std::string name(params["get"].as<std::string>( )); std::cout << "Get '" << name << "'...\n"; work_time wt; std::vector<std::string> vals(impl->get( name )); wt.print_point( "get" ); std::cout << "Ok\n"; std::cout << "got " << vals.size( ) << " value" << (vals.size( ) == 1 ? "" : "s") << "\n==========\n"; std::copy( vals.begin( ), vals.end( ), std::ostream_iterator<std::string>( std::cout, "\n" ) ); std::cout << "==========\n"; } else if( params.count( "del" ) ) { std::string name(params["del"].as<std::string>( )); std::cout << "Delete '" << name << "'...\n"; work_time wt; impl->del( name ); std::cout << "Ok\n"; wt.print_point( "delete" ); } if( params.count( "stat" ) ) { std::cout << "Get db stat\n"; work_time wt; vtrc_example::db_stat s(impl->stat( )); std::cout << "Ok\n"; wt.print_point( "stat" ); std::cout << "Stat:\n" << "\tRecords: \t" << s.total_records( ) << "\n" << "\t'set': \t\t" << s.set_requests( ) << "\n" << "\t'upd': \t\t" << s.upd_requests( ) << "\n" << "\t'get': \t\t" << s.get_requests( ) << "\n" << "\t'del': \t\t" << s.del_requests( ) << "\n" ; } pp.stop_all( ); pp.join_all( ); return 0; } <commit_msg>fs examples. lukki-db<commit_after>#include <vector> #include <string> #include "boost/program_options.hpp" #include "boost/lexical_cast.hpp" #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-condition-variable.h" #include "vtrc-mutex.h" #include "vtrc-bind.h" #include "vtrc-ref.h" #include "lukki-db-iface.h" #include "protocol/lukkidb.pb.h" #include "vtrc-chrono.h" namespace po = boost::program_options; using namespace vtrc; struct work_time { typedef vtrc::chrono::high_resolution_clock::time_point time_point; time_point start_; time_point total_; work_time( ) :start_(vtrc::chrono::high_resolution_clock::now( )) ,total_(start_) { } void print_point( const std::string &name ) { time_point now(vtrc::chrono::high_resolution_clock::now( )); time_point::duration stop( now - start_); std::cout << "[" << name << "]"<< " call time: '" << stop << "' total: '" << (now - total_) << "'\n"; start_ = vtrc::chrono::high_resolution_clock::now( ); } ~work_time( ) { } }; void get_options( po::options_description& desc ) { desc.add_options( ) ("help,?", "help message") ("server,s", po::value<std::string>( ), "server name; <tcp address>:<port> or <pipe/file name>") ( "stat,I", "get db status") ( "set,S", po::value<std::string>( ), "set value; " "use --value options for values") ( "del,D", po::value<std::string>( ), "delete value") ( "upd,U", po::value<std::string>( ), "update value if it exist; " "use --value options for values") ( "get,G", po::value<std::string>( ), "get value") ( "value,V", po::value<std::vector< std::string> >( ), "values for " " set or upd commands;" " -V \"value1\", -V \"value2\", -V \"value3\" ...") ; } void connect_to( client::vtrc_client_sptr client, std::string const &name ) { std::vector<std::string> params; size_t delim_pos = name.find_last_of( ':' ); if( delim_pos == std::string::npos ) { /// local: <localname> params.push_back( name ); } else { /// tcp: <addres>:<port> params.push_back( std::string( name.begin( ), name.begin( ) + delim_pos ) ); params.push_back( std::string( name.begin( ) + delim_pos + 1, name.end( ) ) ); } if( params.size( ) == 1 ) { /// local name client->connect( params[0] ); } else if( params.size( ) == 2 ) { /// tcp client->connect( params[0], boost::lexical_cast<unsigned short>(params[1])); } } void on_client_ready( vtrc::condition_variable &cond ) { std::cout << "Connection is ready...\n"; cond.notify_all( ); } int start( const po::variables_map &params ) { if( params.count( "server" ) == 0 ) { throw std::runtime_error("Server is not defined;\n" "Use --help for details"); } /// will use only one thread for io operations. /// because we don't have callbacks or events from server-side common::pool_pair pp( 1 ); std::cout << "Creating client ... " ; client::vtrc_client_sptr client = client::vtrc_client::create( pp ); /// connect slot to 'on_ready' vtrc::condition_variable ready_cond; client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); std::cout << "Ok\n"; connect_to( client, params["server"].as<std::string>( ) ); std::cout << "Connected to " << params["server"].as<std::string>( ) << "\n"; vtrc::mutex ready_mutex; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &client::vtrc_client::ready, client ) ); vtrc::shared_ptr<interfaces::luki_db> impl (interfaces::create_lukki_db(client)); std::vector<std::string> values; if( params.count( "value" ) ) { values = params["value"].as< std::vector<std::string> >( ); } if( params.count( "set" ) ) { std::string name(params["set"].as<std::string>( )); std::cout << "Set '" << name << "' to " << values.size( ) << " values...\n"; work_time wt; impl->set( name, values ); wt.print_point( "set" ); std::cout << "Ok\n"; } else if( params.count( "upd" ) ) { std::string name(params["upd"].as<std::string>( )); std::cout << "Update '" << name << "' to " << values.size( ) << " values...\n"; work_time wt; impl->upd( name, values ); wt.print_point( "update" ); std::cout << "Ok\n"; } else if( params.count( "get" ) ) { std::string name(params["get"].as<std::string>( )); std::cout << "Get '" << name << "'...\n"; work_time wt; std::vector<std::string> vals(impl->get( name )); wt.print_point( "get" ); std::cout << "Ok\n"; std::cout << "got " << vals.size( ) << " value" << (vals.size( ) == 1 ? "" : "s") << "\n==========\n"; std::copy( vals.begin( ), vals.end( ), std::ostream_iterator<std::string>( std::cout, "\n" ) ); std::cout << "==========\n"; } else if( params.count( "del" ) ) { std::string name(params["del"].as<std::string>( )); std::cout << "Delete '" << name << "'...\n"; work_time wt; impl->del( name ); wt.print_point( "delete" ); std::cout << "Ok\n"; } if( params.count( "stat" ) ) { std::cout << "Get db stat\n"; work_time wt; vtrc_example::db_stat s(impl->stat( )); std::cout << "Ok\n"; wt.print_point( "stat" ); std::cout << "Stat:\n" << "\tRecords: \t" << s.total_records( ) << "\n" << "\t'set': \t\t" << s.set_requests( ) << "\n" << "\t'upd': \t\t" << s.upd_requests( ) << "\n" << "\t'get': \t\t" << s.get_requests( ) << "\n" << "\t'del': \t\t" << s.del_requests( ) << "\n" ; } pp.stop_all( ); pp.join_all( ); return 0; } <|endoftext|>
<commit_before>/** \file RoboteqDevice.cpp * \version 080411 * \date 2011 * * \brief class for RoboteqDevice servo driver * (C) Roboteq Inc., 2012 */ #include <iostream> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <time.h> #include <sstream> #include "guardian_node/RoboteqDevice.h" #include "guardian_node/ErrorCodes.h" using namespace std; #define BUFFER_SIZE 1024 #define MISSING_VALUE -1024 RoboteqDevice::RoboteqDevice() { handle = RQ_INVALID_HANDLE; } RoboteqDevice::~RoboteqDevice() { Disconnect(); } bool RoboteqDevice::IsConnected() { return handle != RQ_INVALID_HANDLE; } int RoboteqDevice::Connect(string port) { if(IsConnected()) { cout<<"RoboteqDevice::Connect: Device is connected, attempting to disconnect."<<endl; Disconnect(); } //Open port. cout<<"RoboteqDevice::Connect: Opening port '"<<port<<"'..."; handle = open(port.c_str(), O_RDWR |O_NOCTTY | O_NDELAY); // Original //handle = open(port.c_str(), O_RDWR |O_NOCTTY); // Adapted by Robotnik if(handle == RQ_INVALID_HANDLE) { cout<<"failed."<<endl; return RQ_ERR_OPEN_PORT; } cout<<"...succeeded."<<endl; fcntl (handle, F_SETFL, O_APPEND | O_NONBLOCK); //original cout<<"RoboteqDevice::Connect: Initializing port..."; InitPort(); cout<<"...done."<<endl; int status; string response; cout<<"Detecting device version..."; status = IssueCommand("?", "$1E", 10, response); if(status != RQ_SUCCESS) { cout<<"RoboteqDevice::Connect: failed (issue ?$1E response: "<<status<<")."<<endl; Disconnect(); return RQ_UNRECOGNIZED_DEVICE; } if(response.length() < 12) { cout<<"RoboteqDevice::Connect: failed (unrecognized version)."<<endl; Disconnect(); return RQ_UNRECOGNIZED_VERSION; } cout<<response.substr(8, 4)<<"."<<endl; return RQ_SUCCESS; } void RoboteqDevice::Disconnect() { if(!IsConnected()) close(handle); handle = RQ_INVALID_HANDLE; } void RoboteqDevice::InitPort() { if(!IsConnected()) return; //Get the existing Comm Port Attributes in cwrget struct termios newtio; tcgetattr (handle, &newtio); //Set the Tx and Rx Baud Rate to 9600 if(cfsetospeed (&newtio, B115200) < 0) cout << "RoboteqDevice::InitPort: Error in cfsetospeed " << endl; if(cfsetispeed (&newtio, B115200) < 0) cout << "RoboteqDevice::InitPort: Error in cfsetispeed " << endl; newtio.c_cflag |= CLOCAL | CREAD; newtio.c_cflag &= ~HUPCL; //parity = NONE newtio.c_cflag &= ~PARENB; newtio.c_cflag &= ~PARODD; newtio.c_cflag &= ~CSTOPB;// 1 Stop bit newtio.c_cflag &= ~CSIZE; newtio.c_cflag |= CS8; newtio.c_cflag &= ~CRTSCTS; //Disables hardware flow control newtio.c_iflag |= IGNBRK; newtio.c_iflag &= ~ICRNL; newtio.c_iflag &= ~IXON; newtio.c_oflag &= ~OPOST; newtio.c_oflag &= ~ONLCR; newtio.c_lflag &= ~ISIG; newtio.c_lflag &= ~IEXTEN; newtio.c_lflag &= ~ECHOK; newtio.c_lflag &= ~ECHOCTL; newtio.c_lflag &= ~ECHOKE; newtio.c_lflag &= ~ECHO; newtio.c_lflag &= ~ECHOE; // // Entrada canónica-> La entrada canónica es orientada a línea. Los caracteres se meten en un buffer hasta recibir un CR o LF. newtio.c_lflag &= ~ICANON; // carácteres de control //options.c_cc[VMIN] = (cc_t)1; newtio.c_cc[VMIN] = (cc_t)1; newtio.c_cc[VTIME] = (cc_t)5; tcflush(handle, TCIFLUSH); //Enable the Receiver and Set local Mode //newtio.c_iflag = IGNBRK; /* Ignore Break Condition & no processing under input options*/ //newtio.c_lflag = 0; /* Select the RAW Input Mode through Local options*/ //newtio.c_oflag = 0; /* Select the RAW Output Mode through Local options*/ //newtio.c_cflag |= (CLOCAL | CREAD); /* Select the Local Mode & Enable Receiver through Control options*/ /// TEST //newtio.c_cflag &= ~HUPCL; //Set Data format to 7E1 //newtio.c_cflag &= ~CSIZE; /* Mask the Character Size Bits through Control options*/ //newtio.c_cflag |= CS7; /* Select Character Size to 7-Bits through Control options*/ //newtio.c_cflag |= PARENB; /* Select the Parity Enable through Control options*/ //newtio.c_cflag &= ~PARODD; /* Select the Even Parity through Control options*/ /// TEST //newtio.c_cflag &= ~CSTOPB;// 1 Stop bit //cwrset.c_iflag |= (INPCK|ISTRIP); //cwrset.c_cc[VMIN] = 6; /// TEST //newtio.c_cc[VMIN] = (cc_t)1; //newtio.c_cc[VTIME] = (cc_t)5; /// TEST //Set the New Comm Port Attributes through cwrset //tcsetattr (fd0, TCSANOW, &newtio); /* Set the attribute NOW without waiting for Data to Complete*/ /// TEST tcsetattr (handle, TCSANOW, &newtio); fcntl(handle,F_SETFL, FNDELAY); } int RoboteqDevice::Write(string str) { if(!IsConnected()) return RQ_ERR_NOT_CONNECTED; //cout<<"Writing: "<<ReplaceString(str, "\r", "\r\n"); int countSent = write(handle, str.c_str(), str.length()); //Verify weather the Transmitting Data on UART was Successful or Not if(countSent < 0) return RQ_ERR_TRANSMIT_FAILED; return RQ_SUCCESS; } int RoboteqDevice::ReadAll(string &str) { int countRcv; if(!IsConnected()) return RQ_ERR_NOT_CONNECTED; char buf[BUFFER_SIZE + 1] = ""; str = ""; int i = 0; while((countRcv = read(handle, buf, BUFFER_SIZE)) > 0) { str.append(buf, countRcv); //No further data. if(countRcv < BUFFER_SIZE) break; } if(countRcv < 0) { if(errno == EAGAIN) return RQ_ERR_SERIAL_IO; else return RQ_ERR_SERIAL_RECEIVE; } return RQ_SUCCESS; } int RoboteqDevice::IssueCommand(string commandType, string command, string args, int waitms, string &response, bool isplusminus) { int status; string read; response = ""; if(args == "") status = Write(commandType + command + "\r"); else status = Write(commandType + command + " " + args + "\r"); if(status != RQ_SUCCESS) { cout << "RoboteqDevice::IssueCommand: error Writing" << endl; return status; } usleep(waitms * 1000l); status = ReadAll(read); if(status != RQ_SUCCESS) { cout << "RoboteqDevice::IssueCommand: error Reading status = " << status << endl; return status; } if(isplusminus) { if(read.length() < 2) return RQ_INVALID_RESPONSE; response = read.substr(read.length() - 2, 1); return RQ_SUCCESS; } string::size_type pos = read.rfind(command + "="); if(pos == string::npos) return RQ_INVALID_RESPONSE; pos += command.length() + 1; string::size_type carriage = read.find("\r", pos); if(carriage == string::npos) return RQ_INVALID_RESPONSE; response = read.substr(pos, carriage - pos); return RQ_SUCCESS; } int RoboteqDevice::IssueCommand(string commandType, string command, int waitms, string &response, bool isplusminus) { return IssueCommand(commandType, command, "", waitms, response, isplusminus); } int RoboteqDevice::SetConfig(int configItem, int index, int value) { string response; char command[10]; char args[50]; if(configItem < 0 || configItem > 255) return RQ_INVALID_CONFIG_ITEM; sprintf(command, "$%02X", configItem); sprintf(args, "%i %i", index, value); if(index == MISSING_VALUE) { sprintf(args, "%i", value); index = 0; } if(index < 0) return RQ_INDEX_OUT_RANGE; int status = IssueCommand("^", command, args, 10, response, true); if(status != RQ_SUCCESS) return status; if(response != "+") return RQ_SET_CONFIG_FAILED; return RQ_SUCCESS; } int RoboteqDevice::SetConfig(int configItem, int value) { return SetConfig(configItem, MISSING_VALUE, value); } int RoboteqDevice::SetCommand(int commandItem, int index, int value) { string response; char command[10]; char args[50]; if(commandItem < 0 || commandItem > 255) return RQ_INVALID_COMMAND_ITEM; sprintf(command, "$%02X", commandItem); sprintf(args, "%i %i", index, value); if(index == MISSING_VALUE) { if(value != MISSING_VALUE) sprintf(args, "%i", value); index = 0; } if(index < 0) return RQ_INDEX_OUT_RANGE; int status = IssueCommand("!", command, args, 10, response, true); if(status != RQ_SUCCESS) return status; if(response != "+") return RQ_SET_COMMAND_FAILED; return RQ_SUCCESS; } int RoboteqDevice::SetCommand(int commandItem, int value) { return SetCommand(commandItem, MISSING_VALUE, value); } int RoboteqDevice::SetCommand(int commandItem) { return SetCommand(commandItem, MISSING_VALUE, MISSING_VALUE); } int RoboteqDevice::GetConfig(int configItem, int index, int &result) { string response; char command[10]; char args[50]; if(configItem < 0 || configItem > 255) return RQ_INVALID_CONFIG_ITEM; if(index < 0) return RQ_INDEX_OUT_RANGE; sprintf(command, "$%02X", configItem); sprintf(args, "%i", index); int status = IssueCommand("~", command, args, 10, response); if(status != RQ_SUCCESS) return status; istringstream iss(response); iss>>result; if(iss.fail()) return RQ_GET_CONFIG_FAILED; return RQ_SUCCESS; } int RoboteqDevice::GetConfig(int configItem, int &result) { return GetConfig(configItem, 0, result); } int RoboteqDevice::GetValue(int operatingItem, int index, int &result) { string response; char command[10]; char args[50]; if(operatingItem < 0 || operatingItem > 255) return RQ_INVALID_OPER_ITEM; if(index < 0) return RQ_INDEX_OUT_RANGE; sprintf(command, "$%02X", operatingItem); sprintf(args, "%i", index); int status = IssueCommand("?", command, args, 10, response); if(status != RQ_SUCCESS) return status; istringstream iss(response); iss>>result; if(iss.fail()) return RQ_GET_VALUE_FAILED; return RQ_SUCCESS; } int RoboteqDevice::GetValue(int operatingItem, int &result) { return GetValue(operatingItem, 0, result); } string ReplaceString(string source, string find, string replacement) { string::size_type pos = 0; while((pos = source.find(find, pos)) != string::npos) { source.replace(pos, find.size(), replacement); pos++; } return source; } void sleepms(int milliseconds) { usleep(milliseconds / 1000); } <commit_msg>guardian_node: fixing compilation error in Ubuntu 14.04<commit_after>/** \file RoboteqDevice.cpp * \version 080411 * \date 2011 * * \brief class for RoboteqDevice servo driver * (C) Roboteq Inc., 2012 */ #include <iostream> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <time.h> #include <sstream> #include <unistd.h> #include "guardian_node/RoboteqDevice.h" #include "guardian_node/ErrorCodes.h" using namespace std; #define BUFFER_SIZE 1024 #define MISSING_VALUE -1024 RoboteqDevice::RoboteqDevice() { handle = RQ_INVALID_HANDLE; } RoboteqDevice::~RoboteqDevice() { Disconnect(); } bool RoboteqDevice::IsConnected() { return handle != RQ_INVALID_HANDLE; } int RoboteqDevice::Connect(string port) { if(IsConnected()) { cout<<"RoboteqDevice::Connect: Device is connected, attempting to disconnect."<<endl; Disconnect(); } //Open port. cout<<"RoboteqDevice::Connect: Opening port '"<<port<<"'..."; handle = open(port.c_str(), O_RDWR |O_NOCTTY | O_NDELAY); // Original //handle = open(port.c_str(), O_RDWR |O_NOCTTY); // Adapted by Robotnik if(handle == RQ_INVALID_HANDLE) { cout<<"failed."<<endl; return RQ_ERR_OPEN_PORT; } cout<<"...succeeded."<<endl; fcntl (handle, F_SETFL, O_APPEND | O_NONBLOCK); //original cout<<"RoboteqDevice::Connect: Initializing port..."; InitPort(); cout<<"...done."<<endl; int status; string response; cout<<"Detecting device version..."; status = IssueCommand("?", "$1E", 10, response); if(status != RQ_SUCCESS) { cout<<"RoboteqDevice::Connect: failed (issue ?$1E response: "<<status<<")."<<endl; Disconnect(); return RQ_UNRECOGNIZED_DEVICE; } if(response.length() < 12) { cout<<"RoboteqDevice::Connect: failed (unrecognized version)."<<endl; Disconnect(); return RQ_UNRECOGNIZED_VERSION; } cout<<response.substr(8, 4)<<"."<<endl; return RQ_SUCCESS; } void RoboteqDevice::Disconnect() { if(!IsConnected()) close(handle); handle = RQ_INVALID_HANDLE; } void RoboteqDevice::InitPort() { if(!IsConnected()) return; //Get the existing Comm Port Attributes in cwrget struct termios newtio; tcgetattr (handle, &newtio); //Set the Tx and Rx Baud Rate to 9600 if(cfsetospeed (&newtio, B115200) < 0) cout << "RoboteqDevice::InitPort: Error in cfsetospeed " << endl; if(cfsetispeed (&newtio, B115200) < 0) cout << "RoboteqDevice::InitPort: Error in cfsetispeed " << endl; newtio.c_cflag |= CLOCAL | CREAD; newtio.c_cflag &= ~HUPCL; //parity = NONE newtio.c_cflag &= ~PARENB; newtio.c_cflag &= ~PARODD; newtio.c_cflag &= ~CSTOPB;// 1 Stop bit newtio.c_cflag &= ~CSIZE; newtio.c_cflag |= CS8; newtio.c_cflag &= ~CRTSCTS; //Disables hardware flow control newtio.c_iflag |= IGNBRK; newtio.c_iflag &= ~ICRNL; newtio.c_iflag &= ~IXON; newtio.c_oflag &= ~OPOST; newtio.c_oflag &= ~ONLCR; newtio.c_lflag &= ~ISIG; newtio.c_lflag &= ~IEXTEN; newtio.c_lflag &= ~ECHOK; newtio.c_lflag &= ~ECHOCTL; newtio.c_lflag &= ~ECHOKE; newtio.c_lflag &= ~ECHO; newtio.c_lflag &= ~ECHOE; // // Entrada canónica-> La entrada canónica es orientada a línea. Los caracteres se meten en un buffer hasta recibir un CR o LF. newtio.c_lflag &= ~ICANON; // carácteres de control //options.c_cc[VMIN] = (cc_t)1; newtio.c_cc[VMIN] = (cc_t)1; newtio.c_cc[VTIME] = (cc_t)5; tcflush(handle, TCIFLUSH); //Enable the Receiver and Set local Mode //newtio.c_iflag = IGNBRK; /* Ignore Break Condition & no processing under input options*/ //newtio.c_lflag = 0; /* Select the RAW Input Mode through Local options*/ //newtio.c_oflag = 0; /* Select the RAW Output Mode through Local options*/ //newtio.c_cflag |= (CLOCAL | CREAD); /* Select the Local Mode & Enable Receiver through Control options*/ /// TEST //newtio.c_cflag &= ~HUPCL; //Set Data format to 7E1 //newtio.c_cflag &= ~CSIZE; /* Mask the Character Size Bits through Control options*/ //newtio.c_cflag |= CS7; /* Select Character Size to 7-Bits through Control options*/ //newtio.c_cflag |= PARENB; /* Select the Parity Enable through Control options*/ //newtio.c_cflag &= ~PARODD; /* Select the Even Parity through Control options*/ /// TEST //newtio.c_cflag &= ~CSTOPB;// 1 Stop bit //cwrset.c_iflag |= (INPCK|ISTRIP); //cwrset.c_cc[VMIN] = 6; /// TEST //newtio.c_cc[VMIN] = (cc_t)1; //newtio.c_cc[VTIME] = (cc_t)5; /// TEST //Set the New Comm Port Attributes through cwrset //tcsetattr (fd0, TCSANOW, &newtio); /* Set the attribute NOW without waiting for Data to Complete*/ /// TEST tcsetattr (handle, TCSANOW, &newtio); fcntl(handle,F_SETFL, FNDELAY); } int RoboteqDevice::Write(string str) { if(!IsConnected()) return RQ_ERR_NOT_CONNECTED; //cout<<"Writing: "<<ReplaceString(str, "\r", "\r\n"); int countSent = write(handle, str.c_str(), str.length()); //Verify weather the Transmitting Data on UART was Successful or Not if(countSent < 0) return RQ_ERR_TRANSMIT_FAILED; return RQ_SUCCESS; } int RoboteqDevice::ReadAll(string &str) { int countRcv; if(!IsConnected()) return RQ_ERR_NOT_CONNECTED; char buf[BUFFER_SIZE + 1] = ""; str = ""; int i = 0; while((countRcv = read(handle, buf, BUFFER_SIZE)) > 0) { str.append(buf, countRcv); //No further data. if(countRcv < BUFFER_SIZE) break; } if(countRcv < 0) { if(errno == EAGAIN) return RQ_ERR_SERIAL_IO; else return RQ_ERR_SERIAL_RECEIVE; } return RQ_SUCCESS; } int RoboteqDevice::IssueCommand(string commandType, string command, string args, int waitms, string &response, bool isplusminus) { int status; string read; response = ""; if(args == "") status = Write(commandType + command + "\r"); else status = Write(commandType + command + " " + args + "\r"); if(status != RQ_SUCCESS) { cout << "RoboteqDevice::IssueCommand: error Writing" << endl; return status; } usleep(waitms * 1000l); status = ReadAll(read); if(status != RQ_SUCCESS) { cout << "RoboteqDevice::IssueCommand: error Reading status = " << status << endl; return status; } if(isplusminus) { if(read.length() < 2) return RQ_INVALID_RESPONSE; response = read.substr(read.length() - 2, 1); return RQ_SUCCESS; } string::size_type pos = read.rfind(command + "="); if(pos == string::npos) return RQ_INVALID_RESPONSE; pos += command.length() + 1; string::size_type carriage = read.find("\r", pos); if(carriage == string::npos) return RQ_INVALID_RESPONSE; response = read.substr(pos, carriage - pos); return RQ_SUCCESS; } int RoboteqDevice::IssueCommand(string commandType, string command, int waitms, string &response, bool isplusminus) { return IssueCommand(commandType, command, "", waitms, response, isplusminus); } int RoboteqDevice::SetConfig(int configItem, int index, int value) { string response; char command[10]; char args[50]; if(configItem < 0 || configItem > 255) return RQ_INVALID_CONFIG_ITEM; sprintf(command, "$%02X", configItem); sprintf(args, "%i %i", index, value); if(index == MISSING_VALUE) { sprintf(args, "%i", value); index = 0; } if(index < 0) return RQ_INDEX_OUT_RANGE; int status = IssueCommand("^", command, args, 10, response, true); if(status != RQ_SUCCESS) return status; if(response != "+") return RQ_SET_CONFIG_FAILED; return RQ_SUCCESS; } int RoboteqDevice::SetConfig(int configItem, int value) { return SetConfig(configItem, MISSING_VALUE, value); } int RoboteqDevice::SetCommand(int commandItem, int index, int value) { string response; char command[10]; char args[50]; if(commandItem < 0 || commandItem > 255) return RQ_INVALID_COMMAND_ITEM; sprintf(command, "$%02X", commandItem); sprintf(args, "%i %i", index, value); if(index == MISSING_VALUE) { if(value != MISSING_VALUE) sprintf(args, "%i", value); index = 0; } if(index < 0) return RQ_INDEX_OUT_RANGE; int status = IssueCommand("!", command, args, 10, response, true); if(status != RQ_SUCCESS) return status; if(response != "+") return RQ_SET_COMMAND_FAILED; return RQ_SUCCESS; } int RoboteqDevice::SetCommand(int commandItem, int value) { return SetCommand(commandItem, MISSING_VALUE, value); } int RoboteqDevice::SetCommand(int commandItem) { return SetCommand(commandItem, MISSING_VALUE, MISSING_VALUE); } int RoboteqDevice::GetConfig(int configItem, int index, int &result) { string response; char command[10]; char args[50]; if(configItem < 0 || configItem > 255) return RQ_INVALID_CONFIG_ITEM; if(index < 0) return RQ_INDEX_OUT_RANGE; sprintf(command, "$%02X", configItem); sprintf(args, "%i", index); int status = IssueCommand("~", command, args, 10, response); if(status != RQ_SUCCESS) return status; istringstream iss(response); iss>>result; if(iss.fail()) return RQ_GET_CONFIG_FAILED; return RQ_SUCCESS; } int RoboteqDevice::GetConfig(int configItem, int &result) { return GetConfig(configItem, 0, result); } int RoboteqDevice::GetValue(int operatingItem, int index, int &result) { string response; char command[10]; char args[50]; if(operatingItem < 0 || operatingItem > 255) return RQ_INVALID_OPER_ITEM; if(index < 0) return RQ_INDEX_OUT_RANGE; sprintf(command, "$%02X", operatingItem); sprintf(args, "%i", index); int status = IssueCommand("?", command, args, 10, response); if(status != RQ_SUCCESS) return status; istringstream iss(response); iss>>result; if(iss.fail()) return RQ_GET_VALUE_FAILED; return RQ_SUCCESS; } int RoboteqDevice::GetValue(int operatingItem, int &result) { return GetValue(operatingItem, 0, result); } string ReplaceString(string source, string find, string replacement) { string::size_type pos = 0; while((pos = source.find(find, pos)) != string::npos) { source.replace(pos, find.size(), replacement); pos++; } return source; } void sleepms(int milliseconds) { usleep(milliseconds / 1000); } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018-19 David Shah <david@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include <algorithm> #include <iterator> #include <unordered_set> #include "cells.h" #include "design_utils.h" #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN // Pack LUTs and LUT-FF pairs static void pack_lut_lutffs(Context *ctx) { log_info("Packing LUT-FFs..\n"); std::unordered_set<IdString> packed_cells; std::vector<std::unique_ptr<CellInfo>> new_cells; for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (ctx->verbose) log_info("cell '%s' is of type '%s'\n", ci->name.c_str(ctx), ci->type.c_str(ctx)); if (is_lut(ctx, ci)) { std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), ci->name.str(ctx) + "_LC"); std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(packed->attrs, packed->attrs.begin())); packed_cells.insert(ci->name); if (ctx->verbose) log_info("packed cell %s into %s\n", ci->name.c_str(ctx), packed->name.c_str(ctx)); // See if we can pack into a DFF // TODO: LUT cascade NetInfo *o = ci->ports.at(ctx->id("Q")).net; CellInfo *dff = net_only_drives(ctx, o, is_ff, ctx->id("D"), true); auto lut_bel = ci->attrs.find(ctx->id("BEL")); bool packed_dff = false; if (dff) { if (ctx->verbose) log_info("found attached dff %s\n", dff->name.c_str(ctx)); auto dff_bel = dff->attrs.find(ctx->id("BEL")); if (lut_bel != ci->attrs.end() && dff_bel != dff->attrs.end() && lut_bel->second != dff_bel->second) { // Locations don't match, can't pack } else { lut_to_lc(ctx, ci, packed.get(), false); dff_to_lc(ctx, dff, packed.get(), false); ctx->nets.erase(o->name); if (dff_bel != dff->attrs.end()) packed->attrs[ctx->id("BEL")] = dff_bel->second; packed_cells.insert(dff->name); if (ctx->verbose) log_info("packed cell %s into %s\n", dff->name.c_str(ctx), packed->name.c_str(ctx)); packed_dff = true; } } if (!packed_dff) { lut_to_lc(ctx, ci, packed.get(), true); } new_cells.push_back(std::move(packed)); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Pack FFs not packed as LUTFFs static void pack_nonlut_ffs(Context *ctx) { log_info("Packing non-LUT FFs..\n"); std::unordered_set<IdString> packed_cells; std::vector<std::unique_ptr<CellInfo>> new_cells; for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (is_ff(ctx, ci)) { std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), ci->name.str(ctx) + "_DFFLC"); std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(packed->attrs, packed->attrs.begin())); if (ctx->verbose) log_info("packed cell %s into %s\n", ci->name.c_str(ctx), packed->name.c_str(ctx)); packed_cells.insert(ci->name); dff_to_lc(ctx, ci, packed.get(), true); new_cells.push_back(std::move(packed)); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } static bool net_is_constant(const Context *ctx, NetInfo *net, bool &value) { if (net == nullptr) return false; if (net->name == ctx->id("$PACKER_GND_NET") || net->name == ctx->id("$PACKER_VCC_NET")) { value = (net->name == ctx->id("$PACKER_VCC_NET")); return true; } else { return false; } } // Merge a net into a constant net static void set_net_constant(const Context *ctx, NetInfo *orig, NetInfo *constnet, bool constval) { orig->driver.cell = nullptr; for (auto user : orig->users) { if (user.cell != nullptr) { CellInfo *uc = user.cell; if (ctx->verbose) log_info("%s user %s\n", orig->name.c_str(ctx), uc->name.c_str(ctx)); if ((is_lut(ctx, uc) || is_lc(ctx, uc)) && (user.port.str(ctx).at(0) == 'I') && !constval) { uc->ports[user.port].net = nullptr; } else { uc->ports[user.port].net = constnet; constnet->users.push_back(user); } } } orig->users.clear(); } // Pack constants (simple implementation) static void pack_constants(Context *ctx) { log_info("Packing constants..\n"); std::unique_ptr<CellInfo> gnd_cell = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), "$PACKER_GND"); gnd_cell->params[ctx->id("INIT")] = 0; std::unique_ptr<NetInfo> gnd_net = std::unique_ptr<NetInfo>(new NetInfo); gnd_net->name = ctx->id("$PACKER_GND_NET"); gnd_net->driver.cell = gnd_cell.get(); gnd_net->driver.port = ctx->id("F"); gnd_cell->ports.at(ctx->id("F")).net = gnd_net.get(); std::unique_ptr<CellInfo> vcc_cell = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), "$PACKER_VCC"); // Fill with 1s vcc_cell->params[ctx->id("INIT")] = Property(Property::S1).extract(0, (1 << ctx->args.K), Property::S1); std::unique_ptr<NetInfo> vcc_net = std::unique_ptr<NetInfo>(new NetInfo); vcc_net->name = ctx->id("$PACKER_VCC_NET"); vcc_net->driver.cell = vcc_cell.get(); vcc_net->driver.port = ctx->id("F"); vcc_cell->ports.at(ctx->id("F")).net = vcc_net.get(); std::vector<IdString> dead_nets; bool gnd_used = false; for (auto net : sorted(ctx->nets)) { NetInfo *ni = net.second; if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id("GND")) { IdString drv_cell = ni->driver.cell->name; set_net_constant(ctx, ni, gnd_net.get(), false); gnd_used = true; dead_nets.push_back(net.first); ctx->cells.erase(drv_cell); } else if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id("VCC")) { IdString drv_cell = ni->driver.cell->name; set_net_constant(ctx, ni, vcc_net.get(), true); dead_nets.push_back(net.first); ctx->cells.erase(drv_cell); } } if (gnd_used) { ctx->cells[gnd_cell->name] = std::move(gnd_cell); ctx->nets[gnd_net->name] = std::move(gnd_net); } // Vcc cell always inserted for now, as it may be needed during carry legalisation (TODO: trim later if actually // never used?) ctx->cells[vcc_cell->name] = std::move(vcc_cell); ctx->nets[vcc_net->name] = std::move(vcc_net); for (auto dn : dead_nets) { ctx->nets.erase(dn); } } static bool is_nextpnr_iob(Context *ctx, CellInfo *cell) { return cell->type == ctx->id("$nextpnr_ibuf") || cell->type == ctx->id("$nextpnr_obuf") || cell->type == ctx->id("$nextpnr_iobuf"); } static bool is_generic_iob(const Context *ctx, const CellInfo *cell) { return cell->type == ctx->id("GENERIC_IOB"); } // Pack IO buffers static void pack_io(Context *ctx) { std::unordered_set<IdString> packed_cells; std::unordered_set<IdString> delete_nets; std::vector<std::unique_ptr<CellInfo>> new_cells; log_info("Packing IOs..\n"); for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (is_nextpnr_iob(ctx, ci)) { CellInfo *iob = nullptr; if (ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_iobuf")) { iob = net_only_drives(ctx, ci->ports.at(ctx->id("O")).net, is_generic_iob, ctx->id("PAD"), true, ci); } else if (ci->type == ctx->id("$nextpnr_obuf")) { NetInfo *net = ci->ports.at(ctx->id("I")).net; iob = net_only_drives(ctx, net, is_generic_iob, ctx->id("PAD"), true, ci); } if (iob != nullptr) { // Trivial case, GENERIC_IOB used. Just destroy the net and the // iobuf log_info("%s feeds GENERIC_IOB %s, removing %s %s.\n", ci->name.c_str(ctx), iob->name.c_str(ctx), ci->type.c_str(ctx), ci->name.c_str(ctx)); NetInfo *net = iob->ports.at(ctx->id("PAD")).net; if (((ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_iobuf")) && net->users.size() > 1) || (ci->type == ctx->id("$nextpnr_obuf") && (net->users.size() > 2 || net->driver.cell != nullptr))) log_error("PAD of %s '%s' connected to more than a single top level IO.\n", iob->type.c_str(ctx), iob->name.c_str(ctx)); if (net != nullptr) { delete_nets.insert(net->name); iob->ports.at(ctx->id("PAD")).net = nullptr; } if (ci->type == ctx->id("$nextpnr_iobuf")) { NetInfo *net2 = ci->ports.at(ctx->id("I")).net; if (net2 != nullptr) { delete_nets.insert(net2->name); } } } else if (bool_or_default(ctx->settings, ctx->id("disable_iobs"))) { // No IO buffer insertion; just remove nextpnr_[io]buf for (auto &p : ci->ports) disconnect_port(ctx, ci, p.first); } else { // Create a GENERIC_IOB buffer std::unique_ptr<CellInfo> ice_cell = create_generic_cell(ctx, ctx->id("GENERIC_IOB"), ci->name.str(ctx) + "$iob"); nxio_to_iob(ctx, ci, ice_cell.get(), packed_cells); new_cells.push_back(std::move(ice_cell)); iob = new_cells.back().get(); } packed_cells.insert(ci->name); std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(iob->attrs, iob->attrs.begin())); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto dnet : delete_nets) { ctx->nets.erase(dnet); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Main pack function bool Arch::pack() { Context *ctx = getCtx(); try { log_break(); pack_constants(ctx); pack_io(ctx); pack_lut_lutffs(ctx); pack_nonlut_ffs(ctx); ctx->settings[ctx->id("pack")] = 1; ctx->assignArchInfo(); log_info("Checksum: 0x%08x\n", ctx->checksum()); return true; } catch (log_execution_error_exception) { return false; } } NEXTPNR_NAMESPACE_END <commit_msg>generic: Fix width of 0-driver INIT<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018-19 David Shah <david@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include <algorithm> #include <iterator> #include <unordered_set> #include "cells.h" #include "design_utils.h" #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN // Pack LUTs and LUT-FF pairs static void pack_lut_lutffs(Context *ctx) { log_info("Packing LUT-FFs..\n"); std::unordered_set<IdString> packed_cells; std::vector<std::unique_ptr<CellInfo>> new_cells; for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (ctx->verbose) log_info("cell '%s' is of type '%s'\n", ci->name.c_str(ctx), ci->type.c_str(ctx)); if (is_lut(ctx, ci)) { std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), ci->name.str(ctx) + "_LC"); std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(packed->attrs, packed->attrs.begin())); packed_cells.insert(ci->name); if (ctx->verbose) log_info("packed cell %s into %s\n", ci->name.c_str(ctx), packed->name.c_str(ctx)); // See if we can pack into a DFF // TODO: LUT cascade NetInfo *o = ci->ports.at(ctx->id("Q")).net; CellInfo *dff = net_only_drives(ctx, o, is_ff, ctx->id("D"), true); auto lut_bel = ci->attrs.find(ctx->id("BEL")); bool packed_dff = false; if (dff) { if (ctx->verbose) log_info("found attached dff %s\n", dff->name.c_str(ctx)); auto dff_bel = dff->attrs.find(ctx->id("BEL")); if (lut_bel != ci->attrs.end() && dff_bel != dff->attrs.end() && lut_bel->second != dff_bel->second) { // Locations don't match, can't pack } else { lut_to_lc(ctx, ci, packed.get(), false); dff_to_lc(ctx, dff, packed.get(), false); ctx->nets.erase(o->name); if (dff_bel != dff->attrs.end()) packed->attrs[ctx->id("BEL")] = dff_bel->second; packed_cells.insert(dff->name); if (ctx->verbose) log_info("packed cell %s into %s\n", dff->name.c_str(ctx), packed->name.c_str(ctx)); packed_dff = true; } } if (!packed_dff) { lut_to_lc(ctx, ci, packed.get(), true); } new_cells.push_back(std::move(packed)); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Pack FFs not packed as LUTFFs static void pack_nonlut_ffs(Context *ctx) { log_info("Packing non-LUT FFs..\n"); std::unordered_set<IdString> packed_cells; std::vector<std::unique_ptr<CellInfo>> new_cells; for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (is_ff(ctx, ci)) { std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), ci->name.str(ctx) + "_DFFLC"); std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(packed->attrs, packed->attrs.begin())); if (ctx->verbose) log_info("packed cell %s into %s\n", ci->name.c_str(ctx), packed->name.c_str(ctx)); packed_cells.insert(ci->name); dff_to_lc(ctx, ci, packed.get(), true); new_cells.push_back(std::move(packed)); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } static bool net_is_constant(const Context *ctx, NetInfo *net, bool &value) { if (net == nullptr) return false; if (net->name == ctx->id("$PACKER_GND_NET") || net->name == ctx->id("$PACKER_VCC_NET")) { value = (net->name == ctx->id("$PACKER_VCC_NET")); return true; } else { return false; } } // Merge a net into a constant net static void set_net_constant(const Context *ctx, NetInfo *orig, NetInfo *constnet, bool constval) { orig->driver.cell = nullptr; for (auto user : orig->users) { if (user.cell != nullptr) { CellInfo *uc = user.cell; if (ctx->verbose) log_info("%s user %s\n", orig->name.c_str(ctx), uc->name.c_str(ctx)); if ((is_lut(ctx, uc) || is_lc(ctx, uc)) && (user.port.str(ctx).at(0) == 'I') && !constval) { uc->ports[user.port].net = nullptr; } else { uc->ports[user.port].net = constnet; constnet->users.push_back(user); } } } orig->users.clear(); } // Pack constants (simple implementation) static void pack_constants(Context *ctx) { log_info("Packing constants..\n"); std::unique_ptr<CellInfo> gnd_cell = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), "$PACKER_GND"); gnd_cell->params[ctx->id("INIT")] = Property(0, 1 << ctx->args.K); std::unique_ptr<NetInfo> gnd_net = std::unique_ptr<NetInfo>(new NetInfo); gnd_net->name = ctx->id("$PACKER_GND_NET"); gnd_net->driver.cell = gnd_cell.get(); gnd_net->driver.port = ctx->id("F"); gnd_cell->ports.at(ctx->id("F")).net = gnd_net.get(); std::unique_ptr<CellInfo> vcc_cell = create_generic_cell(ctx, ctx->id("GENERIC_SLICE"), "$PACKER_VCC"); // Fill with 1s vcc_cell->params[ctx->id("INIT")] = Property(Property::S1).extract(0, (1 << ctx->args.K), Property::S1); std::unique_ptr<NetInfo> vcc_net = std::unique_ptr<NetInfo>(new NetInfo); vcc_net->name = ctx->id("$PACKER_VCC_NET"); vcc_net->driver.cell = vcc_cell.get(); vcc_net->driver.port = ctx->id("F"); vcc_cell->ports.at(ctx->id("F")).net = vcc_net.get(); std::vector<IdString> dead_nets; bool gnd_used = false; for (auto net : sorted(ctx->nets)) { NetInfo *ni = net.second; if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id("GND")) { IdString drv_cell = ni->driver.cell->name; set_net_constant(ctx, ni, gnd_net.get(), false); gnd_used = true; dead_nets.push_back(net.first); ctx->cells.erase(drv_cell); } else if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id("VCC")) { IdString drv_cell = ni->driver.cell->name; set_net_constant(ctx, ni, vcc_net.get(), true); dead_nets.push_back(net.first); ctx->cells.erase(drv_cell); } } if (gnd_used) { ctx->cells[gnd_cell->name] = std::move(gnd_cell); ctx->nets[gnd_net->name] = std::move(gnd_net); } // Vcc cell always inserted for now, as it may be needed during carry legalisation (TODO: trim later if actually // never used?) ctx->cells[vcc_cell->name] = std::move(vcc_cell); ctx->nets[vcc_net->name] = std::move(vcc_net); for (auto dn : dead_nets) { ctx->nets.erase(dn); } } static bool is_nextpnr_iob(Context *ctx, CellInfo *cell) { return cell->type == ctx->id("$nextpnr_ibuf") || cell->type == ctx->id("$nextpnr_obuf") || cell->type == ctx->id("$nextpnr_iobuf"); } static bool is_generic_iob(const Context *ctx, const CellInfo *cell) { return cell->type == ctx->id("GENERIC_IOB"); } // Pack IO buffers static void pack_io(Context *ctx) { std::unordered_set<IdString> packed_cells; std::unordered_set<IdString> delete_nets; std::vector<std::unique_ptr<CellInfo>> new_cells; log_info("Packing IOs..\n"); for (auto cell : sorted(ctx->cells)) { CellInfo *ci = cell.second; if (is_nextpnr_iob(ctx, ci)) { CellInfo *iob = nullptr; if (ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_iobuf")) { iob = net_only_drives(ctx, ci->ports.at(ctx->id("O")).net, is_generic_iob, ctx->id("PAD"), true, ci); } else if (ci->type == ctx->id("$nextpnr_obuf")) { NetInfo *net = ci->ports.at(ctx->id("I")).net; iob = net_only_drives(ctx, net, is_generic_iob, ctx->id("PAD"), true, ci); } if (iob != nullptr) { // Trivial case, GENERIC_IOB used. Just destroy the net and the // iobuf log_info("%s feeds GENERIC_IOB %s, removing %s %s.\n", ci->name.c_str(ctx), iob->name.c_str(ctx), ci->type.c_str(ctx), ci->name.c_str(ctx)); NetInfo *net = iob->ports.at(ctx->id("PAD")).net; if (((ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_iobuf")) && net->users.size() > 1) || (ci->type == ctx->id("$nextpnr_obuf") && (net->users.size() > 2 || net->driver.cell != nullptr))) log_error("PAD of %s '%s' connected to more than a single top level IO.\n", iob->type.c_str(ctx), iob->name.c_str(ctx)); if (net != nullptr) { delete_nets.insert(net->name); iob->ports.at(ctx->id("PAD")).net = nullptr; } if (ci->type == ctx->id("$nextpnr_iobuf")) { NetInfo *net2 = ci->ports.at(ctx->id("I")).net; if (net2 != nullptr) { delete_nets.insert(net2->name); } } } else if (bool_or_default(ctx->settings, ctx->id("disable_iobs"))) { // No IO buffer insertion; just remove nextpnr_[io]buf for (auto &p : ci->ports) disconnect_port(ctx, ci, p.first); } else { // Create a GENERIC_IOB buffer std::unique_ptr<CellInfo> ice_cell = create_generic_cell(ctx, ctx->id("GENERIC_IOB"), ci->name.str(ctx) + "$iob"); nxio_to_iob(ctx, ci, ice_cell.get(), packed_cells); new_cells.push_back(std::move(ice_cell)); iob = new_cells.back().get(); } packed_cells.insert(ci->name); std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(iob->attrs, iob->attrs.begin())); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto dnet : delete_nets) { ctx->nets.erase(dnet); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Main pack function bool Arch::pack() { Context *ctx = getCtx(); try { log_break(); pack_constants(ctx); pack_io(ctx); pack_lut_lutffs(ctx); pack_nonlut_ffs(ctx); ctx->settings[ctx->id("pack")] = 1; ctx->assignArchInfo(); log_info("Checksum: 0x%08x\n", ctx->checksum()); return true; } catch (log_execution_error_exception) { return false; } } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include <QStringList> #include <QDebug> #include "TakeoffMissionItem.h" #include "FirmwarePluginManager.h" #include "QGCApplication.h" #include "JsonHelper.h" #include "MissionCommandTree.h" #include "MissionCommandUIInfo.h" #include "QGroundControlQmlGlobal.h" #include "SettingsManager.h" TakeoffMissionItem::TakeoffMissionItem(Vehicle* vehicle, bool flyView, MissionSettingsItem* settingsItem, QObject* parent) : SimpleMissionItem (vehicle, flyView, parent) , _settingsItem (settingsItem) { _init(); } TakeoffMissionItem::TakeoffMissionItem(MAV_CMD takeoffCmd, Vehicle* vehicle, bool flyView, MissionSettingsItem* settingsItem, QObject* parent) : SimpleMissionItem (vehicle, flyView, parent) , _settingsItem (settingsItem) { setCommand(takeoffCmd); _init(); } TakeoffMissionItem::TakeoffMissionItem(const MissionItem& missionItem, Vehicle* vehicle, bool flyView, MissionSettingsItem* settingsItem, QObject* parent) : SimpleMissionItem (vehicle, flyView, missionItem, parent) , _settingsItem (settingsItem) { _init(); } TakeoffMissionItem::~TakeoffMissionItem() { } void TakeoffMissionItem::_init(void) { _editorQml = QStringLiteral("qrc:/qml/SimpleItemEditor.qml"); connect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &TakeoffMissionItem::launchCoordinateChanged); if (_flyView) { _initLaunchTakeoffAtSameLocation(); return; } QGeoCoordinate homePosition = _settingsItem->coordinate(); if (!homePosition.isValid()) { Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle(); if (activeVehicle) { homePosition = activeVehicle->homePosition(); if (homePosition.isValid()) { _settingsItem->setCoordinate(homePosition); } } } _initLaunchTakeoffAtSameLocation(); if (homePosition.isValid() && coordinate().isValid()) { // Item already full specified, most likely from mission load from storage _wizardMode = false; } else { if (_launchTakeoffAtSameLocation && homePosition.isValid()) { _wizardMode = false; SimpleMissionItem::setCoordinate(homePosition); } else { _wizardMode = true; } } setDirty(false); } void TakeoffMissionItem::setLaunchTakeoffAtSameLocation(bool launchTakeoffAtSameLocation) { if (launchTakeoffAtSameLocation != _launchTakeoffAtSameLocation) { _launchTakeoffAtSameLocation = launchTakeoffAtSameLocation; if (_launchTakeoffAtSameLocation) { setLaunchCoordinate(coordinate()); } emit launchTakeoffAtSameLocationChanged(_launchTakeoffAtSameLocation); setDirty(true); } } void TakeoffMissionItem::setCoordinate(const QGeoCoordinate& coordinate) { if (coordinate != this->coordinate()) { SimpleMissionItem::setCoordinate(coordinate); if (_launchTakeoffAtSameLocation) { _settingsItem->setCoordinate(coordinate); } } } bool TakeoffMissionItem::isTakeoffCommand(MAV_CMD command) { return command == MAV_CMD_NAV_TAKEOFF || command == MAV_CMD_NAV_VTOL_TAKEOFF; } void TakeoffMissionItem::_initLaunchTakeoffAtSameLocation(void) { if (specifiesCoordinate()) { if (_vehicle->fixedWing() || _vehicle->vtol()) { setLaunchTakeoffAtSameLocation(false); } else { // PX4 specifies a coordinate for takeoff even for non fixed wing. But it makes more sense to not have a coordinate // from and end user standpoint. So even for PX4 we try to keep launch and takeoff at the same position. Unless the // user has moved/loaded launch at a different location than takeoff. if (coordinate().isValid() && _settingsItem->coordinate().isValid()) { setLaunchTakeoffAtSameLocation(coordinate().latitude() == _settingsItem->coordinate().latitude() && coordinate().longitude() == _settingsItem->coordinate().longitude()); } else { setLaunchTakeoffAtSameLocation(true); } } } else { setLaunchTakeoffAtSameLocation(true); } } bool TakeoffMissionItem::load(QTextStream &loadStream) { bool success = SimpleMissionItem::load(loadStream); if (success) { _initLaunchTakeoffAtSameLocation(); } return success; } bool TakeoffMissionItem::load(const QJsonObject& json, int sequenceNumber, QString& errorString) { bool success = SimpleMissionItem::load(json, sequenceNumber, errorString); if (success) { _initLaunchTakeoffAtSameLocation(); } return success; } void TakeoffMissionItem::setLaunchCoordinate(const QGeoCoordinate& launchCoordinate) { if (!launchCoordinate.isValid()) { return; } _settingsItem->setCoordinate(launchCoordinate); if (!coordinate().isValid()) { QGeoCoordinate takeoffCoordinate; if (_launchTakeoffAtSameLocation) { takeoffCoordinate = launchCoordinate; } else { double altitude = this->altitude()->rawValue().toDouble(); double distance = 0.0; if (coordinateHasRelativeAltitude()) { // Offset for fixed wing climb out of 30 degrees if (altitude != 0.0) { distance = altitude / tan(qDegreesToRadians(30.0)); } } else { distance = altitude * 1.5; } takeoffCoordinate = launchCoordinate.atDistanceAndAzimuth(distance, 0); } SimpleMissionItem::setCoordinate(takeoffCoordinate); } } <commit_msg><commit_after>/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include <QStringList> #include <QDebug> #include "TakeoffMissionItem.h" #include "FirmwarePluginManager.h" #include "QGCApplication.h" #include "JsonHelper.h" #include "MissionCommandTree.h" #include "MissionCommandUIInfo.h" #include "QGroundControlQmlGlobal.h" #include "SettingsManager.h" TakeoffMissionItem::TakeoffMissionItem(Vehicle* vehicle, bool flyView, MissionSettingsItem* settingsItem, QObject* parent) : SimpleMissionItem (vehicle, flyView, parent) , _settingsItem (settingsItem) { _init(); } TakeoffMissionItem::TakeoffMissionItem(MAV_CMD takeoffCmd, Vehicle* vehicle, bool flyView, MissionSettingsItem* settingsItem, QObject* parent) : SimpleMissionItem (vehicle, flyView, parent) , _settingsItem (settingsItem) { setCommand(takeoffCmd); _init(); } TakeoffMissionItem::TakeoffMissionItem(const MissionItem& missionItem, Vehicle* vehicle, bool flyView, MissionSettingsItem* settingsItem, QObject* parent) : SimpleMissionItem (vehicle, flyView, missionItem, parent) , _settingsItem (settingsItem) { _init(); } TakeoffMissionItem::~TakeoffMissionItem() { } void TakeoffMissionItem::_init(void) { _editorQml = QStringLiteral("qrc:/qml/SimpleItemEditor.qml"); connect(_settingsItem, &MissionSettingsItem::coordinateChanged, this, &TakeoffMissionItem::launchCoordinateChanged); if (_flyView) { _initLaunchTakeoffAtSameLocation(); return; } QGeoCoordinate homePosition = _settingsItem->coordinate(); if (!homePosition.isValid()) { Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle(); if (activeVehicle) { homePosition = activeVehicle->homePosition(); if (homePosition.isValid()) { _settingsItem->setCoordinate(homePosition); } } } _initLaunchTakeoffAtSameLocation(); if (homePosition.isValid() && coordinate().isValid()) { // Item already fully specified, most likely from mission load from storage _wizardMode = false; } else { if (_launchTakeoffAtSameLocation && homePosition.isValid()) { _wizardMode = false; SimpleMissionItem::setCoordinate(homePosition); } else { _wizardMode = true; } } setDirty(false); } void TakeoffMissionItem::setLaunchTakeoffAtSameLocation(bool launchTakeoffAtSameLocation) { if (launchTakeoffAtSameLocation != _launchTakeoffAtSameLocation) { _launchTakeoffAtSameLocation = launchTakeoffAtSameLocation; if (_launchTakeoffAtSameLocation) { setLaunchCoordinate(coordinate()); } emit launchTakeoffAtSameLocationChanged(_launchTakeoffAtSameLocation); setDirty(true); } } void TakeoffMissionItem::setCoordinate(const QGeoCoordinate& coordinate) { if (coordinate != this->coordinate()) { SimpleMissionItem::setCoordinate(coordinate); if (_launchTakeoffAtSameLocation) { _settingsItem->setCoordinate(coordinate); } } } bool TakeoffMissionItem::isTakeoffCommand(MAV_CMD command) { return command == MAV_CMD_NAV_TAKEOFF || command == MAV_CMD_NAV_VTOL_TAKEOFF; } void TakeoffMissionItem::_initLaunchTakeoffAtSameLocation(void) { if (specifiesCoordinate()) { if (_vehicle->fixedWing() || _vehicle->vtol()) { setLaunchTakeoffAtSameLocation(false); } else { // PX4 specifies a coordinate for takeoff even for non fixed wing. But it makes more sense to not have a coordinate // from and end user standpoint. So even for PX4 we try to keep launch and takeoff at the same position. Unless the // user has moved/loaded launch at a different location than takeoff. if (coordinate().isValid() && _settingsItem->coordinate().isValid()) { setLaunchTakeoffAtSameLocation(coordinate().latitude() == _settingsItem->coordinate().latitude() && coordinate().longitude() == _settingsItem->coordinate().longitude()); } else { setLaunchTakeoffAtSameLocation(true); } } } else { setLaunchTakeoffAtSameLocation(true); } } bool TakeoffMissionItem::load(QTextStream &loadStream) { bool success = SimpleMissionItem::load(loadStream); if (success) { _initLaunchTakeoffAtSameLocation(); } return success; } bool TakeoffMissionItem::load(const QJsonObject& json, int sequenceNumber, QString& errorString) { bool success = SimpleMissionItem::load(json, sequenceNumber, errorString); if (success) { _initLaunchTakeoffAtSameLocation(); } _wizardMode = false; // Should always be off for loaded items return success; } void TakeoffMissionItem::setLaunchCoordinate(const QGeoCoordinate& launchCoordinate) { if (!launchCoordinate.isValid()) { return; } _settingsItem->setCoordinate(launchCoordinate); if (!coordinate().isValid()) { QGeoCoordinate takeoffCoordinate; if (_launchTakeoffAtSameLocation) { takeoffCoordinate = launchCoordinate; } else { double altitude = this->altitude()->rawValue().toDouble(); double distance = 0.0; if (coordinateHasRelativeAltitude()) { // Offset for fixed wing climb out of 30 degrees if (altitude != 0.0) { distance = altitude / tan(qDegreesToRadians(30.0)); } } else { distance = altitude * 1.5; } takeoffCoordinate = launchCoordinate.atDistanceAndAzimuth(distance, 0); } SimpleMissionItem::setCoordinate(takeoffCoordinate); } } <|endoftext|>
<commit_before>#include "../include/PulseaudioDevice.h" using namespace std; PulseaudioDevice::PulseaudioDevice(const AudioHeader &header) : AudioDevice(header) { pa_sample_spec ss; ss.format = PA_SAMPLE_S16NE;//PA_SAMPLE_U8; ss.channels = 1; ss.rate = 44100;//header.get_rate(); device = pa_simple_new(nullptr, // Use the default server. "DixieAudio", // Our application's name. PA_STREAM_PLAYBACK, nullptr, // Use the default device. "Retro-Groovy-Music", // Description of our stream. &ss, // Our sample format. nullptr, // Use default channel map nullptr, // Use default buffering attributes. &pulse_error_code // Ignore error code. ); } PulseaudioDevice::~PulseaudioDevice() { pa_simple_free(device); } int PulseaudioDevice::write(const std::vector<AudioData> data) { // int pa_simple_write ( pa_simple * s, // const void * data, // size_t bytes, // int * error // ) return pa_simple_write(device, static_cast<const void *>(&data), data.size(), nullptr); } <commit_msg>Sends the right data to pulse<commit_after>#include "../include/PulseaudioDevice.h" #include <iostream> using namespace std; PulseaudioDevice::PulseaudioDevice(const AudioHeader &header) : AudioDevice(header) { pa_sample_spec ss; ss.format = PA_SAMPLE_U8; ss.channels = 1; ss.rate = header.get_rate(); device = pa_simple_new(nullptr, // Use the default server. "DixieAudio", // Our application's name. PA_STREAM_PLAYBACK, nullptr, // Use the default device. "Retro-Groovy-Music", // Description of our stream. &ss, // Our sample format. nullptr, // Use default channel map nullptr, // Use default buffering attributes. &pulse_error_code // Ignore error code. ); } PulseaudioDevice::~PulseaudioDevice() { pa_simple_free(device); } int PulseaudioDevice::write(const std::vector<AudioData> data) { return pa_simple_write(device, &data[0], 200, nullptr); } <|endoftext|>
<commit_before>/// /// @file popcnt.hpp /// @brief Functions to count the number of 1 bits inside /// an array or a 64-bit word. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POPCNT_HPP #define POPCNT_HPP #include <stdint.h> #if defined(__has_include) #define HAS_INCLUDE(header) __has_include(header) #else // If the __has_include() macro does not exist // we assume that the header file exists. #define HAS_INCLUDE(header) 1 #endif #if !defined(DISABLE_POPCNT) #if defined(__has_builtin) #define HAS_BUILTIN_POPCOUNTLL __has_builtin(__builtin_popcountll) #elif defined(__GNUC__) // GCC does not yet support __has_builtin() // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66970 #define HAS_BUILTIN_POPCOUNTLL 1 #endif // GCC & Clang #if HAS_BUILTIN_POPCOUNTLL namespace { inline uint64_t popcnt64(uint64_t x) { return __builtin_popcountll(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN64) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u64(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN32) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u32((uint32_t) x) + _mm_popcnt_u32((uint32_t)(x >> 32)); } } // namespace #else // Enable fallback mode. Compute popcount using an algorithm // that uses only integer instructions. #define DISABLE_POPCNT #endif #endif #if defined(DISABLE_POPCNT) namespace { /// This uses fewer arithmetic operations than any other known /// implementation on machines with fast multiplication. /// It uses 12 arithmetic operations, one of which is a multiply. /// https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation /// inline uint64_t popcnt64(uint64_t x) { uint64_t m1 = 0x5555555555555555ull; uint64_t m2 = 0x3333333333333333ull; uint64_t m4 = 0x0F0F0F0F0F0F0F0Full; uint64_t h01 = 0x0101010101010101ull; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; } /// Carry-save adder (CSA). /// @see Chapter 5 in "Hacker's Delight" 2nd edition. /// inline void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c) { uint64_t u = a ^ b; h = (a & b) | (u & c); l = u ^ c; } /// Harley-Seal popcount (3rd iteration). /// The Harley-Seal popcount algorithm is one of the fastest algorithms /// for counting 1 bits in an array using only integer operations. /// This implementation uses only 6.38 instructions per 64-bit word. /// @see Chapter 5 in "Hacker's Delight" 2nd edition. /// inline uint64_t popcnt(const uint64_t* data, uint64_t size) { uint64_t cnt = 0; uint64_t ones = 0, twos = 0, fours = 0, eights = 0; uint64_t twosA, twosB, foursA, foursB; uint64_t limit = size - size % 8; uint64_t i = 0; for(; i < limit; i += 8) { CSA(twosA, ones, ones, data[i+0], data[i+1]); CSA(twosB, ones, ones, data[i+2], data[i+3]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, data[i+4], data[i+5]); CSA(twosB, ones, ones, data[i+6], data[i+7]); CSA(foursB, twos, twos, twosA, twosB); CSA(eights, fours, fours, foursA, foursB); cnt += popcnt64(eights); } cnt *= 8; cnt += 4 * popcnt64(fours); cnt += 2 * popcnt64(twos); cnt += 1 * popcnt64(ones); for(; i < size; i++) cnt += popcnt64(data[i]); return cnt; } } // namespace #elif (defined(__ARM_NEON) || \ defined(__aarch64__)) && \ HAS_INCLUDE(<arm_neon.h>) #include <arm_neon.h> namespace { inline uint64x2_t vpadalq(uint64x2_t sum, uint8x16_t t) { return vpadalq_u32(sum, vpaddlq_u16(vpaddlq_u8(t))); } /// Count the number of 1 bits in the data array. /// ARM NEON has a vector popcount instruction but no scalar /// popcount instruction that's why the ARM popcount function /// is more complicated than the x86 popcount function. /// This function has been copied from: /// https://github.com/kimwalisch/libpopcnt /// inline uint64_t popcnt(const uint64_t* data, uint64_t size) { uint64_t i = 0; uint64_t cnt = 0; if (size >= 8) { const uint8_t* data8 = (const uint8_t*) data; uint64_t bytes = size * sizeof(uint64_t); uint64_t chunk_size = 64; uint64_t iters = bytes / chunk_size; uint64_t is_sum = 31; uint64x2_t sum = vcombine_u64(vcreate_u64(0), vcreate_u64(0)); uint8x16_t zero = vcombine_u8(vcreate_u8(0), vcreate_u8(0)); uint8x16_t t0 = zero; uint8x16_t t1 = zero; uint8x16_t t2 = zero; uint8x16_t t3 = zero; // Each iteration processes 64 bytes for (; i < iters; i++) { uint8x16x4_t input = vld4q_u8(data8); data8 += chunk_size; t0 = vaddq_u8(t0, vcntq_u8(input.val[0])); t1 = vaddq_u8(t1, vcntq_u8(input.val[1])); t2 = vaddq_u8(t2, vcntq_u8(input.val[2])); t3 = vaddq_u8(t3, vcntq_u8(input.val[3])); // After every 31 iterations we need to add the // temporary sums (t0, t1, ...) to the total sum. // We must ensure that the temporary sums <= 255 // and 31 * 8 bits = 248 which is OK. if (i == is_sum) { sum = vpadalq(sum, t0); sum = vpadalq(sum, t1); sum = vpadalq(sum, t2); sum = vpadalq(sum, t3); t0 = t1 = t2 = t3 = zero; is_sum += 31; } } sum = vpadalq(sum, t0); sum = vpadalq(sum, t1); sum = vpadalq(sum, t2); sum = vpadalq(sum, t3); uint64_t tmp[2]; vst1q_u64(tmp, sum); cnt += tmp[0]; cnt += tmp[1]; uint64_t bytes_processed = iters * chunk_size; i = bytes_processed / sizeof(uint64_t); } // Process the remaining bytes for (; i < size; i++) cnt += popcnt64(data[i]); return cnt; } } // namespace #else namespace { /// Used for all CPUs except ARM inline uint64_t popcnt(const uint64_t* data, uint64_t size) { uint64_t cnt = 0; uint64_t i = 0; uint64_t limit = size - size % 4; for (; i < limit; i += 4) { cnt += popcnt64(data[i+0]); cnt += popcnt64(data[i+1]); cnt += popcnt64(data[i+2]); cnt += popcnt64(data[i+3]); } for (; i < size; i++) cnt += popcnt64(data[i]); return cnt; } } // namespace #endif #endif // POPCNT_HPP <commit_msg>Faster ARM64 popcount<commit_after>/// /// @file popcnt.hpp /// @brief Functions to count the number of 1 bits inside /// an array or a 64-bit word. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POPCNT_HPP #define POPCNT_HPP #include <algorithm> #include <stdint.h> #if defined(__has_include) #define HAS_INCLUDE(header) __has_include(header) #else // If the __has_include() macro does not exist // we assume that the header file exists. #define HAS_INCLUDE(header) 1 #endif #if !defined(DISABLE_POPCNT) #if defined(__has_builtin) #define HAS_BUILTIN_POPCOUNTLL __has_builtin(__builtin_popcountll) #elif defined(__GNUC__) // GCC does not yet support __has_builtin() // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66970 #define HAS_BUILTIN_POPCOUNTLL 1 #endif // GCC & Clang #if HAS_BUILTIN_POPCOUNTLL namespace { inline uint64_t popcnt64(uint64_t x) { return __builtin_popcountll(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN64) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u64(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN32) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u32((uint32_t) x) + _mm_popcnt_u32((uint32_t)(x >> 32)); } } // namespace #else // Enable fallback mode. Compute popcount using an algorithm // that uses only integer instructions. #define DISABLE_POPCNT #endif #endif #if defined(DISABLE_POPCNT) namespace { /// This uses fewer arithmetic operations than any other known /// implementation on machines with fast multiplication. /// It uses 12 arithmetic operations, one of which is a multiply. /// https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation /// inline uint64_t popcnt64(uint64_t x) { uint64_t m1 = 0x5555555555555555ull; uint64_t m2 = 0x3333333333333333ull; uint64_t m4 = 0x0F0F0F0F0F0F0F0Full; uint64_t h01 = 0x0101010101010101ull; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; } /// Carry-save adder (CSA). /// @see Chapter 5 in "Hacker's Delight" 2nd edition. /// inline void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c) { uint64_t u = a ^ b; h = (a & b) | (u & c); l = u ^ c; } /// Harley-Seal popcount (3rd iteration). /// The Harley-Seal popcount algorithm is one of the fastest algorithms /// for counting 1 bits in an array using only integer operations. /// This implementation uses only 6.38 instructions per 64-bit word. /// @see Chapter 5 in "Hacker's Delight" 2nd edition. /// inline uint64_t popcnt(const uint64_t* data, uint64_t size) { uint64_t cnt = 0; uint64_t ones = 0, twos = 0, fours = 0, eights = 0; uint64_t twosA, twosB, foursA, foursB; uint64_t limit = size - size % 8; uint64_t i = 0; for(; i < limit; i += 8) { CSA(twosA, ones, ones, data[i+0], data[i+1]); CSA(twosB, ones, ones, data[i+2], data[i+3]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, data[i+4], data[i+5]); CSA(twosB, ones, ones, data[i+6], data[i+7]); CSA(foursB, twos, twos, twosA, twosB); CSA(eights, fours, fours, foursA, foursB); cnt += popcnt64(eights); } cnt *= 8; cnt += 4 * popcnt64(fours); cnt += 2 * popcnt64(twos); cnt += 1 * popcnt64(ones); for(; i < size; i++) cnt += popcnt64(data[i]); return cnt; } } // namespace #elif (defined(__ARM_NEON) || \ defined(__aarch64__)) && \ HAS_INCLUDE(<arm_neon.h>) #include <arm_neon.h> namespace { inline uint64x2_t vpadalq(uint64x2_t sum, uint8x16_t t) { return vpadalq_u32(sum, vpaddlq_u16(vpaddlq_u8(t))); } /// Count the number of 1 bits in the data array. /// ARM NEON has a vector popcount instruction but no scalar /// popcount instruction that's why the ARM popcount function /// is more complicated than the x86 popcount function. /// This function has been copied from: /// https://github.com/kimwalisch/libpopcnt /// inline uint64_t popcnt(const uint64_t* data, uint64_t size) { uint64_t i = 0; uint64_t cnt = 0; if (size >= 8) { const uint8_t* data8 = (const uint8_t*) data; uint64_t bytes = size * sizeof(uint64_t); uint64_t chunk_size = 64; uint64_t iters = bytes / chunk_size; uint64x2_t sum = vcombine_u64(vcreate_u64(0), vcreate_u64(0)); uint8x16_t zero = vcombine_u8(vcreate_u8(0), vcreate_u8(0)); do { uint8x16_t t0 = zero; uint8x16_t t1 = zero; uint8x16_t t2 = zero; uint8x16_t t3 = zero; // After every 31 iterations we need to add the // temporary sums (t0, t1, t2, t3) to the total sum. // We must ensure that the temporary sums <= 255 // and 31 * 8 bits = 248 which is OK. uint64_t limit = std::min(i + 31, iters); // Each iteration processes 64 bytes for (; i < limit; i++) { uint8x16x4_t input = vld4q_u8(data8); data8 += chunk_size; t0 = vaddq_u8(t0, vcntq_u8(input.val[0])); t1 = vaddq_u8(t1, vcntq_u8(input.val[1])); t2 = vaddq_u8(t2, vcntq_u8(input.val[2])); t3 = vaddq_u8(t3, vcntq_u8(input.val[3])); } sum = vpadalq(sum, t0); sum = vpadalq(sum, t1); sum = vpadalq(sum, t2); sum = vpadalq(sum, t3); } while (i < iters); uint64_t tmp[2]; vst1q_u64(tmp, sum); cnt += tmp[0]; cnt += tmp[1]; uint64_t bytes_processed = iters * chunk_size; i = bytes_processed / sizeof(uint64_t); } // Process the remaining bytes for (; i < size; i++) cnt += popcnt64(data[i]); return cnt; } } // namespace #else namespace { /// Used for all CPUs except ARM inline uint64_t popcnt(const uint64_t* data, uint64_t size) { uint64_t cnt = 0; uint64_t i = 0; uint64_t limit = size - size % 4; for (; i < limit; i += 4) { cnt += popcnt64(data[i+0]); cnt += popcnt64(data[i+1]); cnt += popcnt64(data[i+2]); cnt += popcnt64(data[i+3]); } for (; i < size; i++) cnt += popcnt64(data[i]); return cnt; } } // namespace #endif #endif // POPCNT_HPP <|endoftext|>
<commit_before>/* Copyright 2015 Ahnaf Siddiqui Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Q_QuantumWorld2D.h" namespace Quantum2D { namespace QuantumWorld2D { static std::vector<unsigned long> trans_index_stack = std::vector<unsigned long>(); static std::vector<unsigned long> body_id_index_map = std::vector<unsigned long>(); static std::vector<unsigned long> body_id_stack = std::vector<unsigned long>(); } } std::vector<Diamond::Transform2i> Quantum2D::QuantumWorld2D::transforms(0); std::vector<Quantum2D::Rigidbody2D> Quantum2D::QuantumWorld2D::bodies(0); Quantum2D::Rigidbody2D *Quantum2D::QuantumWorld2D::getRigidbody(unsigned long body_id) { return &bodies[body_id_index_map[body_id]]; } unsigned long Quantum2D::QuantumWorld2D::genTransform() { if (trans_index_stack.size() != 0) { unsigned long index = trans_index_stack.back(); trans_index_stack.pop_back(); transforms[index].reset(); return index; } else { transforms.push_back(Diamond::Transform2i()); return transforms.size() - 1; } } void Quantum2D::QuantumWorld2D::freeTransform(unsigned long index) { trans_index_stack.push_back(index); } unsigned long Quantum2D::QuantumWorld2D::genRigidbody(unsigned long transform_index) { unsigned long body_id; if (body_id_stack.size() != 0) { body_id = body_id_stack.back(); body_id_stack.pop_back(); body_id_index_map[body_id] = bodies.size(); } else { body_id = body_id_index_map.size(); body_id_index_map.push_back(bodies.size()); } bodies.push_back(Rigidbody2D(body_id, transform_index)); return body_id; } void Quantum2D::QuantumWorld2D::freeRigidbody(unsigned long body_id) { unsigned long index = body_id_index_map[body_id]; if (index < bodies.size() - 1) { // If in middle of vector, replace it with last element in vector bodies[index] = bodies.back(); body_id_index_map[bodies[index].body_id] = index; } bodies.pop_back(); body_id_stack.push_back(body_id); } void Quantum2D::QuantumWorld2D::step(int delta_ms) { for (std::vector<Rigidbody2D>::iterator i = bodies.begin(); i != bodies.end(); i++) { i->update(delta_ms); } } <commit_msg>Fixed build error from misinformed vector initializer<commit_after>/* Copyright 2015 Ahnaf Siddiqui Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Q_QuantumWorld2D.h" namespace Quantum2D { namespace QuantumWorld2D { static std::vector<unsigned long> trans_index_stack = std::vector<unsigned long>(); static std::vector<unsigned long> body_id_index_map = std::vector<unsigned long>(); static std::vector<unsigned long> body_id_stack = std::vector<unsigned long>(); } } std::vector<Diamond::Transform2i> Quantum2D::QuantumWorld2D::transforms = std::vector<Diamond::Transform2i>(); std::vector<Quantum2D::Rigidbody2D> Quantum2D::QuantumWorld2D::bodies = std::vector<Quantum2D::Rigidbody2D>(); Quantum2D::Rigidbody2D *Quantum2D::QuantumWorld2D::getRigidbody(unsigned long body_id) { return &bodies[body_id_index_map[body_id]]; } unsigned long Quantum2D::QuantumWorld2D::genTransform() { if (trans_index_stack.size() != 0) { unsigned long index = trans_index_stack.back(); trans_index_stack.pop_back(); transforms[index].reset(); return index; } else { transforms.push_back(Diamond::Transform2i()); return transforms.size() - 1; } } void Quantum2D::QuantumWorld2D::freeTransform(unsigned long index) { trans_index_stack.push_back(index); } unsigned long Quantum2D::QuantumWorld2D::genRigidbody(unsigned long transform_index) { unsigned long body_id; if (body_id_stack.size() != 0) { body_id = body_id_stack.back(); body_id_stack.pop_back(); body_id_index_map[body_id] = bodies.size(); } else { body_id = body_id_index_map.size(); body_id_index_map.push_back(bodies.size()); } bodies.push_back(Rigidbody2D(body_id, transform_index)); return body_id; } void Quantum2D::QuantumWorld2D::freeRigidbody(unsigned long body_id) { unsigned long index = body_id_index_map[body_id]; if (index < bodies.size() - 1) { // If in middle of vector, replace it with last element in vector bodies[index] = bodies.back(); body_id_index_map[bodies[index].body_id] = index; } bodies.pop_back(); body_id_stack.push_back(body_id); } void Quantum2D::QuantumWorld2D::step(int delta_ms) { for (std::vector<Rigidbody2D>::iterator i = bodies.begin(); i != bodies.end(); i++) { i->update(delta_ms); } } <|endoftext|>
<commit_before>// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pal_config.h" #include "pal_console.h" #include "pal_utilities.h" #include <assert.h> #include <errno.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <termios.h> #include <unistd.h> #include <poll.h> extern "C" int32_t SystemNative_GetWindowSize(WinSize* windowSize) { assert(windowSize != nullptr); #if HAVE_IOCTL && HAVE_TIOCGWINSZ int error = ioctl(STDOUT_FILENO, TIOCGWINSZ, windowSize); if (error != 0) { *windowSize = {}; // managed out param must be initialized } return error; #else errno = ENOTSUP; return -1; #endif } // TODO: temporarily keeping the un-prefixed signature of this method // to keep tests running in CI. This will be removed once the managed assemblies // are synced up with the native assemblies. extern "C" int32_t IsATty(intptr_t fd) { return SystemNative_IsATty(fd); } extern "C" int32_t SystemNative_IsATty(intptr_t fd) { return isatty(ToFileDescriptor(fd)); } static bool g_initialized = false; static termios g_originalTermios = { }; static void UninitializeConsole() { assert(g_initialized); if (g_initialized) { g_initialized = false; tcsetattr(STDIN_FILENO, TCSANOW, &g_originalTermios); } } extern "C" void SystemNative_InitializeConsole() { assert(!g_initialized); #if HAVE_TCGETATTR && HAVE_TCSETATTR && HAVE_ECHO && HAVE_ICANON && HAVE_TCSANOW struct termios newtermios = {}; if (tcgetattr(STDIN_FILENO, &newtermios) >= 0) { g_originalTermios = newtermios; newtermios.c_lflag &= static_cast<uint32_t>(~(ECHO | ICANON)); newtermios.c_cc[VMIN] = 1; newtermios.c_cc[VTIME] = 0; if (tcsetattr(STDIN_FILENO, TCSANOW, &newtermios) >= 0) { g_initialized = true; atexit(UninitializeConsole); } } #endif } extern "C" int32_t SystemNative_StdinReady() { struct pollfd fd; fd.fd = STDIN_FILENO; fd.events = POLLIN; return poll(&fd, 1, 0) > 0 ? 1 : 0; } extern "C" int32_t SystemNative_ReadStdinUnbuffered(void* buffer, int32_t bufferSize) { assert(buffer != nullptr || bufferSize == 0); assert(bufferSize >= 0); if (bufferSize < 0) { errno = EINVAL; return -1; } ssize_t count; while (CheckInterrupted(count = read(STDIN_FILENO, buffer, UnsignedCast(bufferSize)))); return static_cast<int32_t>(count); } static struct sigaction g_origSigIntHandler, g_origSigQuitHandler; // saved signal handlers static volatile CtrlCallback g_ctrlCallback = nullptr; // Callback invoked for SIGINT/SIGQUIT static bool g_signalHandlingInitialized = false; // Whether signal handling is initialized static int g_signalPipe[2] = {-1, -1}; // Pipe used between signal handler and worker // Signal handler for SIGINT / SIGQUIT. static void sigintquit_handler(int code) { // Write the signal code to the pipe uint8_t signalCodeByte = static_cast<uint8_t>(code); ssize_t writtenBytes; do { writtenBytes = write(g_signalPipe[1], &signalCodeByte, 1); } while ((writtenBytes == -1) && (errno == EINTR)); if (writtenBytes != 1) { abort(); // fatal error } } // Ctrl-handling worker thread entry point. void* CtrlHandleLoop(void* arg) { // Passed in argument is a ptr to the file descriptor // for the read end of the pipe. assert(arg != nullptr); int pipeFd = *reinterpret_cast<int*>(arg); free(arg); assert(pipeFd >= 0); // Continually read a signal code from the signal pipe and process it, // until the pipe is closed. while (true) { // Read the next signal, trying again if we were interrupted uint8_t signalCode; ssize_t bytesRead; do { bytesRead = read(pipeFd, &signalCode, 1); } while (bytesRead == -1 && errno == EINTR); if (bytesRead <= 0) { // Write end of pipe was closed or another error occurred. // Regardless, no more data is available, so we close the read // end of the pipe and exit. close(pipeFd); return nullptr; } // Invoke the callback. We take the lock while calling it so as to prevent // it from being removed while we're still using it. CtrlCallback callback = g_ctrlCallback; int rv = callback != nullptr ? callback(signalCode == SIGQUIT ? Break : Interrupt) : 0; if (rv == 0) // callback removed or was invoked and didn't handle the signal { // restore original handlers, then reissue the signal sigaction(SIGINT, &g_origSigIntHandler, NULL); sigaction(SIGQUIT, &g_origSigQuitHandler, NULL); kill(getpid(), signalCode); } } } static void CloseSignalHandlingPipe() { assert(g_signalPipe[0] >= 0); assert(g_signalPipe[1] >= 0); close(g_signalPipe[0]); close(g_signalPipe[1]); g_signalPipe[0] = -1; g_signalPipe[1] = -1; } static bool InitializeSignalHandling() { assert(!g_signalHandlingInitialized); // Create a pipe we'll use to communicate with our worker // thread. We can't do anything interesting in the signal handler, // so we instead send a message to another thread that'll do // the handling work. if (pipe(g_signalPipe) != 0) { return false; } assert(g_signalPipe[0] >= 0); assert(g_signalPipe[1] >= 0); // Create a small object to pass the read end of the pipe to the worker. int* readFdPtr = reinterpret_cast<int*>(malloc(sizeof(int))); if (readFdPtr == nullptr) { CloseSignalHandlingPipe(); errno = ENOMEM; return false; } *readFdPtr = g_signalPipe[0]; // The pipe is created. Create the worker thread. pthread_t handlerThread; if (pthread_create(&handlerThread, nullptr, CtrlHandleLoop, readFdPtr) != 0) { int err = errno; free(readFdPtr); CloseSignalHandlingPipe(); errno = err; return false; } // Finally, register the signal handlers for SIGINT and SIGQUIT. struct sigaction newAction = { .sa_flags = SA_RESTART, .sa_handler = &sigintquit_handler, }; sigemptyset(&newAction.sa_mask); int rv = sigaction(SIGINT, &newAction, &g_origSigIntHandler); assert(rv == 0); rv = sigaction(SIGQUIT, &newAction, &g_origSigQuitHandler); assert(rv == 0); g_signalHandlingInitialized = true; return true; } // TODO: temporarily keeping the un-prefixed signature of this method // to keep tests running in CI. This will be removed once the managed assemblies // are synced up with the native assemblies. extern "C" int32_t RegisterForCtrl(CtrlCallback callback) { return SystemNative_RegisterForCtrl(callback); } extern "C" int32_t SystemNative_RegisterForCtrl(CtrlCallback callback) { assert(callback != nullptr); assert(g_ctrlCallback == nullptr); g_ctrlCallback = callback; if (!g_signalHandlingInitialized && !InitializeSignalHandling()) { g_ctrlCallback = nullptr; return 0; } return 1; } // TODO: temporarily keeping the un-prefixed signature of this method // to keep tests running in CI. This will be removed once the managed assemblies // are synced up with the native assemblies. extern "C" void UnregisterForCtrl() { SystemNative_UnregisterForCtrl(); } extern "C" void SystemNative_UnregisterForCtrl() { assert(g_ctrlCallback != nullptr); g_ctrlCallback = nullptr; // Keep the signal handlers registered and the worker thread // up and running for when registration is done again. } <commit_msg>Make Console signal handling more robust<commit_after>// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pal_config.h" #include "pal_console.h" #include "pal_utilities.h" #include <assert.h> #include <errno.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <termios.h> #include <unistd.h> #include <poll.h> extern "C" int32_t SystemNative_GetWindowSize(WinSize* windowSize) { assert(windowSize != nullptr); #if HAVE_IOCTL && HAVE_TIOCGWINSZ int error = ioctl(STDOUT_FILENO, TIOCGWINSZ, windowSize); if (error != 0) { *windowSize = {}; // managed out param must be initialized } return error; #else errno = ENOTSUP; return -1; #endif } // TODO: temporarily keeping the un-prefixed signature of this method // to keep tests running in CI. This will be removed once the managed assemblies // are synced up with the native assemblies. extern "C" int32_t IsATty(intptr_t fd) { return SystemNative_IsATty(fd); } extern "C" int32_t SystemNative_IsATty(intptr_t fd) { return isatty(ToFileDescriptor(fd)); } static bool g_initialized = false; static termios g_originalTermios = { }; static void UninitializeConsole() { assert(g_initialized); if (g_initialized) { g_initialized = false; tcsetattr(STDIN_FILENO, TCSANOW, &g_originalTermios); } } extern "C" void SystemNative_InitializeConsole() { assert(!g_initialized); #if HAVE_TCGETATTR && HAVE_TCSETATTR && HAVE_ECHO && HAVE_ICANON && HAVE_TCSANOW struct termios newtermios = {}; if (tcgetattr(STDIN_FILENO, &newtermios) >= 0) { g_originalTermios = newtermios; newtermios.c_lflag &= static_cast<uint32_t>(~(ECHO | ICANON)); newtermios.c_cc[VMIN] = 1; newtermios.c_cc[VTIME] = 0; if (tcsetattr(STDIN_FILENO, TCSANOW, &newtermios) >= 0) { g_initialized = true; atexit(UninitializeConsole); } } #endif } extern "C" int32_t SystemNative_StdinReady() { struct pollfd fd; fd.fd = STDIN_FILENO; fd.events = POLLIN; return poll(&fd, 1, 0) > 0 ? 1 : 0; } extern "C" int32_t SystemNative_ReadStdinUnbuffered(void* buffer, int32_t bufferSize) { assert(buffer != nullptr || bufferSize == 0); assert(bufferSize >= 0); if (bufferSize < 0) { errno = EINVAL; return -1; } ssize_t count; while (CheckInterrupted(count = read(STDIN_FILENO, buffer, UnsignedCast(bufferSize)))); return static_cast<int32_t>(count); } static struct sigaction g_origSigIntHandler, g_origSigQuitHandler; // saved signal handlers static volatile CtrlCallback g_ctrlCallback = nullptr; // Callback invoked for SIGINT/SIGQUIT static bool g_signalHandlingInitialized = false; // Whether signal handling is initialized static int g_signalPipe[2] = {-1, -1}; // Pipe used between signal handler and worker // Signal handler for SIGINT / SIGQUIT. static void sigintquit_handler(int code) { // Write the signal code to the pipe uint8_t signalCodeByte = static_cast<uint8_t>(code); ssize_t writtenBytes; do { writtenBytes = write(g_signalPipe[1], &signalCodeByte, 1); } while ((writtenBytes == -1) && (errno == EINTR)); if (writtenBytes != 1) { abort(); // fatal error } } // Ctrl-handling worker thread entry point. void* CtrlHandleLoop(void* arg) { // Passed in argument is a ptr to the file descriptor // for the read end of the pipe. assert(arg != nullptr); int pipeFd = *reinterpret_cast<int*>(arg); free(arg); assert(pipeFd >= 0); // Continually read a signal code from the signal pipe and process it, // until the pipe is closed. while (true) { // Read the next signal, trying again if we were interrupted uint8_t signalCode; ssize_t bytesRead; do { bytesRead = read(pipeFd, &signalCode, 1); } while (bytesRead == -1 && errno == EINTR); if (bytesRead <= 0) { // Write end of pipe was closed or another error occurred. // Regardless, no more data is available, so we close the read // end of the pipe and exit. close(pipeFd); return nullptr; } // Invoke the callback. We take the lock while calling it so as to prevent // it from being removed while we're still using it. CtrlCallback callback = g_ctrlCallback; int rv = callback != nullptr ? callback(signalCode == SIGQUIT ? Break : Interrupt) : 0; if (rv == 0) // callback removed or was invoked and didn't handle the signal { // In general, we now want to remove our handler and reissue the signal to // be picked up by the previously registered handler. In the most common case, // this will be the default handler, causing the process to be torn down. // It could also be a custom handle registered by other code before us. // In the rare case where the signal is set to be ignored, though, we don't // want to do that, as we know our process will simply remain running yet our // handlers will never end up being invoked again. (It's possible that can // happen as well in the custom case, but we can't detect that or handle it well, // at which point we'll just stop responding to the relevant signal here if the // process does remain alive. We only unregister from the relevant handler, though, // so the handler(s) for the other signal(s) will still remain registered.) if (signalCode == SIGINT) { if (g_origSigIntHandler.sa_handler != SIG_IGN) { sigaction(SIGINT, &g_origSigIntHandler, NULL); kill(getpid(), SIGINT); } } else if (signalCode == SIGQUIT) { if (g_origSigQuitHandler.sa_handler != SIG_IGN) { sigaction(SIGQUIT, &g_origSigQuitHandler, NULL); kill(getpid(), SIGQUIT); } } } } } static void CloseSignalHandlingPipe() { assert(g_signalPipe[0] >= 0); assert(g_signalPipe[1] >= 0); close(g_signalPipe[0]); close(g_signalPipe[1]); g_signalPipe[0] = -1; g_signalPipe[1] = -1; } static bool InitializeSignalHandling() { assert(!g_signalHandlingInitialized); // Create a pipe we'll use to communicate with our worker // thread. We can't do anything interesting in the signal handler, // so we instead send a message to another thread that'll do // the handling work. if (pipe(g_signalPipe) != 0) { return false; } assert(g_signalPipe[0] >= 0); assert(g_signalPipe[1] >= 0); // Create a small object to pass the read end of the pipe to the worker. int* readFdPtr = reinterpret_cast<int*>(malloc(sizeof(int))); if (readFdPtr == nullptr) { CloseSignalHandlingPipe(); errno = ENOMEM; return false; } *readFdPtr = g_signalPipe[0]; // The pipe is created. Create the worker thread. pthread_t handlerThread; if (pthread_create(&handlerThread, nullptr, CtrlHandleLoop, readFdPtr) != 0) { int err = errno; free(readFdPtr); CloseSignalHandlingPipe(); errno = err; return false; } // Finally, register the signal handlers for SIGINT and SIGQUIT. struct sigaction newAction = { .sa_flags = SA_RESTART, .sa_handler = &sigintquit_handler, }; sigemptyset(&newAction.sa_mask); int rv = sigaction(SIGINT, &newAction, &g_origSigIntHandler); assert(rv == 0); rv = sigaction(SIGQUIT, &newAction, &g_origSigQuitHandler); assert(rv == 0); g_signalHandlingInitialized = true; return true; } // TODO: temporarily keeping the un-prefixed signature of this method // to keep tests running in CI. This will be removed once the managed assemblies // are synced up with the native assemblies. extern "C" int32_t RegisterForCtrl(CtrlCallback callback) { return SystemNative_RegisterForCtrl(callback); } extern "C" int32_t SystemNative_RegisterForCtrl(CtrlCallback callback) { assert(callback != nullptr); assert(g_ctrlCallback == nullptr); g_ctrlCallback = callback; if (!g_signalHandlingInitialized && !InitializeSignalHandling()) { g_ctrlCallback = nullptr; return 0; } return 1; } // TODO: temporarily keeping the un-prefixed signature of this method // to keep tests running in CI. This will be removed once the managed assemblies // are synced up with the native assemblies. extern "C" void UnregisterForCtrl() { SystemNative_UnregisterForCtrl(); } extern "C" void SystemNative_UnregisterForCtrl() { assert(g_ctrlCallback != nullptr); g_ctrlCallback = nullptr; // Keep the signal handlers registered and the worker thread // up and running for when registration is done again. } <|endoftext|>
<commit_before>// Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // SemaphoreVk.cpp: Defines the class interface for SemaphoreVk, implementing // SemaphoreImpl. #include "libANGLE/renderer/vulkan/SemaphoreVk.h" #include "common/debug.h" #include "libANGLE/Context.h" #include "libANGLE/renderer/vulkan/BufferVk.h" #include "libANGLE/renderer/vulkan/ContextVk.h" #include "libANGLE/renderer/vulkan/RendererVk.h" #include "libANGLE/renderer/vulkan/TextureVk.h" namespace rx { namespace { vk::ImageLayout GetVulkanImageLayout(GLenum layout) { switch (layout) { case GL_NONE: return vk::ImageLayout::Undefined; case GL_LAYOUT_GENERAL_EXT: return vk::ImageLayout::ExternalShadersWrite; case GL_LAYOUT_COLOR_ATTACHMENT_EXT: return vk::ImageLayout::ColorAttachment; case GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT: case GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT: case GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT: case GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT: // Note: once VK_KHR_separate_depth_stencil_layouts becomes core or ubiquitous, we // should optimize depth/stencil image layout transitions to only be performed on the // aspect that needs transition. In that case, these four layouts can be distinguished // and optimized. Note that the exact equivalent of these layouts are specified in // VK_KHR_maintenance2, which are also usable, granted we transition the pair of // depth/stencil layouts accordingly elsewhere in ANGLE. return vk::ImageLayout::DepthStencilAttachment; case GL_LAYOUT_SHADER_READ_ONLY_EXT: return vk::ImageLayout::ExternalShadersReadOnly; case GL_LAYOUT_TRANSFER_SRC_EXT: return vk::ImageLayout::TransferSrc; case GL_LAYOUT_TRANSFER_DST_EXT: return vk::ImageLayout::TransferDst; default: UNREACHABLE(); return vk::ImageLayout::Undefined; } } } // anonymous namespace SemaphoreVk::SemaphoreVk() = default; SemaphoreVk::~SemaphoreVk() = default; void SemaphoreVk::onDestroy(const gl::Context *context) { ContextVk *contextVk = vk::GetImpl(context); contextVk->addGarbage(&mSemaphore); } angle::Result SemaphoreVk::importFd(gl::Context *context, gl::HandleType handleType, GLint fd) { ContextVk *contextVk = vk::GetImpl(context); switch (handleType) { case gl::HandleType::OpaqueFd: return importOpaqueFd(contextVk, fd); default: ANGLE_VK_UNREACHABLE(contextVk); return angle::Result::Stop; } } angle::Result SemaphoreVk::importZirconHandle(gl::Context *context, gl::HandleType handleType, GLuint handle) { ContextVk *contextVk = vk::GetImpl(context); switch (handleType) { case gl::HandleType::ZirconEvent: return importZirconEvent(contextVk, handle); default: ANGLE_VK_UNREACHABLE(contextVk); return angle::Result::Stop; } } angle::Result SemaphoreVk::wait(gl::Context *context, const gl::BufferBarrierVector &bufferBarriers, const gl::TextureBarrierVector &textureBarriers) { ContextVk *contextVk = vk::GetImpl(context); if (!bufferBarriers.empty() || !textureBarriers.empty()) { // Create one global memory barrier to cover all barriers. ANGLE_TRY(contextVk->syncExternalMemory()); } uint32_t rendererQueueFamilyIndex = contextVk->getRenderer()->getQueueFamilyIndex(); if (!bufferBarriers.empty()) { // Perform a queue ownership transfer for each buffer. for (gl::Buffer *buffer : bufferBarriers) { BufferVk *bufferVk = vk::GetImpl(buffer); vk::BufferHelper &bufferHelper = bufferVk->getBuffer(); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Queue ownership transfer. bufferHelper.acquireFromExternal(contextVk, VK_QUEUE_FAMILY_EXTERNAL, rendererQueueFamilyIndex, &commandBuffer); } } if (!textureBarriers.empty()) { // Perform a queue ownership transfer for each texture. Additionally, we are being // informed that the layout of the image has been externally transitioned, so we need to // update our internal state tracking. for (const gl::TextureAndLayout &textureAndLayout : textureBarriers) { TextureVk *textureVk = vk::GetImpl(textureAndLayout.texture); vk::ImageHelper &image = textureVk->getImage(); vk::ImageLayout layout = GetVulkanImageLayout(textureAndLayout.layout); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Image should not be accessed while unowned. ASSERT(!textureVk->getImage().hasStagedUpdates()); // Queue ownership transfer and layout transition. image.acquireFromExternal(contextVk, VK_QUEUE_FAMILY_EXTERNAL, rendererQueueFamilyIndex, layout, &commandBuffer); } } contextVk->addWaitSemaphore(mSemaphore.getHandle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); return angle::Result::Continue; } angle::Result SemaphoreVk::signal(gl::Context *context, const gl::BufferBarrierVector &bufferBarriers, const gl::TextureBarrierVector &textureBarriers) { ContextVk *contextVk = vk::GetImpl(context); uint32_t rendererQueueFamilyIndex = contextVk->getRenderer()->getQueueFamilyIndex(); if (!bufferBarriers.empty()) { // Perform a queue ownership transfer for each buffer. for (gl::Buffer *buffer : bufferBarriers) { BufferVk *bufferVk = vk::GetImpl(buffer); vk::BufferHelper &bufferHelper = bufferVk->getBuffer(); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Queue ownership transfer. bufferHelper.releaseToExternal(contextVk, rendererQueueFamilyIndex, VK_QUEUE_FAMILY_EXTERNAL, &commandBuffer); } } if (!textureBarriers.empty()) { // Perform a queue ownership transfer for each texture. Additionally, transition the image // to the requested layout. for (const gl::TextureAndLayout &textureAndLayout : textureBarriers) { TextureVk *textureVk = vk::GetImpl(textureAndLayout.texture); vk::ImageHelper &image = textureVk->getImage(); vk::ImageLayout layout = GetVulkanImageLayout(textureAndLayout.layout); // Don't transition to Undefined layout. If external wants to transition the image away // from Undefined after this operation, it's perfectly fine to keep the layout as is in // ANGLE. Note that vk::ImageHelper doesn't expect transitions to Undefined. if (layout == vk::ImageLayout::Undefined) { layout = image.getCurrentImageLayout(); } ANGLE_TRY(textureVk->ensureImageInitialized(contextVk, ImageMipLevels::EnabledLevels)); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Queue ownership transfer and layout transition. image.releaseToExternal(contextVk, rendererQueueFamilyIndex, VK_QUEUE_FAMILY_EXTERNAL, layout, &commandBuffer); } } if (!bufferBarriers.empty() || !textureBarriers.empty()) { // Create one global memory barrier to cover all barriers. ANGLE_TRY(contextVk->syncExternalMemory()); } return contextVk->flushImpl(&mSemaphore); } angle::Result SemaphoreVk::importOpaqueFd(ContextVk *contextVk, GLint fd) { RendererVk *renderer = contextVk->getRenderer(); if (!mSemaphore.valid()) { mSemaphore.init(renderer->getDevice()); } ASSERT(mSemaphore.valid()); VkImportSemaphoreFdInfoKHR importSemaphoreFdInfo = {}; importSemaphoreFdInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR; importSemaphoreFdInfo.semaphore = mSemaphore.getHandle(); importSemaphoreFdInfo.flags = 0; importSemaphoreFdInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT; importSemaphoreFdInfo.fd = fd; ANGLE_VK_TRY(contextVk, vkImportSemaphoreFdKHR(renderer->getDevice(), &importSemaphoreFdInfo)); return angle::Result::Continue; } angle::Result SemaphoreVk::importZirconEvent(ContextVk *contextVk, GLuint handle) { RendererVk *renderer = contextVk->getRenderer(); if (!mSemaphore.valid()) { mSemaphore.init(renderer->getDevice()); } ASSERT(mSemaphore.valid()); VkImportSemaphoreZirconHandleInfoFUCHSIA importSemaphoreZirconHandleInfo = {}; importSemaphoreZirconHandleInfo.sType = VK_STRUCTURE_TYPE_TEMP_IMPORT_SEMAPHORE_ZIRCON_HANDLE_INFO_FUCHSIA; importSemaphoreZirconHandleInfo.semaphore = mSemaphore.getHandle(); importSemaphoreZirconHandleInfo.flags = 0; importSemaphoreZirconHandleInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TEMP_ZIRCON_EVENT_BIT_FUCHSIA; importSemaphoreZirconHandleInfo.handle = handle; // TODO(spang): Add vkImportSemaphoreZirconHandleFUCHSIA to volk. static PFN_vkImportSemaphoreZirconHandleFUCHSIA vkImportSemaphoreZirconHandleFUCHSIA = reinterpret_cast<PFN_vkImportSemaphoreZirconHandleFUCHSIA>( vkGetInstanceProcAddr(renderer->getInstance(), "vkImportSemaphoreZirconHandleFUCHSIA")); ANGLE_VK_TRY(contextVk, vkImportSemaphoreZirconHandleFUCHSIA(renderer->getDevice(), &importSemaphoreZirconHandleInfo)); return angle::Result::Continue; } } // namespace rx <commit_msg>Vulkan: Relax ASSERT in SemaphoreVk::wait()<commit_after>// Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // SemaphoreVk.cpp: Defines the class interface for SemaphoreVk, implementing // SemaphoreImpl. #include "libANGLE/renderer/vulkan/SemaphoreVk.h" #include "common/debug.h" #include "libANGLE/Context.h" #include "libANGLE/renderer/vulkan/BufferVk.h" #include "libANGLE/renderer/vulkan/ContextVk.h" #include "libANGLE/renderer/vulkan/RendererVk.h" #include "libANGLE/renderer/vulkan/TextureVk.h" namespace rx { namespace { vk::ImageLayout GetVulkanImageLayout(GLenum layout) { switch (layout) { case GL_NONE: return vk::ImageLayout::Undefined; case GL_LAYOUT_GENERAL_EXT: return vk::ImageLayout::ExternalShadersWrite; case GL_LAYOUT_COLOR_ATTACHMENT_EXT: return vk::ImageLayout::ColorAttachment; case GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT: case GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT: case GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT: case GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT: // Note: once VK_KHR_separate_depth_stencil_layouts becomes core or ubiquitous, we // should optimize depth/stencil image layout transitions to only be performed on the // aspect that needs transition. In that case, these four layouts can be distinguished // and optimized. Note that the exact equivalent of these layouts are specified in // VK_KHR_maintenance2, which are also usable, granted we transition the pair of // depth/stencil layouts accordingly elsewhere in ANGLE. return vk::ImageLayout::DepthStencilAttachment; case GL_LAYOUT_SHADER_READ_ONLY_EXT: return vk::ImageLayout::ExternalShadersReadOnly; case GL_LAYOUT_TRANSFER_SRC_EXT: return vk::ImageLayout::TransferSrc; case GL_LAYOUT_TRANSFER_DST_EXT: return vk::ImageLayout::TransferDst; default: UNREACHABLE(); return vk::ImageLayout::Undefined; } } } // anonymous namespace SemaphoreVk::SemaphoreVk() = default; SemaphoreVk::~SemaphoreVk() = default; void SemaphoreVk::onDestroy(const gl::Context *context) { ContextVk *contextVk = vk::GetImpl(context); contextVk->addGarbage(&mSemaphore); } angle::Result SemaphoreVk::importFd(gl::Context *context, gl::HandleType handleType, GLint fd) { ContextVk *contextVk = vk::GetImpl(context); switch (handleType) { case gl::HandleType::OpaqueFd: return importOpaqueFd(contextVk, fd); default: ANGLE_VK_UNREACHABLE(contextVk); return angle::Result::Stop; } } angle::Result SemaphoreVk::importZirconHandle(gl::Context *context, gl::HandleType handleType, GLuint handle) { ContextVk *contextVk = vk::GetImpl(context); switch (handleType) { case gl::HandleType::ZirconEvent: return importZirconEvent(contextVk, handle); default: ANGLE_VK_UNREACHABLE(contextVk); return angle::Result::Stop; } } angle::Result SemaphoreVk::wait(gl::Context *context, const gl::BufferBarrierVector &bufferBarriers, const gl::TextureBarrierVector &textureBarriers) { ContextVk *contextVk = vk::GetImpl(context); if (!bufferBarriers.empty() || !textureBarriers.empty()) { // Create one global memory barrier to cover all barriers. ANGLE_TRY(contextVk->syncExternalMemory()); } uint32_t rendererQueueFamilyIndex = contextVk->getRenderer()->getQueueFamilyIndex(); if (!bufferBarriers.empty()) { // Perform a queue ownership transfer for each buffer. for (gl::Buffer *buffer : bufferBarriers) { BufferVk *bufferVk = vk::GetImpl(buffer); vk::BufferHelper &bufferHelper = bufferVk->getBuffer(); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Queue ownership transfer. bufferHelper.acquireFromExternal(contextVk, VK_QUEUE_FAMILY_EXTERNAL, rendererQueueFamilyIndex, &commandBuffer); } } if (!textureBarriers.empty()) { // Perform a queue ownership transfer for each texture. Additionally, we are being // informed that the layout of the image has been externally transitioned, so we need to // update our internal state tracking. for (const gl::TextureAndLayout &textureAndLayout : textureBarriers) { TextureVk *textureVk = vk::GetImpl(textureAndLayout.texture); vk::ImageHelper &image = textureVk->getImage(); vk::ImageLayout layout = GetVulkanImageLayout(textureAndLayout.layout); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Image should not be accessed while unowned. Emulated formats may have staged updates // to clear the image after initialization. ASSERT(!image.hasStagedUpdates() || image.getFormat().hasEmulatedImageChannels()); // Queue ownership transfer and layout transition. image.acquireFromExternal(contextVk, VK_QUEUE_FAMILY_EXTERNAL, rendererQueueFamilyIndex, layout, &commandBuffer); } } contextVk->addWaitSemaphore(mSemaphore.getHandle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); return angle::Result::Continue; } angle::Result SemaphoreVk::signal(gl::Context *context, const gl::BufferBarrierVector &bufferBarriers, const gl::TextureBarrierVector &textureBarriers) { ContextVk *contextVk = vk::GetImpl(context); uint32_t rendererQueueFamilyIndex = contextVk->getRenderer()->getQueueFamilyIndex(); if (!bufferBarriers.empty()) { // Perform a queue ownership transfer for each buffer. for (gl::Buffer *buffer : bufferBarriers) { BufferVk *bufferVk = vk::GetImpl(buffer); vk::BufferHelper &bufferHelper = bufferVk->getBuffer(); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Queue ownership transfer. bufferHelper.releaseToExternal(contextVk, rendererQueueFamilyIndex, VK_QUEUE_FAMILY_EXTERNAL, &commandBuffer); } } if (!textureBarriers.empty()) { // Perform a queue ownership transfer for each texture. Additionally, transition the image // to the requested layout. for (const gl::TextureAndLayout &textureAndLayout : textureBarriers) { TextureVk *textureVk = vk::GetImpl(textureAndLayout.texture); vk::ImageHelper &image = textureVk->getImage(); vk::ImageLayout layout = GetVulkanImageLayout(textureAndLayout.layout); // Don't transition to Undefined layout. If external wants to transition the image away // from Undefined after this operation, it's perfectly fine to keep the layout as is in // ANGLE. Note that vk::ImageHelper doesn't expect transitions to Undefined. if (layout == vk::ImageLayout::Undefined) { layout = image.getCurrentImageLayout(); } ANGLE_TRY(textureVk->ensureImageInitialized(contextVk, ImageMipLevels::EnabledLevels)); vk::CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer(); // Queue ownership transfer and layout transition. image.releaseToExternal(contextVk, rendererQueueFamilyIndex, VK_QUEUE_FAMILY_EXTERNAL, layout, &commandBuffer); } } if (!bufferBarriers.empty() || !textureBarriers.empty()) { // Create one global memory barrier to cover all barriers. ANGLE_TRY(contextVk->syncExternalMemory()); } return contextVk->flushImpl(&mSemaphore); } angle::Result SemaphoreVk::importOpaqueFd(ContextVk *contextVk, GLint fd) { RendererVk *renderer = contextVk->getRenderer(); if (!mSemaphore.valid()) { mSemaphore.init(renderer->getDevice()); } ASSERT(mSemaphore.valid()); VkImportSemaphoreFdInfoKHR importSemaphoreFdInfo = {}; importSemaphoreFdInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR; importSemaphoreFdInfo.semaphore = mSemaphore.getHandle(); importSemaphoreFdInfo.flags = 0; importSemaphoreFdInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT; importSemaphoreFdInfo.fd = fd; ANGLE_VK_TRY(contextVk, vkImportSemaphoreFdKHR(renderer->getDevice(), &importSemaphoreFdInfo)); return angle::Result::Continue; } angle::Result SemaphoreVk::importZirconEvent(ContextVk *contextVk, GLuint handle) { RendererVk *renderer = contextVk->getRenderer(); if (!mSemaphore.valid()) { mSemaphore.init(renderer->getDevice()); } ASSERT(mSemaphore.valid()); VkImportSemaphoreZirconHandleInfoFUCHSIA importSemaphoreZirconHandleInfo = {}; importSemaphoreZirconHandleInfo.sType = VK_STRUCTURE_TYPE_TEMP_IMPORT_SEMAPHORE_ZIRCON_HANDLE_INFO_FUCHSIA; importSemaphoreZirconHandleInfo.semaphore = mSemaphore.getHandle(); importSemaphoreZirconHandleInfo.flags = 0; importSemaphoreZirconHandleInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TEMP_ZIRCON_EVENT_BIT_FUCHSIA; importSemaphoreZirconHandleInfo.handle = handle; // TODO(spang): Add vkImportSemaphoreZirconHandleFUCHSIA to volk. static PFN_vkImportSemaphoreZirconHandleFUCHSIA vkImportSemaphoreZirconHandleFUCHSIA = reinterpret_cast<PFN_vkImportSemaphoreZirconHandleFUCHSIA>( vkGetInstanceProcAddr(renderer->getInstance(), "vkImportSemaphoreZirconHandleFUCHSIA")); ANGLE_VK_TRY(contextVk, vkImportSemaphoreZirconHandleFUCHSIA(renderer->getDevice(), &importSemaphoreZirconHandleInfo)); return angle::Result::Continue; } } // namespace rx <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ignoreBaFa_ja_JP.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2003-05-21 08:05:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_BaFa_ja_JP #include <transliteration_Ignore.hxx> using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { static Mapping BaFa[] = { { 0x30F4, 0x30A1, 0x30D0, sal_True }, { 0x3094, 0x3041, 0x3070, sal_True }, { 0x30D5, 0x30A1, 0x30CF, sal_True }, { 0x3075, 0x3041, 0x306F, sal_True }, { 0, 0, 0, sal_True } }; ignoreBaFa_ja_JP::ignoreBaFa_ja_JP() { func = (TransFunc) 0; table = 0; map = BaFa; transliterationName = "ignoreBaFa_ja_JP"; implementationName = "com.sun.star.i18n.Transliteration.ignoreBaFa_ja_JP"; } } } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.7.180); FILE MERGED 2005/09/05 17:47:54 rt 1.7.180.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ignoreBaFa_ja_JP.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:27:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_BaFa_ja_JP #include <transliteration_Ignore.hxx> using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { static Mapping BaFa[] = { { 0x30F4, 0x30A1, 0x30D0, sal_True }, { 0x3094, 0x3041, 0x3070, sal_True }, { 0x30D5, 0x30A1, 0x30CF, sal_True }, { 0x3075, 0x3041, 0x306F, sal_True }, { 0, 0, 0, sal_True } }; ignoreBaFa_ja_JP::ignoreBaFa_ja_JP() { func = (TransFunc) 0; table = 0; map = BaFa; transliterationName = "ignoreBaFa_ja_JP"; implementationName = "com.sun.star.i18n.Transliteration.ignoreBaFa_ja_JP"; } } } } } <|endoftext|>
<commit_before>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #ifdef HAS_VTK #include <irtkImage.h> #include <irtkGaussianBlurring.h> #include <irtkResampling.h> // vtk includes #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataWriter.h> //#include <vtkDecimate.h> #include <vtkDecimatePro.h> #include <vtkSmoothPolyDataFilter.h> #include <vtkMarchingCubes.h> #include <vtkPolyDataNormals.h> char *input_name, *output_name; void usage() { cerr << "Usage: mcubes [image] [polydata] [threshold] <-decimate> <-smooth iterations> <-normals on|off> <-gradients on|off> <-blur sigma> <-isotropic> <-size x y z> <-ascii> <-sepsuf> <-rmatr> \n"<<endl; cerr << "<-close put blank slices on all direction so a set of closed surface will be generated> \n"<<endl; cerr << "<-close_x put blank slices on x direction> \n"<<endl; cerr << "<-close_y put blank slices on y direction> \n"<<endl; cerr << "<-close_z put blank slices on z direction> \n"<<endl; exit(1); } int main(int argc, char **argv) { int ok, i, j, k, t, bASCII = false,rmatr,iterations; int cx,cy,cz; float threshold; double xaxis[3], yaxis[3], zaxis[3], point[3]; irtkPoint origin; vtkDecimatePro *decimate = NULL; vtkSmoothPolyDataFilter *smooth = NULL; rmatr = 0; cx = 0; cy = 0; cz = 0; iterations = 10; if (argc < 4) { usage(); } // Parse parameters input_name = argv[1]; argv++; argc--; output_name = argv[1]; argv++; argc--; threshold = atof(argv[1]); argv++; argc--; // Read image irtkRealImage image; image.Read(input_name); // Set up marching cubes filter vtkMarchingCubes *mcubes = vtkMarchingCubes::New(); mcubes->SetValue(0, threshold); mcubes->ComputeNormalsOn(); mcubes->ComputeGradientsOff(); // Parse remaining arguments while (argc > 1) { ok = false; if ((!ok) && (strcmp(argv[1], "-decimate") == 0)) { argc--; argv++; decimate = vtkDecimatePro::New(); ok = true; } if ((!ok) && (strcmp(argv[1], "-smooth") == 0)) { argc--; argv++; smooth = vtkSmoothPolyDataFilter::New(); iterations = atoi(argv[1]); argc--; argv++; ok = true; } if ((!ok) && (strcmp(argv[1], "-rmatr") == 0)) { argc--; argv++; rmatr = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close") == 0)) { argc--; argv++; cx = 1; cy = 1; cz = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close_x") == 0)) { argc--; argv++; cx = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close_y") == 0)) { argc--; argv++; cy = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close_z") == 0)) { argc--; argv++; cz = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-gradients") == 0) && (strcmp(argv[2], "on") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeGradientsOn(); ok = true; } if ((!ok) && (strcmp(argv[1], "-gradients") == 0) && (strcmp(argv[2], "off") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeGradientsOff(); ok = true; } if ((!ok) && (strcmp(argv[1], "-normals") == 0) && (strcmp(argv[2], "on") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeNormalsOn(); ok = true; } if ((!ok) && (strcmp(argv[1], "-normals") == 0) && (strcmp(argv[2], "off") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeNormalsOff(); ok = true; } if ((!ok) && (strcmp(argv[1], "-blur") == 0)) { argc--; argv++; // Blur image cerr << "Blurring image with sigma = " << atof(argv[1]) << endl; irtkGaussianBlurring<irtkRealPixel> gaussianBlurring(atof(argv[1])); gaussianBlurring.SetInput (&image); gaussianBlurring.SetOutput(&image); gaussianBlurring.Run(); argc--; argv++; ok = true; } if ((!ok) && (strcmp(argv[1], "-isotropic") == 0)) { argc--; argv++; // Resample image to isotropic voxels (smalles voxel dimension) double xsize, ysize, zsize, size; image.GetPixelSize(&xsize, &ysize, &zsize); size = xsize; size = (size < ysize) ? size : ysize; size = (size < zsize) ? size : zsize; cerr << "Resampling image to isotropic voxel size (in mm): " << size << endl; irtkResampling<irtkRealPixel> resampling(size, size, size); irtkLinearInterpolateImageFunction interpolator; resampling.SetInput (&image); resampling.SetOutput(&image); resampling.SetInterpolator(&interpolator); resampling.Run(); ok = true; } if ((!ok) && (strcmp(argv[1], "-size") == 0)) { argc--; argv++; // Resample image cerr << "Resampling image to voxel size (in mm): " << atof(argv[1]) << "," << atof(argv[2]) << "," << atof(argv[3]) << endl; irtkResampling<irtkRealPixel> resampling(atof(argv[1]), atof(argv[2]), atof(argv[3])); irtkLinearInterpolateImageFunction interpolator; resampling.SetInput (&image); resampling.SetOutput(&image); resampling.SetInterpolator(&interpolator); resampling.Run(); argc -= 3; argv += 3; ok = true; } if ((!ok) && (strcmp(argv[1], "-ascii") == 0)) { argc--; argv++; bASCII = true; ok = true; } if ((!ok) && (strcmp(argv[1], "-sepsuf") == 0)) { mcubes->SetNumberOfContours(2); mcubes->SetValue(1, threshold+0.1); } if (!ok) { cerr << "Cannot parse argument " << argv[1] << endl; usage(); } } // Convert image to VTK, taking the differences in vtk/irtk image geometry into account vtkStructuredPoints *vtkimage = vtkStructuredPoints::New(); if(rmatr == 1){ irtkImageAttributes tmpatr; image.PutOrientation(tmpatr._xaxis,tmpatr._yaxis,tmpatr._zaxis); image.PutOrigin(tmpatr._xorigin,tmpatr._yorigin,tmpatr._zorigin); } irtkRealImage dummy; irtkImageAttributes attr = image.GetImageAttributes(); attr._x += 2*cx; attr._y += 2*cy; attr._z += 2*cz; dummy.Initialize(attr); for(i=0; i<dummy.GetX();i++) for(j=0; j<dummy.GetY();j++) for(k=0; k<dummy.GetZ();k++){ dummy.Put(i,j,k,threshold-10.0); } for(i=0; i<image.GetX();i++) for(j=0; j<image.GetY();j++) for(k=0; k<image.GetZ();k++) { dummy.Put(i+cx,j+cy,k+cz,image.Get(i,j,k)); } xaxis[0] = 1; xaxis[1] = 0; xaxis[2] = 0; yaxis[0] = 0; yaxis[1] = 1; yaxis[2] = 0; zaxis[0] = 0; zaxis[1] = 0; zaxis[2] = 1; dummy.PutPixelSize(1, 1, 1); dummy.PutOrientation(xaxis, yaxis, zaxis); dummy.ImageToVTK(vtkimage); // Set as input to MC mcubes->SetInput(vtkimage); // Specify output vtkPolyData *output = NULL; // Let's go to work if (decimate != NULL) { cout << "Decimating ... \n"; decimate->SetInputConnection(mcubes->GetOutputPort()); if (smooth != NULL) { cout << "Smoothing ... \n"; smooth->SetInputConnection(decimate->GetOutputPort()); smooth->SetNumberOfIterations(iterations); output = smooth->GetOutput(); } else { output = decimate->GetOutput(); } } else if (smooth != NULL) { cout << "Smoothing ... \n"; smooth->SetNumberOfIterations(iterations); smooth->SetInputConnection(mcubes->GetOutputPort()); output = smooth->GetOutput(); } else { output = mcubes->GetOutput(); } output->Update(); // just in case // Now transform between vtk and image coordinate systems for (i = 0; i < output->GetNumberOfPoints(); i++) { output->GetPoint(i, point); dummy.WorldToImage(point[0], point[1], point[2]); point[2] = point[2] - cz; point[1] = point[1] - cy; point[0] = point[0] - cx; image.ImageToWorld(point[0], point[1], point[2]); output->GetPoints()->SetPoint(i, point); } output->Modified(); // Recalculate normals, if applicable if (output->GetPointData()->GetNormals() != NULL) { vtkPolyDataNormals *filter = vtkPolyDataNormals::New(); filter->SetInput(output); filter->Update(); // absolutely necessary! output->GetPointData()->SetNormals(filter->GetOutput()->GetPointData()->GetNormals()); filter->Delete(); // be good } // Write result vtkPolyDataWriter *writer = vtkPolyDataWriter::New(); writer->SetInput(output); writer->SetFileName(output_name); if (!bASCII) { writer->SetFileTypeToBinary(); } writer->Write(); // Be good if (smooth != NULL) { smooth->Delete(); } if (decimate != NULL) { decimate->Delete(); } vtkimage->Delete(); mcubes->Delete(); writer->Delete(); return 0; } #else #include <irtkImage.h> int main( int argc, char *argv[] ) { cerr << argv[0] << " this program needs to be compiled with vtk enabled." << endl; return 0; } #endif <commit_msg>Re-wrote usage and other cosmetic changes.<commit_after>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #ifdef HAS_VTK #include <irtkImage.h> #include <irtkGaussianBlurring.h> #include <irtkResampling.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataWriter.h> #include <vtkDecimatePro.h> #include <vtkSmoothPolyDataFilter.h> #include <vtkMarchingCubes.h> #include <vtkPolyDataNormals.h> char *input_name, *output_name; void usage() { cerr << " Usage: mcubes [image] [polydata] [threshold] <options>\n" << endl; cerr << " Run a marching cubes filter on a an image at a given threshold" << endl; cerr << " in order to generate a VTK surface mesh of the boundary.\n" << endl; cerr << " Where <options> are one or more of the following:" << endl; cerr << " <-blur> sigma Blur input image with kernel size sigma before running filter." << endl; cerr << " <-size> x y z Resample image to the given voxel size before running." << endl; cerr << " <-isotropic> Resample image to an isotropic voxel size (minimum of input" << endl; cerr << " voxel x, y and z dimensions)" << endl; cerr << " <-decimate> Decimate the vertices in the output surface." << endl; cerr << " <-smooth> iterations Apply a number of iterations of (Laplacian) smoothing to " << endl; cerr << " the resulting surface." << endl; cerr << " <-normals> on|off Choose whether to generate normals (default) or not." << endl; cerr << " <-gradients> on|off Choose whether to generate gradients or not (default)." << endl; cerr << " <-ascii> Write output mesh in ASCII format (default: binary)." << endl; cerr << " <-sepSurfs> Genarate surfaces for two contours." << endl; cerr << " <-ignoreGeom> Ignore the geometry of the given image (orientation etc)." << endl; cerr << " <-close> Put zeros around the image to generate a closed surface(s)."<<endl; cerr << " <-close_x> Close in x direction only."<<endl; cerr << " <-close_y> Close in y direction only."<<endl; cerr << " <-close_z> Close in z direction only."<<endl; cerr << " " << endl; exit(1); } int main(int argc, char **argv) { int ok, i, j, k, bASCII = false, ignoreGeometry, iterations; int cx,cy,cz; float threshold; double xaxis[3], yaxis[3], zaxis[3], point[3]; irtkPoint origin; vtkDecimatePro *decimate = NULL; vtkSmoothPolyDataFilter *smooth = NULL; ignoreGeometry = 0; cx = 0; cy = 0; cz = 0; iterations = 10; if (argc < 4) { usage(); } // Parse parameters input_name = argv[1]; argv++; argc--; output_name = argv[1]; argv++; argc--; threshold = atof(argv[1]); argv++; argc--; // Read image irtkRealImage image; image.Read(input_name); // Set up marching cubes filter vtkMarchingCubes *mcubes = vtkMarchingCubes::New(); mcubes->SetValue(0, threshold); mcubes->ComputeNormalsOn(); mcubes->ComputeGradientsOff(); // Parse remaining arguments while (argc > 1) { ok = false; if ((!ok) && (strcmp(argv[1], "-decimate") == 0)) { argc--; argv++; decimate = vtkDecimatePro::New(); ok = true; } if ((!ok) && (strcmp(argv[1], "-smooth") == 0)) { argc--; argv++; smooth = vtkSmoothPolyDataFilter::New(); iterations = atoi(argv[1]); argc--; argv++; ok = true; } if ((!ok) && (strcmp(argv[1], "-ignoreGeom") == 0)) { argc--; argv++; ignoreGeometry = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close") == 0)) { argc--; argv++; cx = 1; cy = 1; cz = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close_x") == 0)) { argc--; argv++; cx = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close_y") == 0)) { argc--; argv++; cy = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-close_z") == 0)) { argc--; argv++; cz = 1; ok = true; } if ((!ok) && (strcmp(argv[1], "-gradients") == 0) && (strcmp(argv[2], "on") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeGradientsOn(); ok = true; } if ((!ok) && (strcmp(argv[1], "-gradients") == 0) && (strcmp(argv[2], "off") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeGradientsOff(); ok = true; } if ((!ok) && (strcmp(argv[1], "-normals") == 0) && (strcmp(argv[2], "on") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeNormalsOn(); ok = true; } if ((!ok) && (strcmp(argv[1], "-normals") == 0) && (strcmp(argv[2], "off") == 0)) { argc--; argv++; argc--; argv++; mcubes->ComputeNormalsOff(); ok = true; } if ((!ok) && (strcmp(argv[1], "-blur") == 0)) { argc--; argv++; // Blur image cerr << "Blurring image with sigma = " << atof(argv[1]) << endl; irtkGaussianBlurring<irtkRealPixel> gaussianBlurring(atof(argv[1])); gaussianBlurring.SetInput (&image); gaussianBlurring.SetOutput(&image); gaussianBlurring.Run(); argc--; argv++; ok = true; } if ((!ok) && (strcmp(argv[1], "-isotropic") == 0)) { argc--; argv++; // Resample image to isotropic voxels (smalles voxel dimension) double xsize, ysize, zsize, size; image.GetPixelSize(&xsize, &ysize, &zsize); size = xsize; size = (size < ysize) ? size : ysize; size = (size < zsize) ? size : zsize; cerr << "Resampling image to isotropic voxel size (in mm): " << size << endl; irtkResampling<irtkRealPixel> resampling(size, size, size); irtkLinearInterpolateImageFunction interpolator; resampling.SetInput (&image); resampling.SetOutput(&image); resampling.SetInterpolator(&interpolator); resampling.Run(); ok = true; } if ((!ok) && (strcmp(argv[1], "-size") == 0)) { argc--; argv++; // Resample image cerr << "Resampling image to voxel size (in mm): " << atof(argv[1]) << "," << atof(argv[2]) << "," << atof(argv[3]) << endl; irtkResampling<irtkRealPixel> resampling(atof(argv[1]), atof(argv[2]), atof(argv[3])); irtkLinearInterpolateImageFunction interpolator; resampling.SetInput (&image); resampling.SetOutput(&image); resampling.SetInterpolator(&interpolator); resampling.Run(); argc -= 3; argv += 3; ok = true; } if ((!ok) && (strcmp(argv[1], "-ascii") == 0)) { argc--; argv++; bASCII = true; ok = true; } if ((!ok) && (strcmp(argv[1], "-sepSurfs") == 0)) { mcubes->SetNumberOfContours(2); mcubes->SetValue(1, threshold+0.1); } if (!ok) { cerr << "Cannot parse argument " << argv[1] << endl; usage(); } } // Convert image to VTK, taking the differences in vtk/irtk image geometry into account vtkStructuredPoints *vtkimage = vtkStructuredPoints::New(); if(ignoreGeometry == 1){ irtkImageAttributes tmpatr; image.PutOrientation(tmpatr._xaxis,tmpatr._yaxis,tmpatr._zaxis); image.PutOrigin(tmpatr._xorigin,tmpatr._yorigin,tmpatr._zorigin); } irtkRealImage dummy; irtkImageAttributes attr = image.GetImageAttributes(); attr._x += 2*cx; attr._y += 2*cy; attr._z += 2*cz; dummy.Initialize(attr); for(i=0; i<dummy.GetX();i++) for(j=0; j<dummy.GetY();j++) for(k=0; k<dummy.GetZ();k++){ dummy.Put(i,j,k,threshold-10.0); } for(i=0; i<image.GetX();i++) for(j=0; j<image.GetY();j++) for(k=0; k<image.GetZ();k++) { dummy.Put(i+cx,j+cy,k+cz,image.Get(i,j,k)); } xaxis[0] = 1; xaxis[1] = 0; xaxis[2] = 0; yaxis[0] = 0; yaxis[1] = 1; yaxis[2] = 0; zaxis[0] = 0; zaxis[1] = 0; zaxis[2] = 1; dummy.PutPixelSize(1, 1, 1); dummy.PutOrientation(xaxis, yaxis, zaxis); dummy.ImageToVTK(vtkimage); // Set as input to MC mcubes->SetInput(vtkimage); // Specify output vtkPolyData *output = NULL; // Let's go to work if (decimate != NULL) { cout << "Decimating ... \n"; decimate->SetInputConnection(mcubes->GetOutputPort()); if (smooth != NULL) { cout << "Smoothing ... \n"; smooth->SetInputConnection(decimate->GetOutputPort()); smooth->SetNumberOfIterations(iterations); output = smooth->GetOutput(); } else { output = decimate->GetOutput(); } } else if (smooth != NULL) { cout << "Smoothing ... \n"; smooth->SetNumberOfIterations(iterations); smooth->SetInputConnection(mcubes->GetOutputPort()); output = smooth->GetOutput(); } else { output = mcubes->GetOutput(); } output->Update(); // Now transform between vtk and image coordinate systems for (i = 0; i < output->GetNumberOfPoints(); i++) { output->GetPoint(i, point); dummy.WorldToImage(point[0], point[1], point[2]); point[0] = point[0] - cx; point[1] = point[1] - cy; point[2] = point[2] - cz; image.ImageToWorld(point[0], point[1], point[2]); output->GetPoints()->SetPoint(i, point); } output->Modified(); // Recalculate normals, if applicable if (output->GetPointData()->GetNormals() != NULL) { vtkPolyDataNormals *filter = vtkPolyDataNormals::New(); filter->SetInput(output); filter->Update(); // absolutely necessary! output->GetPointData()->SetNormals(filter->GetOutput()->GetPointData()->GetNormals()); filter->Delete(); } // Write result vtkPolyDataWriter *writer = vtkPolyDataWriter::New(); writer->SetInput(output); writer->SetFileName(output_name); if (!bASCII) { writer->SetFileTypeToBinary(); } writer->Write(); // Be good if (smooth != NULL) { smooth->Delete(); } if (decimate != NULL) { decimate->Delete(); } vtkimage->Delete(); mcubes->Delete(); writer->Delete(); return 0; } #else #include <irtkImage.h> int main( int argc, char *argv[] ) { cerr << argv[0] << " this program needs to be compiled with vtk enabled." << endl; return 0; } #endif <|endoftext|>
<commit_before>// // OCCAM // // Copyright (c) 2011-2016, SRI International // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of SRI International nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "llvm/ADT/StringMap.h" #include "llvm/IR/User.h" #include "llvm/IR/InstVisitor.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/CallSite.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" #include "PrevirtualizeInterfaces.h" #include "Specializer.h" #include "ArgIterator.h" #include <vector> #include <string> #include <stdio.h> #define DUMP 1 using namespace llvm; namespace previrt { static Instruction* applyRewriteToCall(Module& M, const CallRewrite* const rw, CallSite cs) { Function* target = cs.getCalledFunction(); assert(target != NULL); Function* newTarget = M.getFunction(rw->function); if (newTarget == NULL) { // There isn't a function, we need to construct it FunctionType* newType = target->getFunctionType(); std::vector<Type*> argTypes; for (std::vector<unsigned>::const_iterator i = rw->args.begin(), e = rw->args.end(); i != e; ++i) argTypes.push_back(newType->getParamType(*i)); ArrayRef<Type*> params(argTypes); newType = FunctionType::get(target->getReturnType(), params, target->isVarArg()); newTarget = dyn_cast<Function> (M.getOrInsertFunction(rw->function, newType)); } assert(newTarget != NULL); return specializeCallSite(cs.getInstruction(), newTarget, rw->args); } static bool vector_in(const std::vector<unsigned>& x, unsigned in) { for (std::vector<unsigned>::const_iterator i = x.begin(), e = x.end(); i != e; ++i) { if (*i == in) return true; } return false; } bool TransformComponentWithUse(Module& M, ComponentInterfaceTransform& T) { bool modified = false; for (ComponentInterfaceTransform::FMap::const_iterator i = T.rewrites.begin(), e = T.rewrites.end(); i != e; ++i) { errs() << "Looking for calls to " << i->first << "\n"; Function* f = M.getFunction(i->first); if (f == NULL) continue; for (Function::use_iterator ui = f->use_begin(), ue = f->use_end(); ui != ue; ++ui) { //Use* U = &(*ui); User* U = ui->getUser(); //<IAM> CallInst *ci; ci = dyn_cast<CallInst>(U); if (ci != NULL){ errs() << "ci = " << ci << "\n"; } else { errs() << "no luck with " << U << "\n"; } //</IAM> if ((!isa<CallInst>(U) && !isa<InvokeInst>(U)) // iam: prevents compilation currently || !CallSite(cast<Instruction>(U)).isCallee(U) ) { // Not a call, or being used as a parameter rather than as the callee. } else { // The instruction is a call site CallSite cs(cast<Instruction>(U)); const CallRewrite* const rw = T.lookupRewrite(i->first, cs.arg_begin(), cs.arg_end()); if (rw == NULL) continue; #if DUMP BasicBlock* owner = cs.getInstruction()->getParent(); errs() << "Specializing (inter-module) call to '" << cs.getCalledFunction()->getName() << "' in function '" << (owner == NULL ? "??" : owner->getParent()->getName()) << "' on arguments ["; for (unsigned int i = 0, cnt = 0; i < cs.arg_size(); ++i) { if (!vector_in(rw->args, i)) { if (cnt++ != 0) errs() << ","; errs() << i << "=(" << *cs.getArgument(i) << ")"; } } errs() << "]\n"; #endif Instruction* newInst = applyRewriteToCall(M, rw, cs); llvm::ReplaceInstWithInst(cs.getInstruction(), newInst); modified = true; } } } return modified; } /* * Rewrite the given module according to the ComponentInterfaceTransformer. */ bool TransformComponentWithoutUse(Module& M, ComponentInterfaceTransform& T) { assert(T.interface != NULL); bool modified = false; for (Module::iterator f = M.begin(), e = M.end(); f != e; ++f) { for (Function::iterator bb = f->begin(), bbe = f->end(); bb != bbe; ++bb) { for (BasicBlock::iterator I = bb->begin(), E = bb->end(); I != E; ++I) { // TODO: Handle the operands CallSite call; if (CallInst* ci = dyn_cast<CallInst>(&*I)) { if (ci->isInlineAsm()) continue; call = CallSite(ci); } else if (InvokeInst* ci = dyn_cast<InvokeInst>(&*I)) { call = CallSite(ci); } else { // TODO: We need to find all references, including ones stored in variables // we'll be conservative and say that if it is stored in a variable then // we can't optimize it at all continue; } Function* target = call.getCalledFunction(); if (target == NULL || !target->isDeclaration()) { continue; } //iam const CallRewrite* const rw = T.lookupRewrite(target->getNameStr(), call.arg_begin(), call.arg_end()); const CallRewrite* const rw = T.lookupRewrite(target->getName().str(), call.arg_begin(), call.arg_end()); if (rw == NULL) { // There is no rewrite for this function continue; } // Get/Create the function Function* newTarget = M.getFunction(rw->function); if (newTarget == NULL) { // There isn't a function, we need to construct it FunctionType* newType = target->getFunctionType(); std::vector<Type*> argTypes; for (std::vector<unsigned>::const_iterator i = rw->args.begin(), e = rw->args.end(); i != e; ++i) argTypes.push_back(newType->getParamType(*i)); ArrayRef<Type*> params(argTypes); newType = FunctionType::get(target->getReturnType(), params, target->isVarArg()); newTarget = dyn_cast<Function> (M.getOrInsertFunction(rw->function, newType)); } assert(newTarget != NULL); Instruction* newInst = specializeCallSite(I, newTarget, rw->args); llvm::ReplaceInstWithInst(bb->getInstList(), I, newInst); modified = true; } } } return modified; } bool TransformComponent(Module& M, ComponentInterfaceTransform& T) { return TransformComponentWithUse(M, T); } static cl::list<std::string> RewriteComponentInput("Prewrite-input", cl::NotHidden, cl::desc( "specifies the interface to rewrite using")); class RewriteComponentPass : public ModulePass { public: ComponentInterfaceTransform transform; static char ID; public: RewriteComponentPass() : ModulePass(ID), transform() { errs() << "RewriteComponentPass()\n"; for (cl::list<std::string>::const_iterator b = RewriteComponentInput.begin(), e = RewriteComponentInput.end(); b != e; ++b) { errs() << "Reading file '" << *b << "'..."; if (transform.readTransformFromFile(*b)) { errs() << "success\n"; } else { errs() << "failed\n"; } } transform.dump(); errs() << "Done reading (" << transform.rewriteCount() << " rewrites)\n"; } virtual ~RewriteComponentPass() { } public: virtual bool runOnModule(Module& M) { if (this->transform.interface == NULL) { return false; } errs() << "RewriteComponentPass:runOnModule: " << M.getModuleIdentifier() << "\n"; bool modified = TransformComponent(M, this->transform); if (modified) { errs() << "...progress...\n"; } else { errs() << "...no progress...\n"; } return modified; } }; char RewriteComponentPass::ID; static RegisterPass<RewriteComponentPass> X("Prewrite", "previrtualize the given module (requires parameters)", false, false); } <commit_msg>RewriteComponent works again...<commit_after>// // OCCAM // // Copyright (c) 2011-2016, SRI International // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of SRI International nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "llvm/ADT/StringMap.h" #include "llvm/IR/User.h" #include "llvm/IR/InstVisitor.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/CallSite.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" #include "PrevirtualizeInterfaces.h" #include "Specializer.h" #include "ArgIterator.h" #include <vector> #include <string> #include <stdio.h> #define DUMP 1 using namespace llvm; namespace previrt { static Instruction* applyRewriteToCall(Module& M, const CallRewrite* const rw, CallSite cs) { Function* target = cs.getCalledFunction(); assert(target != NULL); Function* newTarget = M.getFunction(rw->function); if (newTarget == NULL) { // There isn't a function, we need to construct it FunctionType* newType = target->getFunctionType(); std::vector<Type*> argTypes; for (std::vector<unsigned>::const_iterator i = rw->args.begin(), e = rw->args.end(); i != e; ++i) argTypes.push_back(newType->getParamType(*i)); ArrayRef<Type*> params(argTypes); newType = FunctionType::get(target->getReturnType(), params, target->isVarArg()); newTarget = dyn_cast<Function> (M.getOrInsertFunction(rw->function, newType)); } assert(newTarget != NULL); return specializeCallSite(cs.getInstruction(), newTarget, rw->args); } static bool vector_in(const std::vector<unsigned>& x, unsigned in) { for (std::vector<unsigned>::const_iterator i = x.begin(), e = x.end(); i != e; ++i) { if (*i == in) return true; } return false; } bool TransformComponentWithUse(Module& M, ComponentInterfaceTransform& T) { bool modified = false; for (ComponentInterfaceTransform::FMap::const_iterator i = T.rewrites.begin(), e = T.rewrites.end(); i != e; ++i) { errs() << "Looking for calls to " << i->first << "\n"; Function* f = M.getFunction(i->first); if (f == NULL) continue; for (Function::use_iterator ui = f->use_begin(), ue = f->use_end(); ui != ue; ++ui) { Use* use = &(*ui); User* user = ui->getUser(); if (isa<CallInst>(user) || isa<InvokeInst>(user)) { // The instruction is a call site CallSite cs(cast<Instruction>(user)); // If we are not the callee we should bail if( ! cs.isCallee(use)){ continue; } const CallRewrite* const rw = T.lookupRewrite(i->first, cs.arg_begin(), cs.arg_end()); if (rw == NULL){ continue; } #if DUMP BasicBlock* owner = cs.getInstruction()->getParent(); errs() << "Specializing (inter-module) call to '" << cs.getCalledFunction()->getName() << "' in function '" << (owner == NULL ? "??" : owner->getParent()->getName()) << "' on arguments ["; for (unsigned int i = 0, cnt = 0; i < cs.arg_size(); ++i) { if (!vector_in(rw->args, i)) { if (cnt++ != 0) errs() << ","; errs() << i << "=(" << *cs.getArgument(i) << ")"; } } errs() << "]\n"; #endif Instruction* newInst = applyRewriteToCall(M, rw, cs); llvm::ReplaceInstWithInst(cs.getInstruction(), newInst); modified = true; } } } return modified; } /* * Rewrite the given module according to the ComponentInterfaceTransformer. */ bool TransformComponentWithoutUse(Module& M, ComponentInterfaceTransform& T) { assert(T.interface != NULL); bool modified = false; for (Module::iterator f = M.begin(), e = M.end(); f != e; ++f) { for (Function::iterator bb = f->begin(), bbe = f->end(); bb != bbe; ++bb) { for (BasicBlock::iterator I = bb->begin(), E = bb->end(); I != E; ++I) { // TODO: Handle the operands CallSite call; if (CallInst* ci = dyn_cast<CallInst>(&*I)) { if (ci->isInlineAsm()) continue; call = CallSite(ci); } else if (InvokeInst* ci = dyn_cast<InvokeInst>(&*I)) { call = CallSite(ci); } else { // TODO: We need to find all references, including ones stored in variables // we'll be conservative and say that if it is stored in a variable then // we can't optimize it at all continue; } Function* target = call.getCalledFunction(); if (target == NULL || !target->isDeclaration()) { continue; } //iam const CallRewrite* const rw = T.lookupRewrite(target->getNameStr(), call.arg_begin(), call.arg_end()); const CallRewrite* const rw = T.lookupRewrite(target->getName().str(), call.arg_begin(), call.arg_end()); if (rw == NULL) { // There is no rewrite for this function continue; } // Get/Create the function Function* newTarget = M.getFunction(rw->function); if (newTarget == NULL) { // There isn't a function, we need to construct it FunctionType* newType = target->getFunctionType(); std::vector<Type*> argTypes; for (std::vector<unsigned>::const_iterator i = rw->args.begin(), e = rw->args.end(); i != e; ++i) argTypes.push_back(newType->getParamType(*i)); ArrayRef<Type*> params(argTypes); newType = FunctionType::get(target->getReturnType(), params, target->isVarArg()); newTarget = dyn_cast<Function> (M.getOrInsertFunction(rw->function, newType)); } assert(newTarget != NULL); Instruction* newInst = specializeCallSite(I, newTarget, rw->args); llvm::ReplaceInstWithInst(bb->getInstList(), I, newInst); modified = true; } } } return modified; } bool TransformComponent(Module& M, ComponentInterfaceTransform& T) { return TransformComponentWithUse(M, T); } static cl::list<std::string> RewriteComponentInput("Prewrite-input", cl::NotHidden, cl::desc( "specifies the interface to rewrite using")); class RewriteComponentPass : public ModulePass { public: ComponentInterfaceTransform transform; static char ID; public: RewriteComponentPass() : ModulePass(ID), transform() { errs() << "RewriteComponentPass()\n"; for (cl::list<std::string>::const_iterator b = RewriteComponentInput.begin(), e = RewriteComponentInput.end(); b != e; ++b) { errs() << "Reading file '" << *b << "'..."; if (transform.readTransformFromFile(*b)) { errs() << "success\n"; } else { errs() << "failed\n"; } } transform.dump(); errs() << "Done reading (" << transform.rewriteCount() << " rewrites)\n"; } virtual ~RewriteComponentPass() { } public: virtual bool runOnModule(Module& M) { if (this->transform.interface == NULL) { return false; } errs() << "RewriteComponentPass:runOnModule: " << M.getModuleIdentifier() << "\n"; bool modified = TransformComponent(M, this->transform); if (modified) { errs() << "...progress...\n"; } else { errs() << "...no progress...\n"; } return modified; } }; char RewriteComponentPass::ID; static RegisterPass<RewriteComponentPass> X("Prewrite", "previrtualize the given module (requires parameters)", false, false); } <|endoftext|>
<commit_before>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 1; sc<=1; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; //cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //For one Video cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act ); //getchar(); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); //cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j< l + segment_length; ++j) { //k++; //cout << " " << j; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } //cout << endl; //cout << " " << stat_seg.count(); if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores { std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); s++; } else { //cout << " " << stat_seg.count(); //getchar(); } } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "Total # of segments" << s << endl; //cout << "press a key " ; //getchar(); } <commit_msg>Ultimos cambios<commit_after>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 1; sc<=1; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; //cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //For one Video cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act ); //getchar(); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); //cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j< l + segment_length; ++j) { //k++; //cout << " " << j; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } //cout << endl; //cout << " " << stat_seg.count(); if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores { std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); s++; } else { //cout << " " << stat_seg.count(); //getchar(); } } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "Total # of segments " << s << endl; //cout << "press a key " ; //getchar(); } <|endoftext|>
<commit_before>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 4; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; //cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //For one Video if ( !( sc=3 && pe=12 && act=1) ) //person13_handclapping_d3 { cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act ); } //getchar(); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); //cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j< l + segment_length; ++j) { //k++; //cout << " " << j; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } //cout << endl; //cout << " " << stat_seg.count(); if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores { std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; std::stringstream save_LogMcov_seg; save_LogMcov_seg << save_folder.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion eig_sym(D, V, cov_seg_i); mat log_M = V*diagmat( log(D) )*V.t(); cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); log_M.save( save_LogMcov_seg.str(), hdf5_binary ); // cov_seg_i.print("cov_seg_i"); // log_M.print("log_M"); // getchar(); s++; } else { //cout << " " << stat_seg.count(); //getchar(); } } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "Total # of segments " << s << endl; //cout << "press a key " ; //getchar(); } <commit_msg> Bug with unexisting video<commit_after>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); for (int sc = 4; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; //cout << "Loading.." << endl; load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //For one Video if ( !( sc==3 && pe==12 && act==1) ) //person13_handclapping_d3 { cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act ); } //getchar(); } } } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); //cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j< l + segment_length; ++j) { //k++; //cout << " " << j; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } //cout << endl; //cout << " " << stat_seg.count(); if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores { std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; std::stringstream save_LogMcov_seg; save_LogMcov_seg << save_folder.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion eig_sym(D, V, cov_seg_i); mat log_M = V*diagmat( log(D) )*V.t(); cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); log_M.save( save_LogMcov_seg.str(), hdf5_binary ); // cov_seg_i.print("cov_seg_i"); // log_M.print("log_M"); // getchar(); s++; } else { //cout << " " << stat_seg.count(); //getchar(); } } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "Total # of segments " << s << endl; //cout << "press a key " ; //getchar(); } <|endoftext|>
<commit_before>#pragma once #ifndef OPENGM_PLANAR_MAXCUT_HXX #define OPENGM_PLANAR_MAXCUT_HXX #include "planar_maxcut_graph.hxx" namespace opengm { /// OpenGM wrappers around third party algorithms namespace external { /// \cond HIDDEN_SYMBOLS /// \brief MAXCUT for planar graphs class PlanarMaxCut { public: typedef size_t node_type; typedef double value_type; PlanarMaxCut(); ~PlanarMaxCut(); PlanarMaxCut(size_t numberOfNodes, size_t numberOfEdges); void addEdge(node_type,node_type,value_type); template <class VEC> void calculateCut(VEC&); private: typename pmc::Graph graph_; typename pmc::Node** NodesPtr; // This should be moved to pmc::Graph size_t numberOfNodes_; size_t numberOfEdges_; // usused so far }; inline PlanarMaxCut::PlanarMaxCut() { numberOfNodes_ = 0; numberOfEdges_ = 0; } inline PlanarMaxCut::PlanarMaxCut(size_t numberOfNodes, size_t numberOfEdges) { numberOfNodes_ = numberOfNodes; numberOfEdges_ = numberOfEdges; NodesPtr = new pmc::Node*[numberOfNodes]; for(size_t variableId=0; variableId < numberOfNodes; ++variableId) { pmc::Node* v = graph_.add_node(variableId, 0.0); NodesPtr[variableId] = v; } } inline PlanarMaxCut::~PlanarMaxCut() { if( NodesPtr != NULL) delete[] NodesPtr; } inline void PlanarMaxCut::addEdge(node_type n1, node_type n2, value_type cost) { assert(n1 < numberOfNodes_); assert(n2 < numberOfNodes_); pmc::Node* v_i = NodesPtr[n1]; pmc::Node* v_j = NodesPtr[n2]; pmc::Edge* e_ij = graph_.find_edge(v_i,v_j); if(e_ij==NULL){ graph_.add_edge(v_i,v_j,cost); }else{ e_ij->weight += cost; } } template <class VEC> void PlanarMaxCut::calculateCut(VEC& segmentation) { graph_.planarize(); // Planarize graph graph_.construct_dual(); // Construct dual graph graph_.mcpm(); // Perform perfect matching / max cut graph_.assign_labels(); // Derive labels from cut set graph_.read_labels(segmentation); //segmentation = graph_.read_labels(); return; } /// \endcond } // namespace external } // namespace opengm #endif // #ifndef OPENGM_PLANAR_MAXCUT_HXX <commit_msg>update for the planar maxcut interface<commit_after>#pragma once #ifndef OPENGM_PLANAR_MAXCUT_HXX #define OPENGM_PLANAR_MAXCUT_HXX #include "planar_graph.hxx" namespace opengm { /// OpenGM wrappers around third party algorithms namespace external { /// \cond HIDDEN_SYMBOLS /// \brief MAXCUT for planar graphs class PlanarMaxCut { public: typedef size_t node_type; typedef double value_type; PlanarMaxCut(); ~PlanarMaxCut(); PlanarMaxCut(size_t numberOfNodes, size_t numberOfEdges); void addEdge(node_type,node_type,value_type); void calculateCut(); template <class VEC> void getCut(VEC&); template <class VEC> void getLabeling(VEC&); private: typename planargraph::PlanarGraph graph_; size_t numberOfNodes_; size_t numberOfEdges_; // usused so far }; inline PlanarMaxCut::PlanarMaxCut() { numberOfNodes_ = 0; numberOfEdges_ = 0; } inline PlanarMaxCut::PlanarMaxCut(size_t numberOfNodes, size_t numberOfEdges) { numberOfNodes_ = numberOfNodes; numberOfEdges_ = numberOfEdges; for(size_t variableId=0; variableId < numberOfNodes; ++variableId) { graph_.add_node(); } } inline PlanarMaxCut::~PlanarMaxCut() { } inline void PlanarMaxCut::addEdge(node_type n1, node_type n2, value_type cost) { assert(n1 < numberOfNodes_); assert(n2 < numberOfNodes_); long int e = graph_.find_edge(n1,n2); if(e == -1){ graph_.add_edge(n1, n2, cost); } else { graph_.add_edge_weight(e, cost); } } void PlanarMaxCut::calculateCut() { graph_.planarize(); // Planarize graph graph_.construct_dual(); // Construct dual graph graph_.calculate_maxcut(); // Perform perfect matching / max cut } template <class VEC> void PlanarMaxCut::getCut(VEC& cut) { // todo: add temptated interface in planargraph std::vector<bool> temp = graph_.get_cut(); cut.resize(temp.size()); for(size_t i=0; i<temp.size(); ++i) cut[i]=temp[i]; return; } template <class VEC> void PlanarMaxCut::getLabeling(VEC& segmentation) { // todo: add temptated interface in planargraph std::vector<int> temp; graph_.get_labeling(temp); segmentation.resize(temp.size()); for(size_t i=0; i<temp.size(); ++i) segmentation[i]=temp[i]; return; } /// \endcond } // namespace external } // namespace opengm #endif // #ifndef OPENGM_PLANAR_MAXCUT_HXX <|endoftext|>
<commit_before>/******************************************************************************* * thrill/api/read_lines.hpp * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_API_READ_LINES_HEADER #define THRILL_API_READ_LINES_HEADER #include <thrill/api/dia.hpp> #include <thrill/api/source_node.hpp> #include <thrill/common/defines.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/math.hpp> #include <thrill/common/string.hpp> #include <thrill/core/file_io.hpp> #include <thrill/net/buffer_builder.hpp> #include <string> #include <utility> #include <vector> namespace thrill { namespace api { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a line-based Read operation. Read reads a file from * the file system and emits it as a DIA. */ class ReadLinesNode : public SourceNode<std::string> { public: using Super = SourceNode<std::string>; using Super::context_; using FileSizePair = std::pair<std::string, size_t>; static const bool debug = false; /*! * Constructor for a ReadLinesNode. Sets the Context * and file path. * * \param ctx Reference to Context, which holds references to data and * network. * * \param path Path of the input file(s) */ ReadLinesNode(Context& ctx, const std::string& path, StatsNode* stats_node) : Super(ctx, { }, stats_node), path_(path) { LOG << "Opening read notes for " << path_; filesize_prefix_ = core::GlobFileSizePrefixSum(path_); for (auto file : filesize_prefix_) { if (core::IsCompressed(file.first)) { contains_compressed_file_ = true; break; } } } void PushData() final { if (contains_compressed_file_) { InputLineIteratorCompressed it = InputLineIteratorCompressed( filesize_prefix_, context_.my_rank(), context_.num_workers()); // Hook Read while (it.HasNext()) { this->PushItem(it.Next()); } } else { InputLineIteratorUncompressed it = InputLineIteratorUncompressed( filesize_prefix_, context_.my_rank(), context_.num_workers()); // Hook Read while (it.HasNext()) { this->PushItem(it.Next()); } } } void Dispose() final { } /*! * Produces an 'empty' function stack, which only contains the identity * emitter function. * * \return Empty function stack */ auto ProduceStack() { return FunctionStack<std::string>(); } private: //! True, if at least one input file is compressed. bool contains_compressed_file_ = false; //! Path of the input file. std::string path_; std::vector<std::pair<std::string, size_t> > filesize_prefix_; // REVIEW(an): this is useless, you never use the inheritance. But, you // actually SHOULD use it! for all member fields and methods that are in // common. But NOT for virtual functions. Remove the virtuals. Find out what // functions the methods below have in common and make them functions of the // superclass. class InputLineIterator { public: static const bool debug = false; const size_t read_size = 2 * 1024 * 1024; virtual ~InputLineIterator() { } }; //! InputLineIterator gives you access to lines of a file class InputLineIteratorUncompressed : public InputLineIterator { public: using Base = InputLineIterator; //! Creates an instance of iterator that reads file line based InputLineIteratorUncompressed( std::vector<FileSizePair> files, size_t my_id, size_t num_workers) : files_(files), my_id_(my_id), num_workers_(num_workers) { input_size_ = files[NumFiles()].second; // Go to start of 'local part'. auto my_start_and_end = common::CalculateLocalRange(input_size_, num_workers_, my_id_); size_t my_start = std::get<0>(my_start_and_end); my_end_ = std::get<1>(my_start_and_end); while (files_[current_file_ + 1].second <= my_start) { current_file_++; } if (my_start < my_end_) { LOG << "Opening file " << current_file_; c_file_ = OpenFile(files_[current_file_].first); } else { LOG << "my_start : " << my_start << " my_end_: " << my_end_; return; } // find offset in current file: // offset = start - sum of previous file sizes offset_ = lseek(c_file_, my_start - files_[current_file_].second, SEEK_CUR); buffer_.Reserve(Base::read_size); ssize_t buffer_size = read(c_file_, buffer_.data(), Base::read_size); buffer_.set_size(buffer_size); current_ = buffer_.begin(); if (offset_ != 0) { bool found_n = false; // find next newline, discard all previous data as previous worker already covers it while (!found_n) { for (auto it = current_; it != buffer_.end(); it++) { if (THRILL_UNLIKELY(*it == '\n')) { current_ = it + 1; found_n = true; break; } } // no newline found: read new data into buffer_builder if (!found_n) { current_ = buffer_.begin(); offset_ += buffer_.size(); buffer_size = read(c_file_, buffer_.data(), Base::read_size); // EOF = newline per definition if (!buffer_size) { found_n = true; } buffer_.set_size(buffer_size); } } assert(*(current_ - 1) == '\n' || !buffer_size); } } //! returns the next element if one exists //! //! does no checks whether a next element exists! std::string Next() { std::string ret; while (true) { for (auto it = current_; it != buffer_.end(); it++) { if (THRILL_UNLIKELY(*it == '\n')) { size_t strlen = it - current_; current_ = it + 1; LOG << "returning string"; if (ret.size()) { return ret.append(it - strlen, it); } else { return std::string(it - strlen, it); } } } ret.append(current_, buffer_.end()); current_ = buffer_.begin(); ssize_t buffer_size = read(c_file_, buffer_.data(), Base::read_size); offset_ += buffer_.size(); if (buffer_size) { buffer_.set_size(buffer_size); } else { close(c_file_); current_file_++; offset_ = 0; if (current_file_ < NumFiles()) { c_file_ = OpenFile(files_[current_file_].first); ssize_t buffer_size = read(c_file_, buffer_.data(), Base::read_size); buffer_.set_size(buffer_size); } else { current_ = buffer_.begin() + files_[current_file_].second - files_[current_file_ - 1].second; } if (ret.length()) { LOG << "end - returning string of length" << ret.length(); return ret; } } } } //! returns true, if an element is available in local part bool HasNext() { size_t global_index = offset_ + current_ - buffer_.begin() + files_[current_file_].second; return global_index < my_end_ || (global_index == my_end_ && files_[current_file_ + 1].second - files_[current_file_].second > offset_ + (current_ - buffer_.begin())); } size_t NumFiles() { return files_.size() - 1; } //! Open file and return file handle //! \param path Path to open int OpenFile(const std::string& path) { return open(path.c_str(), O_RDONLY); } private: //! Input files with size prefixsum. std::vector<FileSizePair> files_; // REVIEW(an): use a const & to the vector //! Index of current file in files_ size_t current_file_ = 0; //! File handle to files_[current_file_] int c_file_; //! Offset of current block in c_file_. size_t offset_ = 0; //! Start of next element in current buffer. unsigned char* current_; //! (exclusive) end of local block size_t my_end_; //! Byte buffer to create line-std::strings net::BufferBuilder buffer_; //! Worker ID size_t my_id_; //! total number of workers size_t num_workers_; //! Size of all files combined (in bytes) size_t input_size_; }; //! InputLineIterator gives you access to lines of a file class InputLineIteratorCompressed : public InputLineIterator { public: using Base = InputLineIterator; //! Creates an instance of iterator that reads file line based InputLineIteratorCompressed( std::vector<FileSizePair> files, size_t my_id, size_t num_workers) : files_(files), my_id_(my_id), num_workers_(num_workers) { input_size_ = files[NumFiles()].second; // Go to start of 'local part'. size_t my_start; std::tie(my_start, my_end_) = common::CalculateLocalRange(input_size_, num_workers_, my_id_); while (files_[current_file_ + 1].second <= my_start) { current_file_++; } for (size_t file_nr = current_file_; file_nr < NumFiles(); file_nr++) { if (files[file_nr + 1].second == my_end_) { break; } if (files[file_nr + 1].second > my_end_) { my_end_ = files_[file_nr].second; break; } } if (my_start < my_end_) { LOG << "Opening file " << current_file_; LOG << "my_start : " << my_start << " my_end_: " << my_end_; c_file_ = core::SysFile::OpenForRead(files_[current_file_].first); } else { // No local files, set buffer size to 2, so HasNext() does not try to read LOG << "my_start : " << my_start << " my_end_: " << my_end_; buffer_.Reserve(2); buffer_.set_size(2); current_ = buffer_.begin(); return; } buffer_.Reserve(read_size); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); buffer_.set_size(buffer_size); current_ = buffer_.begin(); data_.reserve(4 * 1024); } //! returns the next element if one exists //! //! does no checks whether a next element exists! const std::string& Next() { while (true) { data_.clear(); for (auto it = current_; it != buffer_.end(); it++) { if (THRILL_UNLIKELY(*it == '\n')) { current_ = it + 1; return data_; } else { data_.push_back(*it); } } current_ = buffer_.begin(); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); if (buffer_size) { buffer_.set_size(buffer_size); } else { LOG << "Opening new file!"; c_file_.close(); current_file_++; if (current_file_ < NumFiles()) { c_file_ = core::SysFile::OpenForRead(files_[current_file_].first); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); buffer_.set_size(buffer_size); } else { current_ = buffer_.begin(); } if (data_.length()) { LOG << "end - returning string of length" << data_.length(); return data_; } } } } size_t NumFiles() { return files_.size() - 1; } //! returns true, if an element is available in local part bool HasNext() { // if block is fully read, read next block. needs to be done here // as HasNext() has to know if file is finished // v-- no new line at end || v-- newline at end of file if (current_ >= buffer_.end() || (current_ + 1 >= buffer_.end() && *current_ == '\n')) { LOG << "New buffer in HasNext()"; current_ = buffer_.begin(); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); if (buffer_size > 1 || (buffer_size == 1 && buffer_[0] != '\n')) { buffer_.set_size(buffer_size); return true; } else { LOG << "Opening new file in HasNext()"; // already at last file if (current_file_ >= NumFiles() - 1) { return false; } c_file_.close(); // if (this worker reads at least one more file) if (my_end_ > files_[current_file_ + 1].second) { current_file_++; c_file_ = core::SysFile::OpenForRead(files_[current_file_].first); buffer_.set_size(c_file_.read(buffer_.data(), read_size)); return true; } else { return false; } } } else { return files_[current_file_].second < my_end_; } } private: //! Input files with size prefixsum. std::vector<FileSizePair> files_; //! Index of current file in files_ size_t current_file_ = 0; //! File handle to files_[current_file_] core::SysFile c_file_; //! Start of next element in current buffer. unsigned char* current_; //! (exclusive) end of local block size_t my_end_; //! Byte buffer to create line-std::strings net::BufferBuilder buffer_; //! Worker ID size_t my_id_; //! total number of workers size_t num_workers_; //! Size of all files combined (in bytes) size_t input_size_; std::string data_; }; }; DIARef<std::string> ReadLines(Context& ctx, std::string filepath) { StatsNode* stats_node = ctx.stats_graph().AddNode( "ReadLines", DIANodeType::DOP); auto shared_node = std::make_shared<ReadLinesNode>( ctx, filepath, stats_node); auto read_stack = shared_node->ProduceStack(); return DIARef<std::string, decltype(read_stack)>( shared_node, read_stack, { stats_node }); } //! \} } // namespace api } // namespace thrill #endif // !THRILL_API_READ_LINES_HEADER /******************************************************************************/ <commit_msg>remove O(N) allocations also in uncomrpessed read<commit_after>/******************************************************************************* * thrill/api/read_lines.hpp * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_API_READ_LINES_HEADER #define THRILL_API_READ_LINES_HEADER #include <thrill/api/dia.hpp> #include <thrill/api/source_node.hpp> #include <thrill/common/defines.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/math.hpp> #include <thrill/common/string.hpp> #include <thrill/core/file_io.hpp> #include <thrill/net/buffer_builder.hpp> #include <string> #include <utility> #include <vector> namespace thrill { namespace api { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a line-based Read operation. Read reads a file from * the file system and emits it as a DIA. */ class ReadLinesNode : public SourceNode<std::string> { public: using Super = SourceNode<std::string>; using Super::context_; using FileSizePair = std::pair<std::string, size_t>; static const bool debug = false; /*! * Constructor for a ReadLinesNode. Sets the Context * and file path. * * \param ctx Reference to Context, which holds references to data and * network. * * \param path Path of the input file(s) */ ReadLinesNode(Context& ctx, const std::string& path, StatsNode* stats_node) : Super(ctx, { }, stats_node), path_(path) { LOG << "Opening read notes for " << path_; filesize_prefix_ = core::GlobFileSizePrefixSum(path_); for (auto file : filesize_prefix_) { if (core::IsCompressed(file.first)) { contains_compressed_file_ = true; break; } } } void PushData() final { if (contains_compressed_file_) { InputLineIteratorCompressed it = InputLineIteratorCompressed( filesize_prefix_, context_.my_rank(), context_.num_workers()); // Hook Read while (it.HasNext()) { this->PushItem(it.Next()); } } else { InputLineIteratorUncompressed it = InputLineIteratorUncompressed( filesize_prefix_, context_.my_rank(), context_.num_workers()); // Hook Read while (it.HasNext()) { this->PushItem(it.Next()); } } } void Dispose() final { } /*! * Produces an 'empty' function stack, which only contains the identity * emitter function. * * \return Empty function stack */ auto ProduceStack() { return FunctionStack<std::string>(); } private: //! True, if at least one input file is compressed. bool contains_compressed_file_ = false; //! Path of the input file. std::string path_; std::vector<std::pair<std::string, size_t> > filesize_prefix_; // REVIEW(an): this is useless, you never use the inheritance. But, you // actually SHOULD use it! for all member fields and methods that are in // common. But NOT for virtual functions. Remove the virtuals. Find out what // functions the methods below have in common and make them functions of the // superclass. class InputLineIterator { public: static const bool debug = false; const size_t read_size = 2 * 1024 * 1024; virtual ~InputLineIterator() { } }; //! InputLineIterator gives you access to lines of a file class InputLineIteratorUncompressed : public InputLineIterator { public: using Base = InputLineIterator; //! Creates an instance of iterator that reads file line based InputLineIteratorUncompressed( std::vector<FileSizePair> files, size_t my_id, size_t num_workers) : files_(files), my_id_(my_id), num_workers_(num_workers) { input_size_ = files[NumFiles()].second; // Go to start of 'local part'. auto my_start_and_end = common::CalculateLocalRange(input_size_, num_workers_, my_id_); size_t my_start = std::get<0>(my_start_and_end); my_end_ = std::get<1>(my_start_and_end); while (files_[current_file_ + 1].second <= my_start) { current_file_++; } if (my_start < my_end_) { LOG << "Opening file " << current_file_; c_file_ = OpenFile(files_[current_file_].first); } else { LOG << "my_start : " << my_start << " my_end_: " << my_end_; return; } // find offset in current file: // offset = start - sum of previous file sizes offset_ = lseek(c_file_, my_start - files_[current_file_].second, SEEK_CUR); buffer_.Reserve(Base::read_size); ssize_t buffer_size = read(c_file_, buffer_.data(), Base::read_size); buffer_.set_size(buffer_size); current_ = buffer_.begin(); if (offset_ != 0) { bool found_n = false; // find next newline, discard all previous data as previous worker already covers it while (!found_n) { for (auto it = current_; it != buffer_.end(); it++) { if (THRILL_UNLIKELY(*it == '\n')) { current_ = it + 1; found_n = true; break; } } // no newline found: read new data into buffer_builder if (!found_n) { current_ = buffer_.begin(); offset_ += buffer_.size(); buffer_size = read(c_file_, buffer_.data(), Base::read_size); // EOF = newline per definition if (!buffer_size) { found_n = true; } buffer_.set_size(buffer_size); } } assert(*(current_ - 1) == '\n' || !buffer_size); } data_.reserve(4 * 1024); } //! returns the next element if one exists //! //! does no checks whether a next element exists! const std::string& Next() { data_.clear(); while (true) { for (auto it = current_; it != buffer_.end(); it++) { if (THRILL_UNLIKELY(*it == '\n')) { current_ = it + 1; return data_; } else { data_.push_back(*it); } } current_ = buffer_.begin(); ssize_t buffer_size = read(c_file_, buffer_.data(), Base::read_size); offset_ += buffer_.size(); if (buffer_size) { buffer_.set_size(buffer_size); } else { close(c_file_); current_file_++; offset_ = 0; if (current_file_ < NumFiles()) { c_file_ = OpenFile(files_[current_file_].first); ssize_t buffer_size = read(c_file_, buffer_.data(), Base::read_size); buffer_.set_size(buffer_size); } else { current_ = buffer_.begin() + files_[current_file_].second - files_[current_file_ - 1].second; } if (data_.length()) { return data_; } } } } //! returns true, if an element is available in local part bool HasNext() { size_t global_index = offset_ + current_ - buffer_.begin() + files_[current_file_].second; return global_index < my_end_ || (global_index == my_end_ && files_[current_file_ + 1].second - files_[current_file_].second > offset_ + (current_ - buffer_.begin())); } size_t NumFiles() { return files_.size() - 1; } //! Open file and return file handle //! \param path Path to open int OpenFile(const std::string& path) { return open(path.c_str(), O_RDONLY); } private: //! Input files with size prefixsum. std::vector<FileSizePair> files_; // REVIEW(an): use a const & to the vector //! Index of current file in files_ size_t current_file_ = 0; //! File handle to files_[current_file_] int c_file_; //! Offset of current block in c_file_. size_t offset_ = 0; //! Start of next element in current buffer. unsigned char* current_; //! (exclusive) end of local block size_t my_end_; //! Byte buffer to create line-std::strings net::BufferBuilder buffer_; //! Worker ID size_t my_id_; //! total number of workers size_t num_workers_; //! Size of all files combined (in bytes) size_t input_size_; //! String, which Next() references to std::string data_; }; //! InputLineIterator gives you access to lines of a file class InputLineIteratorCompressed : public InputLineIterator { public: using Base = InputLineIterator; //! Creates an instance of iterator that reads file line based InputLineIteratorCompressed( std::vector<FileSizePair> files, size_t my_id, size_t num_workers) : files_(files), my_id_(my_id), num_workers_(num_workers) { input_size_ = files[NumFiles()].second; // Go to start of 'local part'. size_t my_start; std::tie(my_start, my_end_) = common::CalculateLocalRange(input_size_, num_workers_, my_id_); while (files_[current_file_ + 1].second <= my_start) { current_file_++; } for (size_t file_nr = current_file_; file_nr < NumFiles(); file_nr++) { if (files[file_nr + 1].second == my_end_) { break; } if (files[file_nr + 1].second > my_end_) { my_end_ = files_[file_nr].second; break; } } if (my_start < my_end_) { LOG << "Opening file " << current_file_; LOG << "my_start : " << my_start << " my_end_: " << my_end_; c_file_ = core::SysFile::OpenForRead(files_[current_file_].first); } else { // No local files, set buffer size to 2, so HasNext() does not try to read LOG << "my_start : " << my_start << " my_end_: " << my_end_; buffer_.Reserve(2); buffer_.set_size(2); current_ = buffer_.begin(); return; } buffer_.Reserve(read_size); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); buffer_.set_size(buffer_size); current_ = buffer_.begin(); data_.reserve(4 * 1024); } //! returns the next element if one exists //! //! does no checks whether a next element exists! const std::string& Next() { while (true) { data_.clear(); for (auto it = current_; it != buffer_.end(); it++) { if (THRILL_UNLIKELY(*it == '\n')) { current_ = it + 1; return data_; } else { data_.push_back(*it); } } current_ = buffer_.begin(); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); if (buffer_size) { buffer_.set_size(buffer_size); } else { LOG << "Opening new file!"; c_file_.close(); current_file_++; if (current_file_ < NumFiles()) { c_file_ = core::SysFile::OpenForRead(files_[current_file_].first); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); buffer_.set_size(buffer_size); } else { current_ = buffer_.begin(); } if (data_.length()) { LOG << "end - returning string of length" << data_.length(); return data_; } } } } size_t NumFiles() { return files_.size() - 1; } //! returns true, if an element is available in local part bool HasNext() { // if block is fully read, read next block. needs to be done here // as HasNext() has to know if file is finished // v-- no new line at end || v-- newline at end of file if (current_ >= buffer_.end() || (current_ + 1 >= buffer_.end() && *current_ == '\n')) { LOG << "New buffer in HasNext()"; current_ = buffer_.begin(); ssize_t buffer_size = c_file_.read(buffer_.data(), read_size); if (buffer_size > 1 || (buffer_size == 1 && buffer_[0] != '\n')) { buffer_.set_size(buffer_size); return true; } else { LOG << "Opening new file in HasNext()"; // already at last file if (current_file_ >= NumFiles() - 1) { return false; } c_file_.close(); // if (this worker reads at least one more file) if (my_end_ > files_[current_file_ + 1].second) { current_file_++; c_file_ = core::SysFile::OpenForRead(files_[current_file_].first); buffer_.set_size(c_file_.read(buffer_.data(), read_size)); return true; } else { return false; } } } else { return files_[current_file_].second < my_end_; } } private: //! Input files with size prefixsum. std::vector<FileSizePair> files_; //! Index of current file in files_ size_t current_file_ = 0; //! File handle to files_[current_file_] core::SysFile c_file_; //! Start of next element in current buffer. unsigned char* current_; //! (exclusive) end of local block size_t my_end_; //! Byte buffer to create line-std::strings net::BufferBuilder buffer_; //! Worker ID size_t my_id_; //! total number of workers size_t num_workers_; //! Size of all files combined (in bytes) size_t input_size_; //! String, which Next() references to std::string data_; }; }; DIARef<std::string> ReadLines(Context& ctx, std::string filepath) { StatsNode* stats_node = ctx.stats_graph().AddNode( "ReadLines", DIANodeType::DOP); auto shared_node = std::make_shared<ReadLinesNode>( ctx, filepath, stats_node); auto read_stack = shared_node->ProduceStack(); return DIARef<std::string, decltype(read_stack)>( shared_node, read_stack, { stats_node }); } //! \} } // namespace api } // namespace thrill #endif // !THRILL_API_READ_LINES_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/* * SessionConnections.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionConnections.hpp" #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Log.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/system/Process.hpp> #include <r/RSexp.hpp> #include <r/RRoutines.hpp> #include <r/RExec.hpp> #include <r/session/RSessionUtils.hpp> #include <session/SessionConsoleProcess.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include "ActiveConnections.hpp" #include "ConnectionHistory.hpp" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace connections { namespace { SEXP rs_connectionOpened(SEXP typeSEXP, SEXP hostSEXP, SEXP finderSEXP, SEXP connectCodeSEXP, SEXP disconnectCodeSEXP) { // read params std::string type = r::sexp::safeAsString(typeSEXP); std::string host = r::sexp::safeAsString(hostSEXP); std::string finder = r::sexp::safeAsString(finderSEXP); std::string connectCode = r::sexp::safeAsString(connectCodeSEXP); std::string disconnectCode = r::sexp::safeAsString(disconnectCodeSEXP); // create connection object Connection connection(ConnectionId(type, host), finder, connectCode, disconnectCode, date_time::millisecondsSinceEpoch()); // update connection history connectionHistory().update(connection); // update active connections activeConnections().add(connection.id); return R_NilValue; } SEXP rs_connectionClosed(SEXP typeSEXP, SEXP hostSEXP) { std::string type = r::sexp::safeAsString(typeSEXP); std::string host = r::sexp::safeAsString(hostSEXP); // update active connections activeConnections().remove(ConnectionId(type, host)); return R_NilValue; } SEXP rs_connectionUpdated(SEXP typeSEXP, SEXP hostSEXP) { std::string type = r::sexp::safeAsString(typeSEXP); std::string host = r::sexp::safeAsString(hostSEXP); ConnectionId id(type, host); ClientEvent event(client_events::kConnectionUpdated, connectionIdJson(id)); module_context::enqueClientEvent(event); return R_NilValue; } SEXP rs_availableRemoteServers() { // get list of previous connections and extract unique remote servers std::vector<std::string> remoteServers; json::Array connectionsJson = connectionHistory().connectionsAsJson(); BOOST_FOREACH(const json::Value connectionJson, connectionsJson) { // don't inspect if not an object -- this should never happen // but we screen it anyway to prevent a crash on corrupt data if (!json::isType<json::Object>(connectionJson)) continue; // get the host json::Object idJson; Error error = json::readObject(connectionJson.get_obj(), "id", &idJson); if (error) { LOG_ERROR(error); continue; } std::string host; error = json::readObject(idJson, "host", &host); if (error) { LOG_ERROR(error); continue; } // add it if necessary if(std::find(remoteServers.begin(), remoteServers.end(), host) == remoteServers.end()) { if (host != "local" && !boost::algorithm::starts_with(host, "local[")) remoteServers.push_back(host); } } r::sexp::Protect rProtect; return r::sexp::create(remoteServers, &rProtect); } Error removeConnection(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // read params std::string type, host; Error error = json::readObjectParam(request.params, 0, "type", &type, "host", &host); if (error) return error; // remove connection ConnectionId id(type, host); connectionHistory().remove(id); return Success(); } Error getDisconnectCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // read params json::Object idJson; std::string finder, disconnectCode; Error error = json::readObjectParam(request.params, 0, "id", &idJson, "finder", &finder, "disconnect_code", &disconnectCode); if (error) return error; std::string type, host; error = json::readObject(idJson, "type", &type, "host", &host); if (error) return error; // call R function to determine disconnect code r::exec::RFunction func(".rs.getDisconnectCode"); func.addParam(finder); func.addParam(host); func.addParam(disconnectCode); std::string code; error = func.call(&code); if (error) return error; pResponse->setResult(code); return Success(); } Error installSpark(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get params std::string sparkVersion, hadoopVersion; Error error = json::readParams(request.params, &sparkVersion, &hadoopVersion); if (error) return error; // R binary FilePath rProgramPath; error = module_context::rScriptPath(&rProgramPath); if (error) return error; // options core::system::ProcessOptions options; options.terminateChildren = true; options.redirectStdErrToStdOut = true; // build install command boost::format fmt("rspark::spark_install('%1%', hadoop_version = '%2%')"); std::string cmd = boost::str(fmt % sparkVersion % hadoopVersion); // build args std::vector<std::string> args; args.push_back("--slave"); args.push_back("--vanilla"); // propagate R_LIBS core::system::Options childEnv; core::system::environment(&childEnv); std::string libPaths = module_context::libPathsString(); if (!libPaths.empty()) core::system::setenv(&childEnv, "R_LIBS", libPaths); options.environment = childEnv; // for windows we need to forward setInternet2 #ifdef _WIN32 if (!r::session::utils::isR3_3() && userSettings().useInternet2()) args.push_back("--internet2"); #endif args.push_back("-e"); args.push_back(cmd); // create and execute console process boost::shared_ptr<console_process::ConsoleProcess> pCP; pCP = console_process::ConsoleProcess::create( string_utils::utf8ToSystem(rProgramPath.absolutePath()), args, options, "Installing Spark " + sparkVersion, true, console_process::InteractionNever); // return console process pResponse->setResult(pCP->toJson()); return Success(); } // track whether connections were enabled at the start of this R session bool s_connectionsInitiallyEnabled = false; void onInstalledPackagesChanged() { if (activateConnections()) { ClientEvent event(client_events::kEnableConnections); module_context::enqueClientEvent(event); } } } // anonymous namespace bool connectionsEnabled() { return module_context::isPackageVersionInstalled("rspark", "0.1.6"); } bool activateConnections() { return !s_connectionsInitiallyEnabled && connectionsEnabled(); } json::Array connectionsAsJson() { return connectionHistory().connectionsAsJson(); } json::Array activeConnectionsAsJson() { return activeConnections().activeConnectionsAsJson(); } bool isSuspendable() { return activeConnections().empty(); } Error initialize() { // register methods RS_REGISTER_CALL_METHOD(rs_connectionOpened, 5); RS_REGISTER_CALL_METHOD(rs_connectionClosed, 2); RS_REGISTER_CALL_METHOD(rs_connectionUpdated, 2); RS_REGISTER_CALL_METHOD(rs_availableRemoteServers, 0); // initialize connection history Error error = connectionHistory().initialize(); if (error) return error; // connect to events to track whether we should enable connections s_connectionsInitiallyEnabled = connectionsEnabled(); module_context::events().onPackageLibraryMutated.connect( onInstalledPackagesChanged); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "remove_connection", removeConnection)) (bind(registerRpcMethod, "get_disconnect_code", getDisconnectCode)) (bind(registerRpcMethod, "install_spark", installSpark)) (bind(sourceModuleRFile, "SessionConnections.R")); return initBlock.execute(); } } // namespace connections } // namespace modules } // namesapce session } // namespace rstudio <commit_msg>install spark using verbose mode<commit_after>/* * SessionConnections.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionConnections.hpp" #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Log.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <core/system/Process.hpp> #include <r/RSexp.hpp> #include <r/RRoutines.hpp> #include <r/RExec.hpp> #include <r/session/RSessionUtils.hpp> #include <session/SessionConsoleProcess.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include "ActiveConnections.hpp" #include "ConnectionHistory.hpp" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace connections { namespace { SEXP rs_connectionOpened(SEXP typeSEXP, SEXP hostSEXP, SEXP finderSEXP, SEXP connectCodeSEXP, SEXP disconnectCodeSEXP) { // read params std::string type = r::sexp::safeAsString(typeSEXP); std::string host = r::sexp::safeAsString(hostSEXP); std::string finder = r::sexp::safeAsString(finderSEXP); std::string connectCode = r::sexp::safeAsString(connectCodeSEXP); std::string disconnectCode = r::sexp::safeAsString(disconnectCodeSEXP); // create connection object Connection connection(ConnectionId(type, host), finder, connectCode, disconnectCode, date_time::millisecondsSinceEpoch()); // update connection history connectionHistory().update(connection); // update active connections activeConnections().add(connection.id); return R_NilValue; } SEXP rs_connectionClosed(SEXP typeSEXP, SEXP hostSEXP) { std::string type = r::sexp::safeAsString(typeSEXP); std::string host = r::sexp::safeAsString(hostSEXP); // update active connections activeConnections().remove(ConnectionId(type, host)); return R_NilValue; } SEXP rs_connectionUpdated(SEXP typeSEXP, SEXP hostSEXP) { std::string type = r::sexp::safeAsString(typeSEXP); std::string host = r::sexp::safeAsString(hostSEXP); ConnectionId id(type, host); ClientEvent event(client_events::kConnectionUpdated, connectionIdJson(id)); module_context::enqueClientEvent(event); return R_NilValue; } SEXP rs_availableRemoteServers() { // get list of previous connections and extract unique remote servers std::vector<std::string> remoteServers; json::Array connectionsJson = connectionHistory().connectionsAsJson(); BOOST_FOREACH(const json::Value connectionJson, connectionsJson) { // don't inspect if not an object -- this should never happen // but we screen it anyway to prevent a crash on corrupt data if (!json::isType<json::Object>(connectionJson)) continue; // get the host json::Object idJson; Error error = json::readObject(connectionJson.get_obj(), "id", &idJson); if (error) { LOG_ERROR(error); continue; } std::string host; error = json::readObject(idJson, "host", &host); if (error) { LOG_ERROR(error); continue; } // add it if necessary if(std::find(remoteServers.begin(), remoteServers.end(), host) == remoteServers.end()) { if (host != "local" && !boost::algorithm::starts_with(host, "local[")) remoteServers.push_back(host); } } r::sexp::Protect rProtect; return r::sexp::create(remoteServers, &rProtect); } Error removeConnection(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // read params std::string type, host; Error error = json::readObjectParam(request.params, 0, "type", &type, "host", &host); if (error) return error; // remove connection ConnectionId id(type, host); connectionHistory().remove(id); return Success(); } Error getDisconnectCode(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // read params json::Object idJson; std::string finder, disconnectCode; Error error = json::readObjectParam(request.params, 0, "id", &idJson, "finder", &finder, "disconnect_code", &disconnectCode); if (error) return error; std::string type, host; error = json::readObject(idJson, "type", &type, "host", &host); if (error) return error; // call R function to determine disconnect code r::exec::RFunction func(".rs.getDisconnectCode"); func.addParam(finder); func.addParam(host); func.addParam(disconnectCode); std::string code; error = func.call(&code); if (error) return error; pResponse->setResult(code); return Success(); } Error installSpark(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // get params std::string sparkVersion, hadoopVersion; Error error = json::readParams(request.params, &sparkVersion, &hadoopVersion); if (error) return error; // R binary FilePath rProgramPath; error = module_context::rScriptPath(&rProgramPath); if (error) return error; // options core::system::ProcessOptions options; options.terminateChildren = true; options.redirectStdErrToStdOut = true; // build install command boost::format fmt("rspark::spark_install('%1%', hadoop_version = '%2%', " "verbose = TRUE)"); std::string cmd = boost::str(fmt % sparkVersion % hadoopVersion); // build args std::vector<std::string> args; args.push_back("--slave"); args.push_back("--vanilla"); // propagate R_LIBS core::system::Options childEnv; core::system::environment(&childEnv); std::string libPaths = module_context::libPathsString(); if (!libPaths.empty()) core::system::setenv(&childEnv, "R_LIBS", libPaths); options.environment = childEnv; // for windows we need to forward setInternet2 #ifdef _WIN32 if (!r::session::utils::isR3_3() && userSettings().useInternet2()) args.push_back("--internet2"); #endif args.push_back("-e"); args.push_back(cmd); // create and execute console process boost::shared_ptr<console_process::ConsoleProcess> pCP; pCP = console_process::ConsoleProcess::create( string_utils::utf8ToSystem(rProgramPath.absolutePath()), args, options, "Installing Spark " + sparkVersion, true, console_process::InteractionNever); // return console process pResponse->setResult(pCP->toJson()); return Success(); } // track whether connections were enabled at the start of this R session bool s_connectionsInitiallyEnabled = false; void onInstalledPackagesChanged() { if (activateConnections()) { ClientEvent event(client_events::kEnableConnections); module_context::enqueClientEvent(event); } } } // anonymous namespace bool connectionsEnabled() { return module_context::isPackageVersionInstalled("rspark", "0.1.7"); } bool activateConnections() { return !s_connectionsInitiallyEnabled && connectionsEnabled(); } json::Array connectionsAsJson() { return connectionHistory().connectionsAsJson(); } json::Array activeConnectionsAsJson() { return activeConnections().activeConnectionsAsJson(); } bool isSuspendable() { return activeConnections().empty(); } Error initialize() { // register methods RS_REGISTER_CALL_METHOD(rs_connectionOpened, 5); RS_REGISTER_CALL_METHOD(rs_connectionClosed, 2); RS_REGISTER_CALL_METHOD(rs_connectionUpdated, 2); RS_REGISTER_CALL_METHOD(rs_availableRemoteServers, 0); // initialize connection history Error error = connectionHistory().initialize(); if (error) return error; // connect to events to track whether we should enable connections s_connectionsInitiallyEnabled = connectionsEnabled(); module_context::events().onPackageLibraryMutated.connect( onInstalledPackagesChanged); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(registerRpcMethod, "remove_connection", removeConnection)) (bind(registerRpcMethod, "get_disconnect_code", getDisconnectCode)) (bind(registerRpcMethod, "install_spark", installSpark)) (bind(sourceModuleRFile, "SessionConnections.R")); return initBlock.execute(); } } // namespace connections } // namespace modules } // namesapce session } // namespace rstudio <|endoftext|>
<commit_before>//===- EHPersonalities.cpp - Compute EH-related information ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/EHPersonalities.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/Debug.h" using namespace llvm; /// See if the given exception handling personality function is one that we /// understand. If so, return a description of it; otherwise return Unknown. EHPersonality llvm::classifyEHPersonality(const Value *Pers) { const Function *F = Pers ? dyn_cast<Function>(Pers->stripPointerCasts()) : nullptr; if (!F) return EHPersonality::Unknown; return StringSwitch<EHPersonality>(F->getName()) .Case("__gnat_eh_personality", EHPersonality::GNU_Ada) .Case("__gxx_personality_v0", EHPersonality::GNU_CXX) .Case("__gcc_personality_v0", EHPersonality::GNU_C) .Case("__objc_personality_v0", EHPersonality::GNU_ObjC) .Case("_except_handler3", EHPersonality::MSVC_X86SEH) .Case("_except_handler4", EHPersonality::MSVC_X86SEH) .Case("__C_specific_handler", EHPersonality::MSVC_Win64SEH) .Case("__CxxFrameHandler3", EHPersonality::MSVC_CXX) .Case("ProcessCLRException", EHPersonality::CoreCLR) .Default(EHPersonality::Unknown); } bool llvm::canSimplifyInvokeNoUnwind(const Function *F) { EHPersonality Personality = classifyEHPersonality(F->getPersonalityFn()); // We can't simplify any invokes to nounwind functions if the personality // function wants to catch asynch exceptions. The nounwind attribute only // implies that the function does not throw synchronous exceptions. return !isAsynchronousEHPersonality(Personality); } DenseMap<BasicBlock *, ColorVector> llvm::colorEHFunclets(Function &F) { SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist; BasicBlock *EntryBlock = &F.getEntryBlock(); DenseMap<BasicBlock *, ColorVector> BlockColors; // Build up the color map, which maps each block to its set of 'colors'. // For any block B the "colors" of B are the set of funclets F (possibly // including a root "funclet" representing the main function) such that // F will need to directly contain B or a copy of B (where the term "directly // contain" is used to distinguish from being "transitively contained" in // a nested funclet). // // Note: Despite not being funclets in the truest sense, terminatepad and // catchswitch are considered to belong to their own funclet for the purposes // of coloring. DEBUG_WITH_TYPE("winehprepare-coloring", dbgs() << "\nColoring funclets for " << F.getName() << "\n"); Worklist.push_back({EntryBlock, EntryBlock}); while (!Worklist.empty()) { BasicBlock *Visiting; BasicBlock *Color; std::tie(Visiting, Color) = Worklist.pop_back_val(); DEBUG_WITH_TYPE("winehprepare-coloring", dbgs() << "Visiting " << Visiting->getName() << ", " << Color->getName() << "\n"); Instruction *VisitingHead = Visiting->getFirstNonPHI(); if (VisitingHead->isEHPad()) { // Mark this funclet head as a member of itself. Color = Visiting; } // Note that this is a member of the given color. ColorVector &Colors = BlockColors[Visiting]; if (std::find(Colors.begin(), Colors.end(), Color) == Colors.end()) Colors.push_back(Color); else continue; DEBUG_WITH_TYPE("winehprepare-coloring", dbgs() << " Assigned color \'" << Color->getName() << "\' to block \'" << Visiting->getName() << "\'.\n"); BasicBlock *SuccColor = Color; TerminatorInst *Terminator = Visiting->getTerminator(); if (auto *CatchRet = dyn_cast<CatchReturnInst>(Terminator)) { Value *ParentPad = CatchRet->getParentPad(); if (isa<ConstantTokenNone>(ParentPad)) SuccColor = EntryBlock; else SuccColor = cast<Instruction>(ParentPad)->getParent(); } for (BasicBlock *Succ : successors(Visiting)) Worklist.push_back({Succ, SuccColor}); } return BlockColors; } <commit_msg>Try to appease a buildbot<commit_after>//===- EHPersonalities.cpp - Compute EH-related information ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/EHPersonalities.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; /// See if the given exception handling personality function is one that we /// understand. If so, return a description of it; otherwise return Unknown. EHPersonality llvm::classifyEHPersonality(const Value *Pers) { const Function *F = Pers ? dyn_cast<Function>(Pers->stripPointerCasts()) : nullptr; if (!F) return EHPersonality::Unknown; return StringSwitch<EHPersonality>(F->getName()) .Case("__gnat_eh_personality", EHPersonality::GNU_Ada) .Case("__gxx_personality_v0", EHPersonality::GNU_CXX) .Case("__gcc_personality_v0", EHPersonality::GNU_C) .Case("__objc_personality_v0", EHPersonality::GNU_ObjC) .Case("_except_handler3", EHPersonality::MSVC_X86SEH) .Case("_except_handler4", EHPersonality::MSVC_X86SEH) .Case("__C_specific_handler", EHPersonality::MSVC_Win64SEH) .Case("__CxxFrameHandler3", EHPersonality::MSVC_CXX) .Case("ProcessCLRException", EHPersonality::CoreCLR) .Default(EHPersonality::Unknown); } bool llvm::canSimplifyInvokeNoUnwind(const Function *F) { EHPersonality Personality = classifyEHPersonality(F->getPersonalityFn()); // We can't simplify any invokes to nounwind functions if the personality // function wants to catch asynch exceptions. The nounwind attribute only // implies that the function does not throw synchronous exceptions. return !isAsynchronousEHPersonality(Personality); } DenseMap<BasicBlock *, ColorVector> llvm::colorEHFunclets(Function &F) { SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist; BasicBlock *EntryBlock = &F.getEntryBlock(); DenseMap<BasicBlock *, ColorVector> BlockColors; // Build up the color map, which maps each block to its set of 'colors'. // For any block B the "colors" of B are the set of funclets F (possibly // including a root "funclet" representing the main function) such that // F will need to directly contain B or a copy of B (where the term "directly // contain" is used to distinguish from being "transitively contained" in // a nested funclet). // // Note: Despite not being funclets in the truest sense, terminatepad and // catchswitch are considered to belong to their own funclet for the purposes // of coloring. DEBUG_WITH_TYPE("winehprepare-coloring", dbgs() << "\nColoring funclets for " << F.getName() << "\n"); Worklist.push_back({EntryBlock, EntryBlock}); while (!Worklist.empty()) { BasicBlock *Visiting; BasicBlock *Color; std::tie(Visiting, Color) = Worklist.pop_back_val(); DEBUG_WITH_TYPE("winehprepare-coloring", dbgs() << "Visiting " << Visiting->getName() << ", " << Color->getName() << "\n"); Instruction *VisitingHead = Visiting->getFirstNonPHI(); if (VisitingHead->isEHPad()) { // Mark this funclet head as a member of itself. Color = Visiting; } // Note that this is a member of the given color. ColorVector &Colors = BlockColors[Visiting]; if (std::find(Colors.begin(), Colors.end(), Color) == Colors.end()) Colors.push_back(Color); else continue; DEBUG_WITH_TYPE("winehprepare-coloring", dbgs() << " Assigned color \'" << Color->getName() << "\' to block \'" << Visiting->getName() << "\'.\n"); BasicBlock *SuccColor = Color; TerminatorInst *Terminator = Visiting->getTerminator(); if (auto *CatchRet = dyn_cast<CatchReturnInst>(Terminator)) { Value *ParentPad = CatchRet->getParentPad(); if (isa<ConstantTokenNone>(ParentPad)) SuccColor = EntryBlock; else SuccColor = cast<Instruction>(ParentPad)->getParent(); } for (BasicBlock *Succ : successors(Visiting)) Worklist.push_back({Succ, SuccColor}); } return BlockColors; } <|endoftext|>
<commit_before>/* Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <signal.h> #include "Core/ProtoBuf.h" #include "Core/Time.h" #include "Event/Signal.h" #include "Server/Globals.h" #include "Server/RaftConsensus.h" #include "Server/ServerStats.h" namespace LogCabin { namespace Server { ServerStats::ServerStats(Globals& globals) : globals(globals) , mutex() , enabled(false) , stats() , signalHandler() , timerHandler() { } ServerStats::~ServerStats() { } void ServerStats::enable() { Lock lock(*this); if (!enabled) { // defer construction so that TimerHandler can access config, // and that raft, etc are constructed signalHandler.reset(new SignalHandler(globals.eventLoop, *this)); timerHandler.reset(new TimerHandler(globals.eventLoop, *this)); enabled = true; } } Protocol::ServerStats ServerStats::getCurrent() { Protocol::ServerStats copy; copy.set_start_at(std::chrono::nanoseconds( Core::Time::SystemClock::now().time_since_epoch()).count()); bool enabledCopy; { Lock lock(*this); copy = *lock; enabledCopy = enabled; } if (enabledCopy) { globals.raft->updateServerStats(copy); } copy.set_end_at(std::chrono::nanoseconds( Core::Time::SystemClock::now().time_since_epoch()).count()); return copy; } ServerStats::Lock::Lock(ServerStats& wrapper) : wrapper(wrapper) , lockGuard() { } ServerStats::Lock::~Lock() { } Protocol::ServerStats* ServerStats::Lock::operator->() { return &wrapper.stats; } Protocol::ServerStats& ServerStats::Lock::operator*() { return wrapper.stats; } ServerStats::SignalHandler::SignalHandler(Event::Loop& eventLoop, ServerStats& serverStats) : Signal(eventLoop, SIGUSR1) , serverStats(serverStats) { } void ServerStats::SignalHandler::handleSignalEvent() { NOTICE("Received %s: ServerStats:\n%s", strsignal(signalNumber), Core::ProtoBuf::dumpString(serverStats.getCurrent()).c_str()); } ServerStats::TimerHandler::TimerHandler(Event::Loop& eventLoop, ServerStats& serverStats) : Timer(eventLoop) , serverStats(serverStats) , intervalNanos(1000 * 1000 * serverStats.globals.config.read<uint64_t>( "statsDumpIntervalMilliseconds", 60000)) { if (intervalNanos != 0) schedule(intervalNanos); } void ServerStats::TimerHandler::handleTimerEvent() { NOTICE("Periodic dump of ServerStats:\n%s", Core::ProtoBuf::dumpString(serverStats.getCurrent()).c_str()); if (intervalNanos != 0) schedule(intervalNanos); } } // namespace LogCabin::Server } // namespace LogCabin <commit_msg>Fix SIGUSR1 ServerStats handler<commit_after>/* Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <signal.h> #include "Core/ProtoBuf.h" #include "Core/Time.h" #include "Event/Signal.h" #include "Server/Globals.h" #include "Server/RaftConsensus.h" #include "Server/ServerStats.h" namespace LogCabin { namespace Server { ServerStats::ServerStats(Globals& globals) : globals(globals) , mutex() , enabled(false) , stats() , signalHandler() , timerHandler() { // Enable signal handler early so that it blocks signals on the main thread // before other threads are started. signalHandler.reset(new SignalHandler(globals.eventLoop, *this)); } ServerStats::~ServerStats() { } void ServerStats::enable() { Lock lock(*this); if (!enabled) { // Defer construction of timer so that TimerHandler constructor can // access globals.config. timerHandler.reset(new TimerHandler(globals.eventLoop, *this)); enabled = true; } } Protocol::ServerStats ServerStats::getCurrent() { Protocol::ServerStats copy; copy.set_start_at(std::chrono::nanoseconds( Core::Time::SystemClock::now().time_since_epoch()).count()); bool enabledCopy; { Lock lock(*this); copy = *lock; enabledCopy = enabled; } if (enabledCopy) { globals.raft->updateServerStats(copy); } copy.set_end_at(std::chrono::nanoseconds( Core::Time::SystemClock::now().time_since_epoch()).count()); return copy; } ServerStats::Lock::Lock(ServerStats& wrapper) : wrapper(wrapper) , lockGuard() { } ServerStats::Lock::~Lock() { } Protocol::ServerStats* ServerStats::Lock::operator->() { return &wrapper.stats; } Protocol::ServerStats& ServerStats::Lock::operator*() { return wrapper.stats; } ServerStats::SignalHandler::SignalHandler(Event::Loop& eventLoop, ServerStats& serverStats) : Signal(eventLoop, SIGUSR1) , serverStats(serverStats) { } void ServerStats::SignalHandler::handleSignalEvent() { NOTICE("Received %s: ServerStats:\n%s", strsignal(signalNumber), Core::ProtoBuf::dumpString(serverStats.getCurrent()).c_str()); } ServerStats::TimerHandler::TimerHandler(Event::Loop& eventLoop, ServerStats& serverStats) : Timer(eventLoop) , serverStats(serverStats) , intervalNanos(1000 * 1000 * serverStats.globals.config.read<uint64_t>( "statsDumpIntervalMilliseconds", 60000)) { if (intervalNanos != 0) schedule(intervalNanos); } void ServerStats::TimerHandler::handleTimerEvent() { NOTICE("Periodic dump of ServerStats:\n%s", Core::ProtoBuf::dumpString(serverStats.getCurrent()).c_str()); if (intervalNanos != 0) schedule(intervalNanos); } } // namespace LogCabin::Server } // namespace LogCabin <|endoftext|>
<commit_before>#include <math.h> #include "YRTGroup.h" #include "YRTScene.h" #include "YRTSphere.h" #include "YRTTriangle.h" #include "YRTUtils.h" #pragma hdrstop TYRTScene::~TYRTScene(void) { delete _shape; } TYRTShape* TYRTScene::GenerateExample_01Triangles(int width, int height) { TYRTGroup *result = new TYRTGroup; TYRTTriangle *triangle; float y = width / 12; float z = width / 6; // Plane: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, y, z); triangle->Points[1] = TYRTVector(width, y, z); triangle->Points[2] = TYRTVector(0, y, z + width); triangle->Color = (TColor)RGB(0, 0, 255); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(width, y, z + width); triangle->Points[1] = TYRTVector(width, y, z); triangle->Points[2] = TYRTVector(0, y, z + width); triangle->Color = (TColor)RGB(255, 0, 0); result->Add(triangle); // Crown: const int count = 12; for (int i = 0; i < count; i++) { float h = 100 + (rand() * 1.0 / RAND_MAX) * height * 2 / 3; float r = width / 3; triangle = new TYRTTriangle; triangle->Points[0].X = width / 2 + r * sin(i * 2 * PI / count + PI / count / 4); triangle->Points[0].Y = y + 0; triangle->Points[0].Z = z + width / 2 + r * cos(i * 2 * PI / count + PI / count / 4); triangle->Points[1].X = width / 2 + r * sin((i + 1) * 2 * PI / count - PI / count / 4); triangle->Points[1].Y = y + 0; triangle->Points[1].Z = z + width / 2 + r * cos((i + 1) * 2 * PI / count - PI / count / 4); triangle->Points[2].X = width / 2 + (r + h / 8) * sin(i * 2 * PI / count + PI / count); triangle->Points[2].Y = y + h; triangle->Points[2].Z = z + width / 2 + (r + h / 8) * cos(i * 2 * PI / count + PI / count); triangle->Color = (TColor)RGB(0, i * 255 / count, 0); result->Add(triangle); } return result; } TYRTShape* TYRTScene::GenerateExample_02Atom(int width, int height) { TYRTGroup *result = new TYRTGroup; TYRTSphere *sphere; sphere = new TYRTSphere; sphere->Center = TYRTVector(0, 0, 0); sphere->Radius = 10; sphere->Color = clBlue; result->Add(sphere); sphere = new TYRTSphere; sphere->Center = TYRTVector(-5, -5, -3); sphere->Radius = 6; sphere->Color = clRed; result->Add(sphere); sphere = new TYRTSphere; sphere->Center = TYRTVector(+5, -5, +3); sphere->Radius = 6; sphere->Color = clRed; result->Add(sphere); // Zoom/move elements into view: result->Zoom(10); result->Move(width / 2, height / 2, 0); return result; } TYRTShape* TYRTScene::GenerateExample_03Starship(float x, float y, float z) { TYRTGroup *result = new TYRTGroup; TYRTTriangle *triangle; TYRTSphere *sphere; // Bottom: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 0, -1, 0); triangle->Points[1] = TYRTVector(-3, 0, -1); triangle->Points[2] = TYRTVector( 0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, -1, 0); triangle->Points[1] = TYRTVector(3, 0, -1); triangle->Points[2] = TYRTVector(0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); result->Add(triangle); // Top: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 0, 1, 0); triangle->Points[1] = TYRTVector(-3, 0, -1); triangle->Points[2] = TYRTVector( 0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, 0.1, 0); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, 1, 0); triangle->Points[1] = TYRTVector(3, 0, -1); triangle->Points[2] = TYRTVector(0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, 0.1, 0); result->Add(triangle); // Sides: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(-3.0 + 1.0/6, 0.0 - 1.0/18, -1.0); triangle->Points[1] = TYRTVector(-3.0 + 1.0/6, 0.1 + 1.0/18, -1.0); triangle->Points[2] = TYRTVector( 0, 0, -9.5); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(-3.0 + 1.0/6, 0.1 + 1.0/18, -1.0); triangle->Points[1] = TYRTVector( 0, 0.1, -9.5); triangle->Points[2] = TYRTVector( 0, 0.0, -9.5); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 3.0 - 1.0/6, 0.0 - 1.0/18, -1.0); triangle->Points[1] = TYRTVector( 3.0 - 1.0/6, 0.1 + 1.0/18, -1.0); triangle->Points[2] = TYRTVector( 0, 0, -9.5); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 3.0 - 1.0/6, 0.1 + 1.0/18, -1.0); triangle->Points[1] = TYRTVector( 0, 0.1, -9.5); triangle->Points[2] = TYRTVector( 0, 0.0, -9.5); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); // Bridge: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(-1.0, 0.0, -1.0); triangle->Points[1] = TYRTVector(-0.5, 1.5, -1.0); triangle->Points[2] = TYRTVector( 0.5, 1.5, -1.0); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 1.0, 0.0, -1.0); triangle->Points[1] = TYRTVector(-1.0, 0.0, -1.0); triangle->Points[2] = TYRTVector( 0.5, 1.5, -1.0); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); // Bottom generator: sphere = new TYRTSphere; sphere->Center = TYRTVector(0, -0.45, -2.5); sphere->Radius = 0.5; sphere->Color = (TColor)RGB(212, 212, 212); result->Add(sphere); // Top generators: sphere = new TYRTSphere; sphere->Center = TYRTVector(-0.5 + 0.1, 1.6, -1.0); sphere->Radius = 0.1; sphere->Color = (TColor)RGB(190, 190, 190); result->Add(sphere); sphere = new TYRTSphere; sphere->Center = TYRTVector( 0.5 - 0.1, 1.6, -1.0); sphere->Radius = 0.1; sphere->Color = (TColor)RGB(190, 190, 190); result->Add(sphere); result->Move(x, y, z); return result; } TYRTShape* TYRTScene::GenerateExample_03Starships(int width, int height) { TYRTGroup *result = new TYRTGroup; result->Add(GenerateExample_03Starship(0, 0, 0)); result->Add(GenerateExample_03Starship(10, 4, 1)); result->Add(GenerateExample_03Starship(-1, 6, 14)); result->Zoom(30); result->Move(170, 150, 100); return result; } TStrings* TYRTScene::GenerateExamples(int width, int height) { TStringList* result = new TStringList; result->AddObject("Triangles", GenerateExample_01Triangles(width, height)); result->AddObject("Atom", GenerateExample_02Atom(width, height)); result->AddObject("Starships", GenerateExample_03Starships(width, height)); return result; } void TYRTScene::GetIntersection(TYRTRay *ray, TColor &color) { TYRTVector point; _shape->GetIntersection(ray, point, color); } void TYRTScene::RunPrecalculations(void) { _shape->RunPrecalculations(); } void TYRTScene::SetShape(TYRTShape *shape) { _shape = shape; } <commit_msg>Startships example fixed<commit_after>#include <math.h> #include "YRTGroup.h" #include "YRTScene.h" #include "YRTSphere.h" #include "YRTTriangle.h" #include "YRTUtils.h" #pragma hdrstop TYRTScene::~TYRTScene(void) { delete _shape; } TYRTShape* TYRTScene::GenerateExample_01Triangles(int width, int height) { TYRTGroup *result = new TYRTGroup; TYRTTriangle *triangle; float y = width / 12; float z = width / 6; // Plane: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, y, z); triangle->Points[1] = TYRTVector(width, y, z); triangle->Points[2] = TYRTVector(0, y, z + width); triangle->Color = (TColor)RGB(0, 0, 255); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(width, y, z + width); triangle->Points[1] = TYRTVector(width, y, z); triangle->Points[2] = TYRTVector(0, y, z + width); triangle->Color = (TColor)RGB(255, 0, 0); result->Add(triangle); // Crown: const int count = 12; for (int i = 0; i < count; i++) { float h = 100 + (rand() * 1.0 / RAND_MAX) * height * 2 / 3; float r = width / 3; triangle = new TYRTTriangle; triangle->Points[0].X = width / 2 + r * sin(i * 2 * PI / count + PI / count / 4); triangle->Points[0].Y = y + 0; triangle->Points[0].Z = z + width / 2 + r * cos(i * 2 * PI / count + PI / count / 4); triangle->Points[1].X = width / 2 + r * sin((i + 1) * 2 * PI / count - PI / count / 4); triangle->Points[1].Y = y + 0; triangle->Points[1].Z = z + width / 2 + r * cos((i + 1) * 2 * PI / count - PI / count / 4); triangle->Points[2].X = width / 2 + (r + h / 8) * sin(i * 2 * PI / count + PI / count); triangle->Points[2].Y = y + h; triangle->Points[2].Z = z + width / 2 + (r + h / 8) * cos(i * 2 * PI / count + PI / count); triangle->Color = (TColor)RGB(0, i * 255 / count, 0); result->Add(triangle); } return result; } TYRTShape* TYRTScene::GenerateExample_02Atom(int width, int height) { TYRTGroup *result = new TYRTGroup; TYRTSphere *sphere; sphere = new TYRTSphere; sphere->Center = TYRTVector(0, 0, 0); sphere->Radius = 10; sphere->Color = clBlue; result->Add(sphere); sphere = new TYRTSphere; sphere->Center = TYRTVector(-5, -5, -3); sphere->Radius = 6; sphere->Color = clRed; result->Add(sphere); sphere = new TYRTSphere; sphere->Center = TYRTVector(+5, -5, +3); sphere->Radius = 6; sphere->Color = clRed; result->Add(sphere); // Zoom/move elements into view: result->Zoom(10); result->Move(width / 2, height / 2, 0); return result; } TYRTShape* TYRTScene::GenerateExample_03Starship(float x, float y, float z) { float deckHeight = 0.1; float epsilon = 0.01; TYRTGroup *result = new TYRTGroup; TYRTTriangle *triangle; TYRTSphere *sphere; // Bottom: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 0, -1, 0); triangle->Points[1] = TYRTVector(-3, 0, -1); triangle->Points[2] = TYRTVector( 0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, -deckHeight, 0); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, -1, 0); triangle->Points[1] = TYRTVector(3, 0, -1); triangle->Points[2] = TYRTVector(0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, -deckHeight, 0); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 0, 0, 0); triangle->Points[1] = TYRTVector(-3, 0, -1); triangle->Points[2] = TYRTVector( 0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, -deckHeight, 0); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, 0, 0); triangle->Points[1] = TYRTVector(3, 0, -1); triangle->Points[2] = TYRTVector(0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, -deckHeight, 0); result->Add(triangle); // Top: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 0, 1, 0); triangle->Points[1] = TYRTVector(-3, 0, -1); triangle->Points[2] = TYRTVector( 0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, deckHeight, 0); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, 1, 0); triangle->Points[1] = TYRTVector(3, 0, -1); triangle->Points[2] = TYRTVector(0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, deckHeight, 0); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 0, 0, 0); triangle->Points[1] = TYRTVector(-3, 0, -1); triangle->Points[2] = TYRTVector( 0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, deckHeight, 0); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(0, 0, 0); triangle->Points[1] = TYRTVector(3, 0, -1); triangle->Points[2] = TYRTVector(0, 0, -10); triangle->Color = (TColor)RGB(190, 190, 190); triangle->Move(0, deckHeight, 0); result->Add(triangle); // Sides: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(-3.0 + 1.0/6, -deckHeight, -1.0); triangle->Points[1] = TYRTVector(-3.0 + 1.0/6, deckHeight, -1.0); triangle->Points[2] = TYRTVector( 0, deckHeight, -9.444); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(-3.0 + 1.0/6, -deckHeight, -1.0); triangle->Points[1] = TYRTVector( 0, deckHeight, -9.444); triangle->Points[2] = TYRTVector( 0, -deckHeight, -9.444); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 3.0 - 1.0/6, -deckHeight, -1.0); triangle->Points[1] = TYRTVector( 3.0 - 1.0/6, deckHeight, -1.0); triangle->Points[2] = TYRTVector( 0, deckHeight, -9.444); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 3.0 - 1.0/6, -deckHeight, -1.0); triangle->Points[1] = TYRTVector( 0, deckHeight, -9.444); triangle->Points[2] = TYRTVector( 0, -deckHeight, -9.444); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); // Bridge: triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector(-1.0, 0.0, -1.0); triangle->Points[1] = TYRTVector(-0.5, 1.5, -1.0); triangle->Points[2] = TYRTVector( 0.5, 1.5, -1.0); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); triangle = new TYRTTriangle; triangle->Points[0] = TYRTVector( 1.0, 0.0, -1.0); triangle->Points[1] = TYRTVector(-1.0, 0.0, -1.0); triangle->Points[2] = TYRTVector( 0.5, 1.5, -1.0); triangle->Color = (TColor)RGB(127, 127, 127); result->Add(triangle); // Bottom generator: sphere = new TYRTSphere; sphere->Center = TYRTVector(0, -0.45, -2.5); sphere->Radius = 0.5; sphere->Color = (TColor)RGB(212, 212, 212); result->Add(sphere); // Top generators: sphere = new TYRTSphere; sphere->Center = TYRTVector(-0.5 + 0.1, 1.6, -1.0); sphere->Radius = 0.1; sphere->Color = (TColor)RGB(190, 190, 190); result->Add(sphere); sphere = new TYRTSphere; sphere->Center = TYRTVector( 0.5 - 0.1, 1.6, -1.0); sphere->Radius = 0.1; sphere->Color = (TColor)RGB(190, 190, 190); result->Add(sphere); result->Move(x, y, z); return result; } TYRTShape* TYRTScene::GenerateExample_03Starships(int width, int height) { TYRTGroup *result = new TYRTGroup; result->Add(GenerateExample_03Starship(0, 0, 0)); result->Add(GenerateExample_03Starship(10, 4, 1)); result->Add(GenerateExample_03Starship(-1, 6, 14)); result->Zoom(30); result->Move(170, 150, 100); return result; } TStrings* TYRTScene::GenerateExamples(int width, int height) { TStringList* result = new TStringList; result->AddObject("Triangles", GenerateExample_01Triangles(width, height)); result->AddObject("Atom", GenerateExample_02Atom(width, height)); result->AddObject("Starships", GenerateExample_03Starships(width, height)); return result; } void TYRTScene::GetIntersection(TYRTRay *ray, TColor &color) { TYRTVector point; _shape->GetIntersection(ray, point, color); } void TYRTScene::RunPrecalculations(void) { _shape->RunPrecalculations(); } void TYRTScene::SetShape(TYRTShape *shape) { _shape = shape; } <|endoftext|>
<commit_before>#include "collection.h" #include "jsonlistmodel.h" namespace com { namespace cutehacks { namespace gel { Collection::Collection(QObject *parent) : QSortFilterProxyModel(parent) { connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(emitCountChanged())); connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(emitCountChanged())); sort(0); } QJSValue Collection::comparator() const { return m_comparator; } QJSValue Collection::filter() const { return m_filter; } JsonListModel *Collection::model() const { return qobject_cast<JsonListModel*>(sourceModel()); } void Collection::setComparator(QJSValue comparator) { if (m_comparator.strictlyEquals(comparator)) return; m_comparator = comparator; updateModel(); emit comparatorChanged(comparator); } void Collection::setFilter(QJSValue filter) { if (m_filter.strictlyEquals(filter)) return; m_filter = filter; invalidateFilter(); emit filterChanged(filter); } void Collection::setModel(JsonListModel *model) { JsonListModel *oldModel = qobject_cast<JsonListModel*>(sourceModel()); if (oldModel == model) return; if (oldModel) { disconnect(oldModel, SIGNAL(rolesChanged()), this, SLOT(rolesChanged())); } setSourceModel(model); updateModel(); connect(model, SIGNAL(rolesChanged()), this, SLOT(rolesChanged())); connect(model, SIGNAL(countChanged(int)), this, SLOT(emitCountChanged())); emit modelChanged(model); } void Collection::rolesChanged() { resetInternalData(); updateModel(); } void Collection::emitCountChanged() { emit countChanged(rowCount()); } void Collection::updateModel() { if (model() && m_comparator.isString()) { int role = model()->getRole(m_comparator.toString()); setSortRole(role); } } bool Collection::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { if (m_filter.isCallable()) { QJSValue result = m_filter.call(QJSValueList() << model()->at(source_row) << source_row); return result.toBool(); } else { return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); } } bool Collection::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const { if (m_comparator.isCallable()) { QJSValue left = model()->at(source_left.row()); QJSValue right = model()->at(source_right.row()); QJSValue result = m_comparator.call(QJSValueList() << left << right); return result.toBool(); } else { return QSortFilterProxyModel::lessThan(source_left, source_right); } } QJSValue Collection::at(int row) const { QModelIndex m = index(row, 0); QModelIndex source = mapToSource(m); return model()->at(source.row()); } void Collection::reSort() { if (dynamicSortFilter()) { // Workaround: If dynamic_sortfilter == true, sort(0) will not (always) // result in d->sort() being called, but setDynamicSortFilter(true) will. setDynamicSortFilter(true); } else { sort(0); } } void Collection::reFilter() { invalidateFilter(); } } } } <commit_msg>Fix code style to be consistent with rest of project.<commit_after>#include "collection.h" #include "jsonlistmodel.h" namespace com { namespace cutehacks { namespace gel { Collection::Collection(QObject *parent) : QSortFilterProxyModel(parent) { connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(emitCountChanged())); connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(emitCountChanged())); sort(0); } QJSValue Collection::comparator() const { return m_comparator; } QJSValue Collection::filter() const { return m_filter; } JsonListModel *Collection::model() const { return qobject_cast<JsonListModel*>(sourceModel()); } void Collection::setComparator(QJSValue comparator) { if (m_comparator.strictlyEquals(comparator)) return; m_comparator = comparator; updateModel(); emit comparatorChanged(comparator); } void Collection::setFilter(QJSValue filter) { if (m_filter.strictlyEquals(filter)) return; m_filter = filter; invalidateFilter(); emit filterChanged(filter); } void Collection::setModel(JsonListModel *model) { JsonListModel *oldModel = qobject_cast<JsonListModel*>(sourceModel()); if (oldModel == model) return; if (oldModel) { disconnect(oldModel, SIGNAL(rolesChanged()), this, SLOT(rolesChanged())); } setSourceModel(model); updateModel(); connect(model, SIGNAL(rolesChanged()), this, SLOT(rolesChanged())); connect(model, SIGNAL(countChanged(int)), this, SLOT(emitCountChanged())); emit modelChanged(model); } void Collection::rolesChanged() { resetInternalData(); updateModel(); } void Collection::emitCountChanged() { emit countChanged(rowCount()); } void Collection::updateModel() { if (model() && m_comparator.isString()) { int role = model()->getRole(m_comparator.toString()); setSortRole(role); } } bool Collection::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { if (m_filter.isCallable()) { QJSValue result = m_filter.call(QJSValueList() << model()->at(source_row) << source_row); return result.toBool(); } else { return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); } } bool Collection::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const { if (m_comparator.isCallable()) { QJSValue left = model()->at(source_left.row()); QJSValue right = model()->at(source_right.row()); QJSValue result = m_comparator.call(QJSValueList() << left << right); return result.toBool(); } else { return QSortFilterProxyModel::lessThan(source_left, source_right); } } QJSValue Collection::at(int row) const { QModelIndex m = index(row, 0); QModelIndex source = mapToSource(m); return model()->at(source.row()); } void Collection::reSort() { if (dynamicSortFilter()) { // Workaround: If dynamic_sortfilter == true, sort(0) will not (always) // result in d->sort() being called, but setDynamicSortFilter(true) will. setDynamicSortFilter(true); } else { sort(0); } } void Collection::reFilter() { invalidateFilter(); } } } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP #define STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/log.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/size_zero.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/value_of_rec.hpp> #include <stan/math/prim/functor/operands_and_partials.hpp> #include <Eigen/Core> #include <cmath> namespace stan { namespace math { /** \ingroup multivar_dists * Returns the log PMF of the Generalized Linear Model (GLM) * with categorical distribution and logit (softmax) link function. * * @tparam T_y type of classes. It can be either `std::vector<int>` or `int`. * @tparam T_x_scalar type of the matrix of independent variables (features) * @tparam T_alpha type of the intercept vector * @tparam T_beta type of the matrix of weights * @param y a scalar or vector of classes. If it is a scalar it will be * broadcast - used for all instances. Values should be between 1 and number of * classes, including endpoints. * @param x design matrix or row vector. If it is a row vector it will be * broadcast - used for all instances. * @param alpha intercept vector (in log odds) * @param beta weight matrix * @return log probability or log sum of probabilities * @throw std::domain_error x, beta or alpha is infinite or y is not within * bounds * @throw std::invalid_argument if container sizes mismatch. */ template <bool propto, typename T_y, typename T_x, typename T_alpha, typename T_beta, require_eigen_t<T_x>* = nullptr, require_eigen_col_vector_t<T_alpha>* = nullptr, require_eigen_matrix_t<T_beta>* = nullptr> return_type_t<T_x, T_alpha, T_beta> categorical_logit_glm_lpmf( const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta) { using T_partials_return = partials_return_t<T_x, T_alpha, T_beta>; using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; using std::exp; using std::log; using T_y_ref = ref_type_t<T_y>; using T_x_ref = ref_type_if_t<!is_constant<T_x>::value, T_x>; using T_alpha_ref = ref_type_if_t<!is_constant<T_alpha>::value, T_alpha>; using T_beta_ref = ref_type_if_t<!is_constant<T_beta>::value, T_beta>; constexpr int T_x_rows = T_x::RowsAtCompileTime; const size_t N_instances = T_x_rows == 1 ? stan::math::size(y) : x.rows(); const size_t N_attributes = x.cols(); const size_t N_classes = beta.cols(); static const char* function = "categorical_logit_glm_lpmf"; check_consistent_size(function, "Vector of dependent variables", y, N_instances); check_consistent_size(function, "Intercept vector", alpha, N_classes); check_size_match(function, "x.cols()", N_attributes, "beta.rows()", beta.rows()); if (size_zero(y) || N_classes == 1) { return 0; } T_y_ref y_ref = y; check_bounded(function, "categorical outcome out of support", y_ref, 1, N_classes); if (!include_summand<propto, T_x, T_alpha, T_beta>::value) { return 0; } T_x_ref x_ref = x; T_alpha_ref alpha_ref = alpha; T_beta_ref beta_ref = beta; const auto& x_val = to_ref_if<!is_constant<T_beta>::value>(value_of_rec(x_ref)); const auto& alpha_val = value_of_rec(alpha_ref); const auto& beta_val = to_ref_if<!is_constant<T_x>::value>(value_of_rec(beta_ref)); const auto& alpha_val_vec = as_column_vector_or_scalar(alpha_val).transpose(); Array<T_partials_return, T_x_rows, Dynamic> lin = (x_val * beta_val).rowwise() + alpha_val_vec; Array<T_partials_return, T_x_rows, 1> lin_max = lin.rowwise().maxCoeff(); // This is used to prevent overflow when // calculating softmax/log_sum_exp and // similar expressions Array<T_partials_return, T_x_rows, Dynamic> exp_lin = exp(lin.colwise() - lin_max); Array<T_partials_return, T_x_rows, 1> inv_sum_exp_lin = 1 / exp_lin.rowwise().sum(); T_partials_return logp = log(inv_sum_exp_lin).sum() - lin_max.sum(); if (T_x_rows == 1) { logp *= N_instances; } scalar_seq_view<T_y_ref> y_seq(y_ref); for (int i = 0; i < N_instances; i++) { if (T_x_rows == 1) { logp += lin(0, y_seq[i] - 1); } else { logp += lin(i, y_seq[i] - 1); } } // TODO(Tadej) maybe we can replace previous block with the following line // when we have newer Eigen T_partials_return logp = // lin(Eigen::all,y-1).sum() + log(inv_sum_exp_lin).sum() - lin_max.sum(); if (!std::isfinite(logp)) { check_finite(function, "Weight vector", beta_ref); check_finite(function, "Intercept", alpha_ref); check_finite(function, "Matrix of independent variables", x_ref); } // Compute the derivatives. operands_and_partials<T_x_ref, T_alpha_ref, T_beta_ref> ops_partials( x_ref, alpha_ref, beta_ref); if (!is_constant_all<T_x>::value) { if (T_x_rows == 1) { Array<double, 1, Dynamic> beta_y = beta_val.col(y_seq[0] - 1); for (int i = 1; i < N_instances; i++) { beta_y += beta_val.col(y_seq[i] - 1).array(); } ops_partials.edge1_.partials_ = beta_y - (exp_lin.matrix() * beta_val.transpose()).array().colwise() * inv_sum_exp_lin * N_instances; } else { Array<double, Dynamic, Dynamic> beta_y(N_instances, N_attributes); for (int i = 0; i < N_instances; i++) { beta_y.row(i) = beta_val.col(y_seq[i] - 1); } ops_partials.edge1_.partials_ = beta_y - (exp_lin.matrix() * beta_val.transpose()).array().colwise() * inv_sum_exp_lin; // TODO(Tadej) maybe we can replace previous block with the following line // when we have newer Eigen ops_partials.edge1_.partials_ = beta_val(y - // 1, all) - (exp_lin.matrix() * beta.transpose()).colwise() * // inv_sum_exp_lin; } } if (!is_constant_all<T_alpha, T_beta>::value) { Array<T_partials_return, T_x_rows, Dynamic> neg_softmax_lin = exp_lin.colwise() * -inv_sum_exp_lin; if (!is_constant_all<T_alpha>::value) { if (T_x_rows == 1) { ops_partials.edge2_.partials_ = neg_softmax_lin.colwise().sum() * N_instances; } else { ops_partials.edge2_.partials_ = neg_softmax_lin.colwise().sum(); } for (int i = 0; i < N_instances; i++) { ops_partials.edge2_.partials_[y_seq[i] - 1] += 1; } } if (!is_constant_all<T_beta>::value) { Matrix<T_partials_return, Dynamic, Dynamic> beta_derivative; if (T_x_rows == 1) { beta_derivative = x_val.transpose() * neg_softmax_lin.matrix() * N_instances; } else { beta_derivative = x_val.transpose() * neg_softmax_lin.matrix(); } for (int i = 0; i < N_instances; i++) { if (T_x_rows == 1) { beta_derivative.col(y_seq[i] - 1) += x_val; } else { beta_derivative.col(y_seq[i] - 1) += x_val.row(i); } } // TODO(Tadej) maybe we can replace previous loop with the following line // when we have newer Eigen ops_partials.edge3_.partials_(Eigen::all, y - // 1) += x_val.colwise.sum().transpose(); ops_partials.edge3_.partials_ = std::move(beta_derivative); } } return ops_partials.build(logp); } template <typename T_y, typename T_x, typename T_alpha, typename T_beta> return_type_t<T_x, T_alpha, T_beta> categorical_logit_glm_lpmf( const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta) { return categorical_logit_glm_lpmf<false>(y, x, alpha, beta); } } // namespace math } // namespace stan #endif <commit_msg>added missing include to categorical_logit_glm_lpmf.hpp<commit_after>#ifndef STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP #define STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/eval.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/log.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/size_zero.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/value_of_rec.hpp> #include <stan/math/prim/functor/operands_and_partials.hpp> #include <Eigen/Core> #include <cmath> namespace stan { namespace math { /** \ingroup multivar_dists * Returns the log PMF of the Generalized Linear Model (GLM) * with categorical distribution and logit (softmax) link function. * * @tparam T_y type of classes. It can be either `std::vector<int>` or `int`. * @tparam T_x_scalar type of the matrix of independent variables (features) * @tparam T_alpha type of the intercept vector * @tparam T_beta type of the matrix of weights * @param y a scalar or vector of classes. If it is a scalar it will be * broadcast - used for all instances. Values should be between 1 and number of * classes, including endpoints. * @param x design matrix or row vector. If it is a row vector it will be * broadcast - used for all instances. * @param alpha intercept vector (in log odds) * @param beta weight matrix * @return log probability or log sum of probabilities * @throw std::domain_error x, beta or alpha is infinite or y is not within * bounds * @throw std::invalid_argument if container sizes mismatch. */ template <bool propto, typename T_y, typename T_x, typename T_alpha, typename T_beta, require_eigen_t<T_x>* = nullptr, require_eigen_col_vector_t<T_alpha>* = nullptr, require_eigen_matrix_t<T_beta>* = nullptr> return_type_t<T_x, T_alpha, T_beta> categorical_logit_glm_lpmf( const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta) { using T_partials_return = partials_return_t<T_x, T_alpha, T_beta>; using Eigen::Array; using Eigen::Dynamic; using Eigen::Matrix; using std::exp; using std::log; using T_y_ref = ref_type_t<T_y>; using T_x_ref = ref_type_if_t<!is_constant<T_x>::value, T_x>; using T_alpha_ref = ref_type_if_t<!is_constant<T_alpha>::value, T_alpha>; using T_beta_ref = ref_type_if_t<!is_constant<T_beta>::value, T_beta>; constexpr int T_x_rows = T_x::RowsAtCompileTime; const size_t N_instances = T_x_rows == 1 ? stan::math::size(y) : x.rows(); const size_t N_attributes = x.cols(); const size_t N_classes = beta.cols(); static const char* function = "categorical_logit_glm_lpmf"; check_consistent_size(function, "Vector of dependent variables", y, N_instances); check_consistent_size(function, "Intercept vector", alpha, N_classes); check_size_match(function, "x.cols()", N_attributes, "beta.rows()", beta.rows()); if (size_zero(y) || N_classes == 1) { return 0; } T_y_ref y_ref = y; check_bounded(function, "categorical outcome out of support", y_ref, 1, N_classes); if (!include_summand<propto, T_x, T_alpha, T_beta>::value) { return 0; } T_x_ref x_ref = x; T_alpha_ref alpha_ref = alpha; T_beta_ref beta_ref = beta; const auto& x_val = to_ref_if<!is_constant<T_beta>::value>(value_of_rec(x_ref)); const auto& alpha_val = value_of_rec(alpha_ref); const auto& beta_val = to_ref_if<!is_constant<T_x>::value>(value_of_rec(beta_ref)); const auto& alpha_val_vec = as_column_vector_or_scalar(alpha_val).transpose(); Array<T_partials_return, T_x_rows, Dynamic> lin = (x_val * beta_val).rowwise() + alpha_val_vec; Array<T_partials_return, T_x_rows, 1> lin_max = lin.rowwise().maxCoeff(); // This is used to prevent overflow when // calculating softmax/log_sum_exp and // similar expressions Array<T_partials_return, T_x_rows, Dynamic> exp_lin = exp(lin.colwise() - lin_max); Array<T_partials_return, T_x_rows, 1> inv_sum_exp_lin = 1 / exp_lin.rowwise().sum(); T_partials_return logp = log(inv_sum_exp_lin).sum() - lin_max.sum(); if (T_x_rows == 1) { logp *= N_instances; } scalar_seq_view<T_y_ref> y_seq(y_ref); for (int i = 0; i < N_instances; i++) { if (T_x_rows == 1) { logp += lin(0, y_seq[i] - 1); } else { logp += lin(i, y_seq[i] - 1); } } // TODO(Tadej) maybe we can replace previous block with the following line // when we have newer Eigen T_partials_return logp = // lin(Eigen::all,y-1).sum() + log(inv_sum_exp_lin).sum() - lin_max.sum(); if (!std::isfinite(logp)) { check_finite(function, "Weight vector", beta_ref); check_finite(function, "Intercept", alpha_ref); check_finite(function, "Matrix of independent variables", x_ref); } // Compute the derivatives. operands_and_partials<T_x_ref, T_alpha_ref, T_beta_ref> ops_partials( x_ref, alpha_ref, beta_ref); if (!is_constant_all<T_x>::value) { if (T_x_rows == 1) { Array<double, 1, Dynamic> beta_y = beta_val.col(y_seq[0] - 1); for (int i = 1; i < N_instances; i++) { beta_y += beta_val.col(y_seq[i] - 1).array(); } ops_partials.edge1_.partials_ = beta_y - (exp_lin.matrix() * beta_val.transpose()).array().colwise() * inv_sum_exp_lin * N_instances; } else { Array<double, Dynamic, Dynamic> beta_y(N_instances, N_attributes); for (int i = 0; i < N_instances; i++) { beta_y.row(i) = beta_val.col(y_seq[i] - 1); } ops_partials.edge1_.partials_ = beta_y - (exp_lin.matrix() * beta_val.transpose()).array().colwise() * inv_sum_exp_lin; // TODO(Tadej) maybe we can replace previous block with the following line // when we have newer Eigen ops_partials.edge1_.partials_ = beta_val(y - // 1, all) - (exp_lin.matrix() * beta.transpose()).colwise() * // inv_sum_exp_lin; } } if (!is_constant_all<T_alpha, T_beta>::value) { Array<T_partials_return, T_x_rows, Dynamic> neg_softmax_lin = exp_lin.colwise() * -inv_sum_exp_lin; if (!is_constant_all<T_alpha>::value) { if (T_x_rows == 1) { ops_partials.edge2_.partials_ = neg_softmax_lin.colwise().sum() * N_instances; } else { ops_partials.edge2_.partials_ = neg_softmax_lin.colwise().sum(); } for (int i = 0; i < N_instances; i++) { ops_partials.edge2_.partials_[y_seq[i] - 1] += 1; } } if (!is_constant_all<T_beta>::value) { Matrix<T_partials_return, Dynamic, Dynamic> beta_derivative; if (T_x_rows == 1) { beta_derivative = x_val.transpose() * neg_softmax_lin.matrix() * N_instances; } else { beta_derivative = x_val.transpose() * neg_softmax_lin.matrix(); } for (int i = 0; i < N_instances; i++) { if (T_x_rows == 1) { beta_derivative.col(y_seq[i] - 1) += x_val; } else { beta_derivative.col(y_seq[i] - 1) += x_val.row(i); } } // TODO(Tadej) maybe we can replace previous loop with the following line // when we have newer Eigen ops_partials.edge3_.partials_(Eigen::all, y - // 1) += x_val.colwise.sum().transpose(); ops_partials.edge3_.partials_ = std::move(beta_derivative); } } return ops_partials.build(logp); } template <typename T_y, typename T_x, typename T_alpha, typename T_beta> return_type_t<T_x, T_alpha, T_beta> categorical_logit_glm_lpmf( const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta) { return categorical_logit_glm_lpmf<false>(y, x, alpha, beta); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* Copyright (c) 2009 - http://ruinwesen.com/ */ #include "Encoders.hh" #include "MidiTools.h" #include "Midi.h" #include "GUI.h" /* handlers */ /** * \addtogroup GUI * * @{ * * \addtogroup gui_encoders Encoder classes * * @{ * * \file * Encoder classes **/ class Encoder; /** * Handle a change in a CCEncoder by sending out the CC, using the * channel and cc out of the CCEncoder object. **/ void CCEncoderHandle(Encoder *enc) { CCEncoder *ccEnc = (CCEncoder *)enc; uint8_t channel = ccEnc->getChannel(); uint8_t cc = ccEnc->getCC(); uint8_t value = ccEnc->getValue(); MidiUart.sendCC(channel, cc, value); } /** * Handle a change in a VarRangeEncoder by setting the variable pointed to by enc->var. **/ void VarRangeEncoderHandle(Encoder *enc) { VarRangeEncoder *rEnc = (VarRangeEncoder *)enc; if (rEnc->var != NULL) { *(rEnc->var) = rEnc->getValue(); } } #ifndef HOST_MIDIDUINO #include <MidiClock.h> /** * Handle an encoder change by setting the MidiClock tempo to the encoder value. **/ void TempoEncoderHandle(Encoder *enc) { MidiClock.setTempo(enc->getValue()); } #endif Encoder::Encoder(const char *_name, encoder_handle_t _handler) : old(0), cur(0), redisplay(false), handler(_handler), fastmode(true), fastmodestep(5), pressmode(false), locked(false) { setName(_name); } void Encoder::checkHandle() { if (cur != old) { if (!locked) { if (handler != NULL) handler(this); } } old = cur; } void Encoder::setName(const char *_name) { if (_name != NULL) m_strncpy_fill(name, _name, 4); name[3] = '\0'; } void Encoder::setValue(int value, bool handle) { if (handle) { cur = value; checkHandle(); } else { old = cur = value; } redisplay = true; } void Encoder::lock() { old_lock = old; locked = true; } void Encoder::unlock() { locked = false; old = old_lock; checkHandle(); } void Encoder::displayAt(int i) { GUI.put_value(i, getValue()); redisplay = false; } bool Encoder::hasChanged() { return old != cur && !locked; } void Encoder::clear() { old = 0; cur = 0; } int Encoder::update(encoder_t *enc) { cur = cur + enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button)); return cur; } /* EnumEncoder */ void EnumEncoder::displayAt(int i) { GUI.put_string_at(i * 4, enumStrings[getValue()]); redisplay = false; } void PEnumEncoder::displayAt(int i) { // GUI.put_p_string_at_fill(i * 4, (PGM_P)(pgm_read_word(enumStrings[getValue()]))); GUI.put_p_string_at(i * 4, (PGM_P)(enumStrings[getValue()])); redisplay = false; } /* RangeEncoder */ int RangeEncoder::update(encoder_t *enc) { int inc = enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button)); cur = limit_value(cur, inc, min, max); return cur; } /* CharEncoder */ CharEncoder::CharEncoder() : RangeEncoder(0, 37) { } char CharEncoder::getChar() { uint8_t val = getValue(); if (val == 0) { return ' '; } if (val < 27) return val - 1+ 'A'; else return (val - 27) + '0'; } void CharEncoder::setChar(char c) { if (c >= 'A' && c <= 'Z') { setValue(c - 'A' + 1); } else if (c >= '0' && c <= '9') { setValue(c - '0' + 26 + 1); } else { setValue(0); } } /* notePitchEncoder */ NotePitchEncoder::NotePitchEncoder(char *_name) : RangeEncoder(0, 127, _name) { setName(_name); } void NotePitchEncoder::displayAt(int i) { char name[5]; getNotePitch(getValue(), name); GUI.put_string_at(i * 4, name); } void MidiTrackEncoder::displayAt(int i) { GUI.put_value(i, getValue() + 1); } /* auto name CC encoder */ void AutoNameCCEncoder::initCCEncoder(uint8_t _channel, uint8_t _cc) { CCEncoder::initCCEncoder(_channel, _cc); setCCName(); GUI.redisplay(); } <commit_msg>Remove checkHandle on encoder unlocking (wait for next GUI loop to take care of that).<commit_after>/* Copyright (c) 2009 - http://ruinwesen.com/ */ #include "Encoders.hh" #include "MidiTools.h" #include "Midi.h" #include "GUI.h" /* handlers */ /** * \addtogroup GUI * * @{ * * \addtogroup gui_encoders Encoder classes * * @{ * * \file * Encoder classes **/ class Encoder; /** * Handle a change in a CCEncoder by sending out the CC, using the * channel and cc out of the CCEncoder object. **/ void CCEncoderHandle(Encoder *enc) { CCEncoder *ccEnc = (CCEncoder *)enc; uint8_t channel = ccEnc->getChannel(); uint8_t cc = ccEnc->getCC(); uint8_t value = ccEnc->getValue(); MidiUart.sendCC(channel, cc, value); } /** * Handle a change in a VarRangeEncoder by setting the variable pointed to by enc->var. **/ void VarRangeEncoderHandle(Encoder *enc) { VarRangeEncoder *rEnc = (VarRangeEncoder *)enc; if (rEnc->var != NULL) { *(rEnc->var) = rEnc->getValue(); } } #ifndef HOST_MIDIDUINO #include <MidiClock.h> /** * Handle an encoder change by setting the MidiClock tempo to the encoder value. **/ void TempoEncoderHandle(Encoder *enc) { MidiClock.setTempo(enc->getValue()); } #endif Encoder::Encoder(const char *_name, encoder_handle_t _handler) : old(0), cur(0), redisplay(false), handler(_handler), fastmode(true), fastmodestep(5), pressmode(false), locked(false) { setName(_name); } void Encoder::checkHandle() { if (cur != old) { if (!locked) { if (handler != NULL) handler(this); } } old = cur; } void Encoder::setName(const char *_name) { if (_name != NULL) m_strncpy_fill(name, _name, 4); name[3] = '\0'; } void Encoder::setValue(int value, bool handle) { if (handle) { cur = value; checkHandle(); } else { old = cur = value; } redisplay = true; } void Encoder::lock() { old_lock = old; locked = true; } void Encoder::unlock() { locked = false; old = old_lock; // checkHandle(); } void Encoder::displayAt(int i) { GUI.put_value(i, getValue()); redisplay = false; } bool Encoder::hasChanged() { return old != cur && !locked; } void Encoder::clear() { old = 0; cur = 0; } int Encoder::update(encoder_t *enc) { cur = cur + enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button)); return cur; } /* EnumEncoder */ void EnumEncoder::displayAt(int i) { GUI.put_string_at(i * 4, enumStrings[getValue()]); redisplay = false; } void PEnumEncoder::displayAt(int i) { // GUI.put_p_string_at_fill(i * 4, (PGM_P)(pgm_read_word(enumStrings[getValue()]))); GUI.put_p_string_at(i * 4, (PGM_P)(enumStrings[getValue()])); redisplay = false; } /* RangeEncoder */ int RangeEncoder::update(encoder_t *enc) { int inc = enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button)); cur = limit_value(cur, inc, min, max); return cur; } /* CharEncoder */ CharEncoder::CharEncoder() : RangeEncoder(0, 37) { } char CharEncoder::getChar() { uint8_t val = getValue(); if (val == 0) { return ' '; } if (val < 27) return val - 1+ 'A'; else return (val - 27) + '0'; } void CharEncoder::setChar(char c) { if (c >= 'A' && c <= 'Z') { setValue(c - 'A' + 1); } else if (c >= '0' && c <= '9') { setValue(c - '0' + 26 + 1); } else { setValue(0); } } /* notePitchEncoder */ NotePitchEncoder::NotePitchEncoder(char *_name) : RangeEncoder(0, 127, _name) { setName(_name); } void NotePitchEncoder::displayAt(int i) { char name[5]; getNotePitch(getValue(), name); GUI.put_string_at(i * 4, name); } void MidiTrackEncoder::displayAt(int i) { GUI.put_value(i, getValue() + 1); } /* auto name CC encoder */ void AutoNameCCEncoder::initCCEncoder(uint8_t _channel, uint8_t _cc) { CCEncoder::initCCEncoder(_channel, _cc); setCCName(); GUI.redisplay(); } <|endoftext|>
<commit_before>#include "brawlmd5.h" #include "brawlextract.h" #include "brawlsdiff.h" #include "find_children.h" using namespace System; using namespace System::Collections::Generic; using namespace System::ComponentModel; using namespace System::IO; using namespace System::Reflection; using namespace System::Text::RegularExpressions; using namespace BrawlLib::SSBB::ResourceNodes; using BrawlLS::MD5; const char* usage_line = "Usage: brawlls [options] filename [path within file]"; const char* usage_help_line = "Run with --help or /? for more information."; const char* usage_desc = R"( -d, --self list only the specified nodes, not their children (akin to ls -d) -R list nodes recursively (akin to ls -R) -c find only the first path that matches (disables wildcards and +s) --help, /? print this message to stdout --xallhelp info about the "xall" command --no-stpm don't list STPM values (default is --stpm) --no-bone don't print bone values (default is --bone) --mdl0 always list sub-nodes of MDL0 models --no-mdl0 never list sub-nodes of MDL0 models The default is to show MDL0 sub-nodes when the node is the working root (specified on the command-line) or its name ends in "osition". -t show node types next to names -m show MD5 checksums next to names --full-path show full path instead of name --format="..." overrides -t, -m, --bone, --no-bone, and --full-path; run "brawlls --formathelp" for more information Elements of the inside-file path can be node names, with or without wildcards (*), or indicies prefixed by "+" (for example, +0 or +17). The + character does not need to be preceded by a slash.)"; const char* format_help = R"( Default format with -t and -m: %~+%i %n %t %b %m %t appears when -t is specified, %m appears for -m, and %b appears by default (but can be turned off with --no-bone.) Available options for --format: %~ indentation for recursive listing (two spaces for each depth) %i index of node in parent (you can use this with + prefix in pathname) %n name of node %p full path of node inside file %t type of node %b trans/rot/scale of MDL0 bones (only appears for MDL0BoneNodes) %m MD5 checksum of original node data %s size in bytes of original node data %% literal % sign)"; int usage(String^ error_msg) { if (error_msg->Length != 0) Console::Error->WriteLine(error_msg + "\n"); Console::Error->WriteLine(gcnew String(usage_line)); Console::Error->WriteLine(gcnew String(usage_help_line)); return 1; } enum class MDL0PrintType { ALWAYS, NEVER, SELECTIVE }; enum class ProgramBehavior { UNDEFINED, NORMAL, EXTRACT_ALL, SDIFF }; template < class T, class U > Boolean isinst(U u) { return dynamic_cast< T >(u) != nullptr; } void print_recursive(TextWriter^ outstream, String^ format, String^ prefix, ResourceNode^ node, MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth); void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj); void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node); int brawlls(array<String^>^ args, TextWriter^ outwriter) { if (args->Length == 0) { return usage(""); } String^ filename; String^ nodepath; String^ format; MDL0PrintType modelsDeep = MDL0PrintType::SELECTIVE; // --mdl0, --no-mdl0 // affects printout only bool recursive = false, // -R stpmValues = true, // --stpm, --no-stpm boneValues = true, // --bone, --no-bone showtype = false, // -t printSelf = false, // -d, --self printMD5 = false, // -m fullpath = false; // --full-path // affects node search bool searchChildren = false; // -c ProgramBehavior behavior = ProgramBehavior::UNDEFINED; List<String^> behavior_arguments; // arguments not otherwise defined that come after the behavior for each(String^ argument in args) { if (argument == "--help" || argument == "/?") { Console::WriteLine(gcnew String(usage_line)); Console::WriteLine(gcnew String(usage_desc)); return 0; } if (argument == "--formathelp") { Console::WriteLine(gcnew String(format_help)); return 0; } if (argument == "--xallhelp") { List<String^> l; l.Add("--help"); return extract_all(nullptr, %l); } if (argument == "--self") printSelf = true; else if (argument == "--stpm") stpmValues = true; else if (argument == "--no-stpm") stpmValues = false; else if (argument == "--bone") boneValues = true; else if (argument == "--no-bone") boneValues = false; else if (argument == "--mdl0") modelsDeep = MDL0PrintType::ALWAYS; else if (argument == "--no-mdl0") modelsDeep = MDL0PrintType::NEVER; else if (argument == "--full-path") fullpath = true; else if (argument->StartsWith("--format=")) format = argument->Substring(9); else if (argument->StartsWith("-")) { for each(char c in argument->Substring(1)) { if (c == 'd') printSelf = true; else if (c == 'R') recursive = true; else if (c == 't') showtype = true; else if (c == 'm') printMD5 = true; else if (c == 'c') searchChildren = true; else { return usage("Invalid argument: " + argument); } } } else { if (filename == nullptr) filename = argument; else if (behavior == ProgramBehavior::UNDEFINED && argument == "xall") behavior = ProgramBehavior::EXTRACT_ALL; else if (behavior == ProgramBehavior::UNDEFINED && argument == "sdiff") behavior = ProgramBehavior::SDIFF; else if (behavior != ProgramBehavior::UNDEFINED) behavior_arguments.Add(argument); else if (nodepath == nullptr) nodepath = argument; else return usage("Error: too many arguments: " + filename + " " + nodepath + " " + argument); } } if (behavior == ProgramBehavior::UNDEFINED) behavior = ProgramBehavior::NORMAL; if (behavior == ProgramBehavior::SDIFF) { if (behavior_arguments.Count < 1 || behavior_arguments.Count > 2) return 1; int width = behavior_arguments.Count == 2 ? Int32::Parse(behavior_arguments[1]) : -1; return brawlsdiff(filename, behavior_arguments[0], width); } if (filename == nullptr) return usage("Error: no filename given."); if (!File::Exists(filename)) return usage("Error: file not found: " + filename); if (format == nullptr) { format = "%~+%i" + (fullpath ? " %p" : " %n") + (showtype ? " %t" : "") + (boneValues ? " %b" : "") + (printMD5 ? " %m" : ""); } ResourceNode^ node = NodeFactory::FromFile(nullptr, filename); List<ResourceNode^> matchingNodes; find_children(node, nodepath, %matchingNodes, searchChildren); if (matchingNodes.Count == 0) return usage("No nodes found matching path: " + nodepath); if (behavior == ProgramBehavior::NORMAL && printSelf) { for each(ResourceNode^ child in matchingNodes) { printf_obj(outwriter, format, "", child); } } else if (matchingNodes.Count > 1) { Console::Error->WriteLine("Search matched " + matchingNodes.Count + " nodes. Use -d or --self to list them."); return 1; } else if (behavior == ProgramBehavior::EXTRACT_ALL) { return extract_all(matchingNodes[0], %behavior_arguments); } else if (matchingNodes[0]->Children->Count == 0) { Console::Error->WriteLine("The node " + matchingNodes[0]->Name + " does not have any children."); return 0; } else { int maxdepth = recursive ? -1 : 1; print_recursive(outwriter, format, "", matchingNodes[0], modelsDeep, stpmValues, true, maxdepth); } } int main(array<String^>^ args) { brawlls(args, Console::Out); } void print_recursive(TextWriter^ outstream, String^ format, String^ prefix, ResourceNode^ node, MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth) { if (!isRoot) { printf_obj(outstream, format, prefix, node); prefix += " "; } if (maxdepth == 0) return; if (isinst<STPMEntryNode^>(node) && stpmValues) { print_properties(outstream, prefix, node); } else { if (isinst<MDL0Node^>(node)) { if (modelsDeep == MDL0PrintType::NEVER) { return; } else if (modelsDeep == MDL0PrintType::SELECTIVE && !isRoot && !node->Name->EndsWith("osition")) { return; } } int newdepth = maxdepth < 0 ? -1 : maxdepth - 1; for each(ResourceNode^ child in node->Children) { print_recursive(outstream, format, prefix, child, modelsDeep, stpmValues, false, newdepth); } } delete node; // calls Dispose(). this may improve performance slightly, but we can't use these nodes later in the program } void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj) { String^ name = obj == nullptr ? "null" : obj->ToString(); String^ bone = ""; if (isinst<MDL0BoneNode^>(obj)) { MDL0BoneNode^ b = (MDL0BoneNode^)obj; bone = "T" + b->Translation; bone += " R" + b->Rotation; bone += " S" + b->Scale; } String^ index = ""; String^ md5 = ""; String^ size = ""; String^ path = ""; if (isinst<ResourceNode^>(obj)) { ResourceNode^ node = (ResourceNode^)obj; if (format->Contains("%m")) { // don't do this if we don't need the data - this does save some time /*if (isinst<MDL0GroupNode^>(node)) { md5 = "Children:"; for each(ResourceNode^ child in node->Children) { md5 += MD5::MD5Str(child)->Substring(0,4) + ","; } } else {*/ // note: mdl0groupnode md5sums always end up the same, so they won't show up in sdiff md5 = "MD5:" + MD5::MD5Str(node); } index = node->Index + ""; size = node->OriginalSource.Length + ""; while (node->Parent != nullptr) { path = node->Name + "/" + path; node = node->Parent; } if (path->EndsWith("/")) path = path->Substring(0, path->Length - 1); } String^ line = format ->Replace("%~", prefix) ->Replace("%n", name) ->Replace("%p", path) ->Replace("%i", index) ->Replace("%t", "(" + obj->GetType()->Name + ")") ->Replace("%b", bone) ->Replace("%m", md5) ->Replace("%s", size) ->Replace("%%", "%"); outstream->WriteLine(line); } void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node) { for each(PropertyInfo^ entry in node->GetType()->GetProperties()) { for each(Attribute^ attribute in entry->GetCustomAttributes(false)) { if (isinst<CategoryAttribute^>(attribute)) { Object^ val = entry->GetValue(node, nullptr); String^ valstr = val == nullptr ? "null" : val->ToString(); outstream->WriteLine(prefix + entry->Name + " " + valstr); } } } } <commit_msg>brawlls can now read from stdin<commit_after>#include "brawlmd5.h" #include "brawlextract.h" #include "brawlsdiff.h" #include "find_children.h" using namespace System; using namespace System::Collections::Generic; using namespace System::ComponentModel; using namespace System::IO; using namespace System::Reflection; using namespace System::Text::RegularExpressions; using namespace BrawlLib::SSBB::ResourceNodes; using BrawlLS::MD5; const char* usage_line = "Usage: brawlls [options] filename [path within file]"; const char* usage_help_line = "Run with --help or /? for more information."; const char* usage_desc = R"( -d, --self list only the specified nodes, not their children (akin to ls -d) -R list nodes recursively (akin to ls -R) -c find only the first path that matches (disables wildcards and +s) --help, /? print this message to stdout --xallhelp info about the "xall" command --no-stpm don't list STPM values (default is --stpm) --no-bone don't print bone values (default is --bone) --mdl0 always list sub-nodes of MDL0 models --no-mdl0 never list sub-nodes of MDL0 models The default is to show MDL0 sub-nodes when the node is the working root (specified on the command-line) or its name ends in "osition". -t show node types next to names -m show MD5 checksums next to names --full-path show full path instead of name --format="..." overrides -t, -m, --bone, --no-bone, and --full-path; run "brawlls --formathelp" for more information Elements of the inside-file path can be node names, with or without wildcards (*), or indicies prefixed by "+" (for example, +0 or +17). The + character does not need to be preceded by a slash.)"; const char* format_help = R"( Default format with -t and -m: %~+%i %n %t %b %m %t appears when -t is specified, %m appears for -m, and %b appears by default (but can be turned off with --no-bone.) Available options for --format: %~ indentation for recursive listing (two spaces for each depth) %i index of node in parent (you can use this with + prefix in pathname) %n name of node %p full path of node inside file %t type of node %b trans/rot/scale of MDL0 bones (only appears for MDL0BoneNodes) %m MD5 checksum of original node data %s size in bytes of original node data %% literal % sign)"; int usage(String^ error_msg) { if (error_msg->Length != 0) Console::Error->WriteLine(error_msg + "\n"); Console::Error->WriteLine(gcnew String(usage_line)); Console::Error->WriteLine(gcnew String(usage_help_line)); return 1; } enum class MDL0PrintType { ALWAYS, NEVER, SELECTIVE }; enum class ProgramBehavior { UNDEFINED, NORMAL, EXTRACT_ALL, SDIFF }; template < class T, class U > Boolean isinst(U u) { return dynamic_cast< T >(u) != nullptr; } void print_recursive(TextWriter^ outstream, String^ format, String^ prefix, ResourceNode^ node, MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth); void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj); void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node); int brawlls(array<String^>^ args, TextWriter^ outwriter) { if (args->Length == 0) { return usage(""); } String^ filename; String^ nodepath; String^ format; MDL0PrintType modelsDeep = MDL0PrintType::SELECTIVE; // --mdl0, --no-mdl0 // affects printout only bool recursive = false, // -R stpmValues = true, // --stpm, --no-stpm boneValues = true, // --bone, --no-bone showtype = false, // -t printSelf = false, // -d, --self printMD5 = false, // -m fullpath = false; // --full-path // affects node search bool searchChildren = false; // -c ProgramBehavior behavior = ProgramBehavior::UNDEFINED; List<String^> behavior_arguments; // arguments not otherwise defined that come after the behavior for each(String^ argument in args) { if (argument == "--help" || argument == "/?") { Console::WriteLine(gcnew String(usage_line)); Console::WriteLine(gcnew String(usage_desc)); return 0; } if (argument == "--formathelp") { Console::WriteLine(gcnew String(format_help)); return 0; } if (argument == "--xallhelp") { List<String^> l; l.Add("--help"); return extract_all(nullptr, %l); } if (argument == "--self") printSelf = true; else if (argument == "--stpm") stpmValues = true; else if (argument == "--no-stpm") stpmValues = false; else if (argument == "--bone") boneValues = true; else if (argument == "--no-bone") boneValues = false; else if (argument == "--mdl0") modelsDeep = MDL0PrintType::ALWAYS; else if (argument == "--no-mdl0") modelsDeep = MDL0PrintType::NEVER; else if (argument == "--full-path") fullpath = true; else if (argument->StartsWith("--format=")) format = argument->Substring(9); else if (argument->StartsWith("-") && argument->Length > 1) { for each(char c in argument->Substring(1)) { if (c == 'd') printSelf = true; else if (c == 'R') recursive = true; else if (c == 't') showtype = true; else if (c == 'm') printMD5 = true; else if (c == 'c') searchChildren = true; else { return usage("Invalid argument: " + argument); } } } else { if (filename == nullptr) filename = argument; else if (behavior == ProgramBehavior::UNDEFINED && argument == "xall") behavior = ProgramBehavior::EXTRACT_ALL; else if (behavior == ProgramBehavior::UNDEFINED && argument == "sdiff") behavior = ProgramBehavior::SDIFF; else if (behavior != ProgramBehavior::UNDEFINED) behavior_arguments.Add(argument); else if (nodepath == nullptr) nodepath = argument; else return usage("Error: too many arguments: " + filename + " " + nodepath + " " + argument); } } if (behavior == ProgramBehavior::UNDEFINED) behavior = ProgramBehavior::NORMAL; if (filename == "-") { String^ tmpfile = Path::GetTempFileName(); Stream^ stdin = Console::OpenStandardInput(); Stream^ outstream = gcnew FileStream(tmpfile, FileMode::Create, FileAccess::Write); array<unsigned char>^ buffer = gcnew array<unsigned char>(2048); int bytes; while ((bytes = stdin->Read(buffer, 0, buffer->Length)) > 0) { outstream->Write(buffer, 0, bytes); } outstream->Close(); filename = tmpfile; } if (behavior == ProgramBehavior::SDIFF) { if (behavior_arguments.Count < 1 || behavior_arguments.Count > 2) return 1; int width = behavior_arguments.Count == 2 ? Int32::Parse(behavior_arguments[1]) : -1; return brawlsdiff(filename, behavior_arguments[0], width); } if (filename == nullptr) return usage("Error: no filename given."); if (!File::Exists(filename)) return usage("Error: file not found: " + filename); if (format == nullptr) { format = "%~+%i" + (fullpath ? " %p" : " %n") + (showtype ? " %t" : "") + (boneValues ? " %b" : "") + (printMD5 ? " %m" : ""); } ResourceNode^ node = NodeFactory::FromFile(nullptr, filename); List<ResourceNode^> matchingNodes; find_children(node, nodepath, %matchingNodes, searchChildren); if (matchingNodes.Count == 0) return usage("No nodes found matching path: " + nodepath); if (behavior == ProgramBehavior::NORMAL && printSelf) { for each(ResourceNode^ child in matchingNodes) { printf_obj(outwriter, format, "", child); } } else if (matchingNodes.Count > 1) { Console::Error->WriteLine("Search matched " + matchingNodes.Count + " nodes. Use -d or --self to list them."); return 1; } else if (behavior == ProgramBehavior::EXTRACT_ALL) { return extract_all(matchingNodes[0], %behavior_arguments); } else if (matchingNodes[0]->Children->Count == 0) { Console::Error->WriteLine("The node " + matchingNodes[0]->Name + " does not have any children."); return 0; } else { int maxdepth = recursive ? -1 : 1; print_recursive(outwriter, format, "", matchingNodes[0], modelsDeep, stpmValues, true, maxdepth); } } int main(array<String^>^ args) { brawlls(args, Console::Out); } void print_recursive(TextWriter^ outstream, String^ format, String^ prefix, ResourceNode^ node, MDL0PrintType modelsDeep, bool stpmValues, bool isRoot, int maxdepth) { if (!isRoot) { printf_obj(outstream, format, prefix, node); prefix += " "; } if (maxdepth == 0) return; if (isinst<STPMEntryNode^>(node) && stpmValues) { print_properties(outstream, prefix, node); } else { if (isinst<MDL0Node^>(node)) { if (modelsDeep == MDL0PrintType::NEVER) { return; } else if (modelsDeep == MDL0PrintType::SELECTIVE && !isRoot && !node->Name->EndsWith("osition")) { return; } } int newdepth = maxdepth < 0 ? -1 : maxdepth - 1; for each(ResourceNode^ child in node->Children) { print_recursive(outstream, format, prefix, child, modelsDeep, stpmValues, false, newdepth); } } delete node; // calls Dispose(). this may improve performance slightly, but we can't use these nodes later in the program } void printf_obj(TextWriter^ outstream, String^ format, String^ prefix, Object^ obj) { String^ name = obj == nullptr ? "null" : obj->ToString(); String^ bone = ""; if (isinst<MDL0BoneNode^>(obj)) { MDL0BoneNode^ b = (MDL0BoneNode^)obj; bone = "T" + b->Translation; bone += " R" + b->Rotation; bone += " S" + b->Scale; } String^ index = ""; String^ md5 = ""; String^ size = ""; String^ path = ""; if (isinst<ResourceNode^>(obj)) { ResourceNode^ node = (ResourceNode^)obj; if (format->Contains("%m")) { // don't do this if we don't need the data - this does save some time /*if (isinst<MDL0GroupNode^>(node)) { md5 = "Children:"; for each(ResourceNode^ child in node->Children) { md5 += MD5::MD5Str(child)->Substring(0,4) + ","; } } else {*/ // note: mdl0groupnode md5sums always end up the same, so they won't show up in sdiff md5 = "MD5:" + MD5::MD5Str(node); } index = node->Index + ""; size = node->OriginalSource.Length + ""; while (node->Parent != nullptr) { path = node->Name + "/" + path; node = node->Parent; } if (path->EndsWith("/")) path = path->Substring(0, path->Length - 1); } String^ line = format ->Replace("%~", prefix) ->Replace("%n", name) ->Replace("%p", path) ->Replace("%i", index) ->Replace("%t", "(" + obj->GetType()->Name + ")") ->Replace("%b", bone) ->Replace("%m", md5) ->Replace("%s", size) ->Replace("%%", "%"); outstream->WriteLine(line); } void print_properties(TextWriter^ outstream, String^ prefix, ResourceNode^ node) { for each(PropertyInfo^ entry in node->GetType()->GetProperties()) { for each(Attribute^ attribute in entry->GetCustomAttributes(false)) { if (isinst<CategoryAttribute^>(attribute)) { Object^ val = entry->GetValue(node, nullptr); String^ valstr = val == nullptr ? "null" : val->ToString(); outstream->WriteLine(prefix + entry->Name + " " + valstr); } } } } <|endoftext|>
<commit_before>/** * @file turbulence.cpp * * @date Jan 7, 2015 * @author Tack */ #include <boost/lexical_cast.hpp> #include "turbulence.h" #include "plugin_factory.h" #include "logger_factory.h" #include "level.h" #include "forecast_time.h" #include "regular_grid.h" #include "util.h" using namespace std; using namespace himan::plugin; turbulence::turbulence() { itsClearTextFormula = "complex formula"; itsLogger = logger_factory::Instance()->GetLog("turbulence"); } void turbulence::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter properties * - name PARM_NAME, this name is found from neons. For example: T-K * - univ_id UNIV_ID, newbase-id, ie code table 204 * - grib1 id must be in database * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml * */ // param theRequestedParam(PARM_NAME, UNIV_ID, GRIB2DISCIPLINE, GRIB2CATEGORY, GRIB2NUMBER); param TI("TI-S2", 1208); param TI2("TI2-S2", 1209); // If this param is also used as a source param for other calculations // (like for example dewpoint, relative humidity), unit should also be // specified TI.Unit(kS2); TI2.Unit(kS2); SetParams({TI,TI2}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void turbulence::Calculate(info_t myTargetInfo, unsigned short threadIndex) { /* * Required source parameters */ const param UParam("U-MS"); const param VParam("V-MS"); const param HParam("HL-M"); // ---- // Current time and level as given to this thread forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); level prevLevel; prevLevel = level(myTargetInfo->Level()); prevLevel.Value(myTargetInfo->Level().Value() - 1); prevLevel.Index(prevLevel.Index() - 1); auto myThreadedLogger = logger_factory::Instance()->GetLog("turbulence_pluginThread #" + boost::lexical_cast<string> (threadIndex)); myThreadedLogger->Debug("Calculating time " + static_cast<string> (forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel)); /*bool firstLevel = false; if (myTargetInfo->Level().Value() == itsTopLevel) { firstLevel = true; } if (firstLevel) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", first hybrid level " + static_cast<string> (forecastLevel)); return; }*/ info_t UInfo, VInfo, HInfo, prevUInfo, prevVInfo, prevHInfo; prevHInfo = Fetch(forecastTime, prevLevel, HParam, false); prevUInfo = Fetch(forecastTime, prevLevel, UParam, false); prevVInfo = Fetch(forecastTime, prevLevel, VParam, false); HInfo = Fetch(forecastTime, forecastLevel, HParam, false); UInfo = Fetch(forecastTime, forecastLevel, UParam, false); VInfo = Fetch(forecastTime, forecastLevel, VParam, false); if (!(prevHInfo && prevUInfo && prevVInfo && HInfo && UInfo && VInfo)) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel)); return; } // If calculating for hybrid levels, A/B vertical coordinates must be set // (copied from source) myTargetInfo->ParamIndex(0); SetAB(myTargetInfo, HInfo); myTargetInfo->ParamIndex(1); SetAB(myTargetInfo, HInfo); string deviceType = "CPU"; double Di = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Di(); double Dj = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Dj(); point firstPoint = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->FirstGridPoint(); size_t Ni = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Ni(); size_t Nj = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Nj(); vector<double> dx (Nj, kFloatMissing); vector<double> dy (Ni, kFloatMissing); for (size_t i=0; i < Ni; ++i) { dy[i] = util::LatitudeLength(0) * Dj / 360; } for (size_t j=0; j < Nj; ++j) { dx[j] = util::LatitudeLength(firstPoint.Y() + double(j) * Dj) * Di / 360; } pair<matrix<double>,matrix<double>> gradU = util::CentralDifference(UInfo->Data(),dx,dy); pair<matrix<double>,matrix<double>> gradV = util::CentralDifference(VInfo->Data(),dx,dy); LOCKSTEP(myTargetInfo, UInfo, VInfo, HInfo, prevUInfo, prevVInfo, prevHInfo) { size_t index = myTargetInfo->LocationIndex(); double U = UInfo->Value(); double V = VInfo->Value(); double H = HInfo->Value(); double prevU = prevUInfo->Value(); double prevV = prevVInfo->Value(); double prevH = prevHInfo->Value(); if (U == kFloatMissing || V == kFloatMissing || H == kFloatMissing || prevU == kFloatMissing || prevV == kFloatMissing || prevH == kFloatMissing) { continue; } //Precalculation of wind shear, deformation and convergence double VWS = sqrt(pow((prevU-U)/(prevH-H),2) + pow((prevV-V)/(prevH-H),2)); double DEF = sqrt(pow(get<0>(gradU).At(index)-get<1>(gradV).At(index),2) + pow(get<0>(gradV).At(index) + get<1>(gradU).At(index),2)); double CVG = -get<0>(gradU).At(index)-get<1>(gradV).At(index); //Calculation of turbulence indices double TI = VWS*DEF; double TI2 = VWS*(DEF+CVG); //return result myTargetInfo->ParamIndex(0); myTargetInfo->Value(TI); myTargetInfo->ParamIndex(1); myTargetInfo->Value(TI2); } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } <commit_msg>Change univ id for TI-S2<commit_after>/** * @file turbulence.cpp * * @date Jan 7, 2015 * @author Tack */ #include <boost/lexical_cast.hpp> #include "turbulence.h" #include "plugin_factory.h" #include "logger_factory.h" #include "level.h" #include "forecast_time.h" #include "regular_grid.h" #include "util.h" using namespace std; using namespace himan::plugin; turbulence::turbulence() { itsClearTextFormula = "complex formula"; itsLogger = logger_factory::Instance()->GetLog("turbulence"); } void turbulence::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter properties * - name PARM_NAME, this name is found from neons. For example: T-K * - univ_id UNIV_ID, newbase-id, ie code table 204 * - grib1 id must be in database * - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml * */ // param theRequestedParam(PARM_NAME, UNIV_ID, GRIB2DISCIPLINE, GRIB2CATEGORY, GRIB2NUMBER); param TI("TI-S2", 1164); param TI2("TI2-S2", 1209); // If this param is also used as a source param for other calculations // (like for example dewpoint, relative humidity), unit should also be // specified TI.Unit(kS2); TI2.Unit(kS2); SetParams({TI,TI2}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void turbulence::Calculate(info_t myTargetInfo, unsigned short threadIndex) { /* * Required source parameters */ const param UParam("U-MS"); const param VParam("V-MS"); const param HParam("HL-M"); // ---- // Current time and level as given to this thread forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); level prevLevel; prevLevel = level(myTargetInfo->Level()); prevLevel.Value(myTargetInfo->Level().Value() - 1); prevLevel.Index(prevLevel.Index() - 1); auto myThreadedLogger = logger_factory::Instance()->GetLog("turbulence_pluginThread #" + boost::lexical_cast<string> (threadIndex)); myThreadedLogger->Debug("Calculating time " + static_cast<string> (forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel)); /*bool firstLevel = false; if (myTargetInfo->Level().Value() == itsTopLevel) { firstLevel = true; } if (firstLevel) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", first hybrid level " + static_cast<string> (forecastLevel)); return; }*/ info_t UInfo, VInfo, HInfo, prevUInfo, prevVInfo, prevHInfo; prevHInfo = Fetch(forecastTime, prevLevel, HParam, false); prevUInfo = Fetch(forecastTime, prevLevel, UParam, false); prevVInfo = Fetch(forecastTime, prevLevel, VParam, false); HInfo = Fetch(forecastTime, forecastLevel, HParam, false); UInfo = Fetch(forecastTime, forecastLevel, UParam, false); VInfo = Fetch(forecastTime, forecastLevel, VParam, false); if (!(prevHInfo && prevUInfo && prevVInfo && HInfo && UInfo && VInfo)) { myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel)); return; } // If calculating for hybrid levels, A/B vertical coordinates must be set // (copied from source) myTargetInfo->ParamIndex(0); SetAB(myTargetInfo, HInfo); myTargetInfo->ParamIndex(1); SetAB(myTargetInfo, HInfo); string deviceType = "CPU"; double Di = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Di(); double Dj = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Dj(); point firstPoint = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->FirstGridPoint(); size_t Ni = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Ni(); size_t Nj = dynamic_cast<regular_grid*> (myTargetInfo->Grid())->Nj(); vector<double> dx (Nj, kFloatMissing); vector<double> dy (Ni, kFloatMissing); for (size_t i=0; i < Ni; ++i) { dy[i] = util::LatitudeLength(0) * Dj / 360; } for (size_t j=0; j < Nj; ++j) { dx[j] = util::LatitudeLength(firstPoint.Y() + double(j) * Dj) * Di / 360; } pair<matrix<double>,matrix<double>> gradU = util::CentralDifference(UInfo->Data(),dx,dy); pair<matrix<double>,matrix<double>> gradV = util::CentralDifference(VInfo->Data(),dx,dy); LOCKSTEP(myTargetInfo, UInfo, VInfo, HInfo, prevUInfo, prevVInfo, prevHInfo) { size_t index = myTargetInfo->LocationIndex(); double U = UInfo->Value(); double V = VInfo->Value(); double H = HInfo->Value(); double prevU = prevUInfo->Value(); double prevV = prevVInfo->Value(); double prevH = prevHInfo->Value(); if (U == kFloatMissing || V == kFloatMissing || H == kFloatMissing || prevU == kFloatMissing || prevV == kFloatMissing || prevH == kFloatMissing) { continue; } //Precalculation of wind shear, deformation and convergence double VWS = sqrt(pow((prevU-U)/(prevH-H),2) + pow((prevV-V)/(prevH-H),2)); double DEF = sqrt(pow(get<0>(gradU).At(index)-get<1>(gradV).At(index),2) + pow(get<0>(gradV).At(index) + get<1>(gradU).At(index),2)); double CVG = -get<0>(gradU).At(index)-get<1>(gradV).At(index); //Calculation of turbulence indices double TI = VWS*DEF; double TI2 = VWS*(DEF+CVG); //return result myTargetInfo->ParamIndex(0); myTargetInfo->Value(TI); myTargetInfo->ParamIndex(1); myTargetInfo->Value(TI2); } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data().Size())); } <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> #include <cmath> // StdAir #include <stdair/basic/BasConst_General.hpp> #include <stdair/basic/BasConst_Inventory.hpp> #include <stdair/bom/BomManager.hpp> #include <stdair/bom/SegmentCabin.hpp> #include <stdair/bom/BookingClass.hpp> #include <stdair/bom/SimpleNestingStructure.hpp> #include <stdair/bom/NestingNode.hpp> #include <stdair/bom/Policy.hpp> #include <stdair/factory/FacBomManager.hpp> #include <stdair/service/Logger.hpp> // RMOL #include <rmol/bom/PolicyHelper.hpp> #include <rmol/bom/Utilities.hpp> #include <rmol/command/MarginalRevenueTransformation.hpp> namespace RMOL { // //////////////////////////////////////////////////////////////////// bool MarginalRevenueTransformation:: prepareDemandInput (stdair::SegmentCabin& ioSegmentCabin) { // Build the convex hull, then adjust the yield and demand of all // classes based on the hull. buildNestedConvexHull (ioSegmentCabin); bool isSucceeded = adjustYieldAndDemand (ioSegmentCabin); return isSucceeded; } // //////////////////////////////////////////////////////////////////// void MarginalRevenueTransformation:: buildConvexHull (stdair::SegmentCabin& ioSegmentCabin) { // Reset the convex hull of the segment. ioSegmentCabin.resetConvexHull(); // The first (from the left side) point of the convex hull is the "empty" // policy, i.e. the one with all fare families closed. const stdair::PolicyList_T& lPolicyList = stdair::BomManager::getList<stdair::Policy> (ioSegmentCabin); // By construction, the empty policy is the first one on the list of // eligible policies. stdair::PolicyList_T::const_iterator itPolicy=lPolicyList.begin(); stdair::Policy* lEmptyPolicy_ptr = *itPolicy; assert (lEmptyPolicy_ptr != NULL); ioSegmentCabin.addPolicy (*lEmptyPolicy_ptr); // Pointer on the current policy of the convex hull. stdair::Policy* lCurrentPolicy_ptr = lEmptyPolicy_ptr; bool lEndOfHull = false; // The end of hull is reached when from the current policy, we cannot // find an other one with greater demand and total revenue. while (lEndOfHull == false) { // Demand and total revenue of the current policy. const double& lCurrentDem = lCurrentPolicy_ptr->getDemand(); const double lCurrentTR = lCurrentPolicy_ptr->getTotalRevenue(); // Search for the next policy. double lGradient = 0.0; stdair::Policy* lNextPolicy_ptr = NULL; for (stdair::PolicyList_T::const_iterator itPol = lPolicyList.begin(); itPol != lPolicyList.end(); ++itPol) { stdair::Policy* lPolicy_ptr = *itPol; assert (lPolicy_ptr != NULL); const double& lDem = lPolicy_ptr->getDemand(); const double lTR = lPolicy_ptr->getTotalRevenue(); if (lDem > lCurrentDem && lTR > lCurrentTR) { const double lNewGradient = (lTR-lCurrentTR)/(lDem-lCurrentDem); if (lNewGradient > lGradient) { lGradient = lNewGradient; lNextPolicy_ptr = lPolicy_ptr; } } } // Check if we have found the next policy if (lNextPolicy_ptr == NULL) { lEndOfHull = true; } else { ioSegmentCabin.addPolicy (*lNextPolicy_ptr); lCurrentPolicy_ptr = lNextPolicy_ptr; } } } // //////////////////////////////////////////////////////////////////// void MarginalRevenueTransformation:: buildNestedConvexHull (stdair::SegmentCabin& ioSegmentCabin) { // Reset the convex hull of the segment. ioSegmentCabin.resetConvexHull(); // The first (from the left side) point of the convex hull is the "empty" // policy, i.e. the one with all fare families closed. const stdair::PolicyList_T& lPolicyList = stdair::BomManager::getList<stdair::Policy> (ioSegmentCabin); // By construction, the empty policy is the first one on the list of // eligible policies. stdair::PolicyList_T::const_iterator itPolicy=lPolicyList.begin(); stdair::Policy* lEmptyPolicy_ptr = *itPolicy; assert (lEmptyPolicy_ptr != NULL); ioSegmentCabin.addPolicy (*lEmptyPolicy_ptr); // Pointer on the current policy of the convex hull. stdair::Policy* lCurrentPolicy_ptr = lEmptyPolicy_ptr; bool lEndOfHull = false; // The end of hull is reached when from the current policy, we cannot // find an other one with greater demand and total revenue. while (lEndOfHull == false) { // Demand and total revenue of the current policy. const double& lCurrentDem = lCurrentPolicy_ptr->getDemand(); const double lCurrentTR = lCurrentPolicy_ptr->getTotalRevenue(); // Search for the next policy. double lGradient = 0.0; stdair::Policy* lNextPolicy_ptr = NULL; for (stdair::PolicyList_T::const_iterator itPol = lPolicyList.begin(); itPol != lPolicyList.end(); ++itPol) { stdair::Policy* lPolicy_ptr = *itPol; assert (lPolicy_ptr != NULL); const double& lDem = lPolicy_ptr->getDemand(); const double lTR = lPolicy_ptr->getTotalRevenue(); if (lDem > lCurrentDem && lTR > lCurrentTR && PolicyHelper::isNested (*lCurrentPolicy_ptr, *lPolicy_ptr)) { const double lNewGradient = (lTR-lCurrentTR)/(lDem-lCurrentDem); if (lNewGradient > lGradient) { lGradient = lNewGradient; lNextPolicy_ptr = lPolicy_ptr; } } } // Check if we have found the next policy if (lNextPolicy_ptr == NULL) { lEndOfHull = true; } else { ioSegmentCabin.addPolicy (*lNextPolicy_ptr); lCurrentPolicy_ptr = lNextPolicy_ptr; } } } // //////////////////////////////////////////////////////////////////// bool MarginalRevenueTransformation:: adjustYieldAndDemand (stdair::SegmentCabin& ioSegmentCabin) { // Reset the yield-based nesting structure stdair::FacBomManager::resetYieldBasedNestingStructure (ioSegmentCabin); unsigned int lBookingClassCounter = 0; // Browse the list of policies on the convex hull, compute the differences // between pairs of consecutive policies. const stdair::PolicyList_T& lConvexHull = ioSegmentCabin.getConvexHull(); stdair::PolicyList_T::const_iterator itCurrentPolicy = lConvexHull.begin(); assert (itCurrentPolicy != lConvexHull.end()); stdair::PolicyList_T::const_iterator itNextPolicy = itCurrentPolicy; ++itNextPolicy; if (itNextPolicy == lConvexHull.end()) { return false; } // Retrieve the yield-based nesting structure. stdair::SimpleNestingStructure& lYieldBasedNS = stdair::BomManager::getObject<stdair::SimpleNestingStructure> (ioSegmentCabin, stdair::YIELD_BASED_NESTING_STRUCTURE_CODE); const stdair::NestingNodeList_T& lNodeList = stdair::BomManager::getList<stdair::NestingNode> (lYieldBasedNS); stdair::NestingNodeList_T::const_iterator itNode = lNodeList.begin(); for (; itNextPolicy != lConvexHull.end(); ++itCurrentPolicy, ++itNextPolicy, ++itNode){ const stdair::Policy* lCurrentPolicy_ptr = *itCurrentPolicy; assert (lCurrentPolicy_ptr != NULL); const stdair::Policy* lNextPolicy_ptr = *itNextPolicy; assert (lNextPolicy_ptr != NULL); // Retrieve the node. If there isn't any node left, create new one. stdair::NestingNode* lNode_ptr = NULL; if (itNode == lNodeList.end()) { // Create a nesting node stdair::NestingNodeCode_T lNodeCode ("XXX"); stdair::NestingNodeKey lNodeKey (lNodeCode); stdair::NestingNode& lNestingNode = stdair::FacBom<stdair::NestingNode>::instance().create (lNodeKey); stdair::FacBomManager::addToList (lYieldBasedNS, lNestingNode); stdair::FacBomManager::linkWithParent (lYieldBasedNS, lNestingNode); lNode_ptr = &lNestingNode; } else { lNode_ptr = *itNode; } assert (lNode_ptr != NULL); PolicyHelper::diffBetweenTwoPolicies (*lNode_ptr, *lNextPolicy_ptr, *lCurrentPolicy_ptr); // Compute the adjusted yield, demand mean and demand standard deviation. // Note: because of the nature of the convex hull, in the adjusted // standard deviation computation, we can take the difference between // the squares of the standard deviations of the two policies instead of // the sum of the squares. const double lAdjustedDemMean = lNextPolicy_ptr->getDemand()-lCurrentPolicy_ptr->getDemand(); assert (lAdjustedDemMean > 0.0); const double& lCurrentStdDev = lCurrentPolicy_ptr->getStdDev(); const double& lNextStdDev = lNextPolicy_ptr->getStdDev(); assert (lNextStdDev > lCurrentStdDev); const double lAdjustedDemStdDev = sqrt (lNextStdDev*lNextStdDev - lCurrentStdDev*lCurrentStdDev); const double lAdjustedYield = (lNextPolicy_ptr->getTotalRevenue()-lCurrentPolicy_ptr->getTotalRevenue())/(lAdjustedDemMean); assert (lAdjustedYield > 0.0); lNode_ptr->setYield (lAdjustedYield); // Browse the list of booking classes in the node. Set the adjusted yield // for each class. However, the adjusted demand forecast will be // distributed only to the first class of the list. const stdair::BookingClassList_T lBCList = stdair::BomManager::getList<stdair::BookingClass> (*lNode_ptr); stdair::BookingClassList_T::const_iterator itBC = lBCList.begin(); assert (itBC != lBCList.end()); stdair::BookingClass* lFirstClass = *itBC; assert (lFirstClass != NULL); lFirstClass->setMean (lAdjustedDemMean); lFirstClass->setStdDev (lAdjustedDemStdDev); for (; itBC != lBCList.end(); ++itBC) { stdair::BookingClass* lClass = *itBC; assert (lClass != NULL); lClass->setAdjustedYield (lAdjustedYield); ++lBookingClassCounter; } } const stdair::BookingClassList_T& lSCBookingClassList = stdair::BomManager::getList<stdair::BookingClass> (ioSegmentCabin); const unsigned int lNbOfBookingClass = lSCBookingClassList.size(); assert (lNbOfBookingClass >= lBookingClassCounter); if (lBookingClassCounter < lNbOfBookingClass) { // At the last node. All the classes which haven't been added to the // nesting structure will be added to the next nesting node, with // an ajusted yield of zero. // Retrieve the node. If there isn't any node left, create new one. stdair::NestingNode* lLastNode_ptr = NULL; if (itNode == lNodeList.end()) { // Create a nesting node stdair::NestingNodeCode_T lNodeCode ("XXX"); stdair::NestingNodeKey lNodeKey (lNodeCode); stdair::NestingNode& lNestingNode = stdair::FacBom<stdair::NestingNode>::instance().create (lNodeKey); stdair::FacBomManager::addToList (lYieldBasedNS, lNestingNode); stdair::FacBomManager::linkWithParent (lYieldBasedNS, lNestingNode); lLastNode_ptr = stdair::BomManager::getObjectPtr<stdair::NestingNode>(lYieldBasedNS, lNodeKey.toString()); } else { lLastNode_ptr = *itNode; } assert (lLastNode_ptr != NULL); const stdair::Policy* lLastPolicy_ptr = *itCurrentPolicy; assert (lLastPolicy_ptr != NULL); PolicyHelper::computeLastNode (*lLastNode_ptr, *lLastPolicy_ptr, ioSegmentCabin); } return true; } } <commit_msg>[DEV] Fixed some types. Reset the nesting structure only if the forecasted demand is not null.<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> #include <cmath> // StdAir #include <stdair/basic/BasConst_General.hpp> #include <stdair/basic/BasConst_Inventory.hpp> #include <stdair/bom/BomManager.hpp> #include <stdair/bom/SegmentCabin.hpp> #include <stdair/bom/BookingClass.hpp> #include <stdair/bom/SimpleNestingStructure.hpp> #include <stdair/bom/NestingNode.hpp> #include <stdair/bom/Policy.hpp> #include <stdair/factory/FacBomManager.hpp> #include <stdair/service/Logger.hpp> // RMOL #include <rmol/bom/PolicyHelper.hpp> #include <rmol/bom/Utilities.hpp> #include <rmol/command/MarginalRevenueTransformation.hpp> namespace RMOL { // //////////////////////////////////////////////////////////////////// bool MarginalRevenueTransformation:: prepareDemandInput (stdair::SegmentCabin& ioSegmentCabin) { // Build the convex hull, then adjust the yield and demand of all // classes based on the hull. buildNestedConvexHull (ioSegmentCabin); bool isSucceeded = adjustYieldAndDemand (ioSegmentCabin); return isSucceeded; } // //////////////////////////////////////////////////////////////////// void MarginalRevenueTransformation:: buildConvexHull (stdair::SegmentCabin& ioSegmentCabin) { // Reset the convex hull of the segment. ioSegmentCabin.resetConvexHull(); // The first (from the left side) point of the convex hull is the "empty" // policy, i.e. the one with all fare families closed. const stdair::PolicyList_T& lPolicyList = stdair::BomManager::getList<stdair::Policy> (ioSegmentCabin); // By construction, the empty policy is the first one on the list of // eligible policies. stdair::PolicyList_T::const_iterator itPolicy=lPolicyList.begin(); stdair::Policy* lEmptyPolicy_ptr = *itPolicy; assert (lEmptyPolicy_ptr != NULL); ioSegmentCabin.addPolicy (*lEmptyPolicy_ptr); // Pointer on the current policy of the convex hull. stdair::Policy* lCurrentPolicy_ptr = lEmptyPolicy_ptr; bool lEndOfHull = false; // The end of hull is reached when from the current policy, we cannot // find an other one with greater demand and total revenue. while (lEndOfHull == false) { // Demand and total revenue of the current policy. const double& lCurrentDem = lCurrentPolicy_ptr->getDemand(); const double lCurrentTR = lCurrentPolicy_ptr->getTotalRevenue(); // Search for the next policy. double lGradient = 0.0; stdair::Policy* lNextPolicy_ptr = NULL; for (stdair::PolicyList_T::const_iterator itPol = lPolicyList.begin(); itPol != lPolicyList.end(); ++itPol) { stdair::Policy* lPolicy_ptr = *itPol; assert (lPolicy_ptr != NULL); const double& lDem = lPolicy_ptr->getDemand(); const double lTR = lPolicy_ptr->getTotalRevenue(); if (lDem > lCurrentDem && lTR > lCurrentTR) { const double lNewGradient = (lTR-lCurrentTR)/(lDem-lCurrentDem); if (lNewGradient > lGradient) { lGradient = lNewGradient; lNextPolicy_ptr = lPolicy_ptr; } } } // Check if we have found the next policy if (lNextPolicy_ptr == NULL) { lEndOfHull = true; } else { ioSegmentCabin.addPolicy (*lNextPolicy_ptr); lCurrentPolicy_ptr = lNextPolicy_ptr; } } } // //////////////////////////////////////////////////////////////////// void MarginalRevenueTransformation:: buildNestedConvexHull (stdair::SegmentCabin& ioSegmentCabin) { // Reset the convex hull of the segment. ioSegmentCabin.resetConvexHull(); // The first (from the left side) point of the convex hull is the "empty" // policy, i.e. the one with all fare families closed. const stdair::PolicyList_T& lPolicyList = stdair::BomManager::getList<stdair::Policy> (ioSegmentCabin); // By construction, the empty policy is the first one on the list of // eligible policies. stdair::PolicyList_T::const_iterator itPolicy=lPolicyList.begin(); stdair::Policy* lEmptyPolicy_ptr = *itPolicy; assert (lEmptyPolicy_ptr != NULL); ioSegmentCabin.addPolicy (*lEmptyPolicy_ptr); // Pointer on the current policy of the convex hull. stdair::Policy* lCurrentPolicy_ptr = lEmptyPolicy_ptr; bool lEndOfHull = false; // The end of hull is reached when from the current policy, we cannot // find an other one with greater demand and total revenue. while (lEndOfHull == false) { // Demand and total revenue of the current policy. const double& lCurrentDem = lCurrentPolicy_ptr->getDemand(); const double lCurrentTR = lCurrentPolicy_ptr->getTotalRevenue(); // Search for the next policy. double lGradient = 0.0; stdair::Policy* lNextPolicy_ptr = NULL; for (stdair::PolicyList_T::const_iterator itPol = lPolicyList.begin(); itPol != lPolicyList.end(); ++itPol) { stdair::Policy* lPolicy_ptr = *itPol; assert (lPolicy_ptr != NULL); const double& lDem = lPolicy_ptr->getDemand(); const double lTR = lPolicy_ptr->getTotalRevenue(); if (lDem > lCurrentDem && lTR > lCurrentTR && PolicyHelper::isNested (*lCurrentPolicy_ptr, *lPolicy_ptr)) { const double lNewGradient = (lTR-lCurrentTR)/(lDem-lCurrentDem); if (lNewGradient > lGradient) { lGradient = lNewGradient; lNextPolicy_ptr = lPolicy_ptr; } } } // Check if we have found the next policy if (lNextPolicy_ptr == NULL) { lEndOfHull = true; } else { ioSegmentCabin.addPolicy (*lNextPolicy_ptr); lCurrentPolicy_ptr = lNextPolicy_ptr; } } } // //////////////////////////////////////////////////////////////////// bool MarginalRevenueTransformation:: adjustYieldAndDemand (stdair::SegmentCabin& ioSegmentCabin) { bool isSucceeded = false; stdair::NbOfClasses_T lBookingClassCounter = 0; // Browse the list of policies on the convex hull, compute the differences // between pairs of consecutive policies. const stdair::PolicyList_T& lConvexHull = ioSegmentCabin.getConvexHull(); stdair::PolicyList_T::const_iterator itCurrentPolicy = lConvexHull.begin(); assert (itCurrentPolicy != lConvexHull.end()); stdair::PolicyList_T::const_iterator itNextPolicy = itCurrentPolicy; ++itNextPolicy; // If the nesting has only one element (the empty policy), // there is no optimisation and no pre-optimisation. if (itNextPolicy == lConvexHull.end()) { return isSucceeded; } // Reset the yield-based nesting structure stdair::FacBomManager::resetYieldBasedNestingStructure (ioSegmentCabin); // Retrieve the yield-based nesting structure. stdair::SimpleNestingStructure& lYieldBasedNS = stdair::BomManager::getObject<stdair::SimpleNestingStructure> (ioSegmentCabin, stdair::YIELD_BASED_NESTING_STRUCTURE_CODE); const stdair::NestingNodeList_T& lNodeList = stdair::BomManager::getList<stdair::NestingNode> (lYieldBasedNS); stdair::NestingNodeList_T::const_iterator itNode = lNodeList.begin(); for (; itNextPolicy != lConvexHull.end(); ++itCurrentPolicy, ++itNextPolicy, ++itNode){ const stdair::Policy* lCurrentPolicy_ptr = *itCurrentPolicy; assert (lCurrentPolicy_ptr != NULL); const stdair::Policy* lNextPolicy_ptr = *itNextPolicy; assert (lNextPolicy_ptr != NULL); // Retrieve the node. If there isn't any node left, create new one. stdair::NestingNode* lNode_ptr = NULL; if (itNode == lNodeList.end()) { // Create a nesting node stdair::NestingNodeCode_T lNodeCode ("XXX"); stdair::NestingNodeKey lNodeKey (lNodeCode); stdair::NestingNode& lNestingNode = stdair::FacBom<stdair::NestingNode>::instance().create (lNodeKey); stdair::FacBomManager::addToList (lYieldBasedNS, lNestingNode); stdair::FacBomManager::linkWithParent (lYieldBasedNS, lNestingNode); lNode_ptr = &lNestingNode; } else { lNode_ptr = *itNode; } assert (lNode_ptr != NULL); PolicyHelper::diffBetweenTwoPolicies (*lNode_ptr, *lNextPolicy_ptr, *lCurrentPolicy_ptr); // Compute the adjusted yield, demand mean and demand standard deviation. // Note: because of the nature of the convex hull, in the adjusted // standard deviation computation, we can take the difference between // the squares of the standard deviations of the two policies instead of // the sum of the squares. const stdair::MeanValue_T lAdjustedDemMean = lNextPolicy_ptr->getDemand()-lCurrentPolicy_ptr->getDemand(); assert (lAdjustedDemMean > 0.0); const stdair::StdDevValue_T& lCurrentStdDev = lCurrentPolicy_ptr->getStdDev(); const stdair::StdDevValue_T& lNextStdDev = lNextPolicy_ptr->getStdDev(); assert (lNextStdDev > lCurrentStdDev); const stdair::StdDevValue_T lAdjustedDemStdDev = std::sqrt (lNextStdDev*lNextStdDev - lCurrentStdDev*lCurrentStdDev); const stdair::Yield_T lAdjustedYield = (lNextPolicy_ptr->getTotalRevenue()-lCurrentPolicy_ptr->getTotalRevenue())/(lAdjustedDemMean); assert (lAdjustedYield > 0.0); lNode_ptr->setYield (lAdjustedYield); // Browse the list of booking classes in the node. Set the adjusted yield // for each class. However, the adjusted demand forecast will be // distributed only to the first class of the list. const stdair::BookingClassList_T lBCList = stdair::BomManager::getList<stdair::BookingClass> (*lNode_ptr); stdair::BookingClassList_T::const_iterator itBC = lBCList.begin(); assert (itBC != lBCList.end()); stdair::BookingClass* lFirstClass = *itBC; assert (lFirstClass != NULL); lFirstClass->setMean (lAdjustedDemMean); lFirstClass->setStdDev (lAdjustedDemStdDev); for (; itBC != lBCList.end(); ++itBC) { stdair::BookingClass* lClass = *itBC; assert (lClass != NULL); lClass->setAdjustedYield (lAdjustedYield); ++lBookingClassCounter; } } const stdair::BookingClassList_T& lSCBookingClassList = stdair::BomManager::getList<stdair::BookingClass> (ioSegmentCabin); const stdair::NbOfClasses_T lNbOfBookingClass = lSCBookingClassList.size(); assert (lNbOfBookingClass >= lBookingClassCounter); if (lBookingClassCounter < lNbOfBookingClass) { // At the last node. All the classes which haven't been added to the // nesting structure will be added to the next nesting node, with // an adjusted yield of zero. // Retrieve the node. If there isn't any node left, create new one. stdair::NestingNode* lLastNode_ptr = NULL; if (itNode == lNodeList.end()) { // Create a nesting node stdair::NestingNodeCode_T lNodeCode ("XXX"); stdair::NestingNodeKey lNodeKey (lNodeCode); stdair::NestingNode& lNestingNode = stdair::FacBom<stdair::NestingNode>::instance().create (lNodeKey); stdair::FacBomManager::addToList (lYieldBasedNS, lNestingNode); stdair::FacBomManager::linkWithParent (lYieldBasedNS, lNestingNode); lLastNode_ptr = stdair::BomManager::getObjectPtr<stdair::NestingNode>(lYieldBasedNS, lNodeKey.toString()); } else { lLastNode_ptr = *itNode; } assert (lLastNode_ptr != NULL); const stdair::Policy* lLastPolicy_ptr = *itCurrentPolicy; assert (lLastPolicy_ptr != NULL); PolicyHelper::computeLastNode (*lLastNode_ptr, *lLastPolicy_ptr, ioSegmentCabin); } isSucceeded = true; return isSucceeded; } } <|endoftext|>
<commit_before>#include "rosplan_planning_system/PlanDispatcher.h" #include <map> namespace KCL_rosplan { int PlanDispatcher::getCurrentAction() { return current_action; } void PlanDispatcher::reset() { dispatch_paused = false; current_action = 0; action_received.clear(); action_completed.clear(); replan_requested = false; } /*-----------------*/ /* action dispatch */ /*-----------------*/ /* * Loop through and publish planned actions */ bool PlanDispatcher::dispatchPlan(const std::vector<rosplan_dispatch_msgs::ActionDispatch> &actionList, double missionStart, double planStart) { ros::NodeHandle nh("~"); ros::Rate loop_rate(10); ROS_INFO("KCL: (PS) Dispatching plan"); replan_requested = false; bool repeatAction = false; while (ros::ok() && actionList.size() > current_action) { // get next action rosplan_dispatch_msgs::ActionDispatch currentMessage = actionList[current_action]; if((unsigned int)currentMessage.action_id != current_action) ROS_ERROR("KCL: (PS) Message action_id [%d] does not meet expected [%zu]", currentMessage.action_id, current_action); // loop while waiting for dispatch time if(!dispatch_on_completion) { double wait_period = 10.0; int wait_print = (int)(currentMessage.dispatch_time + planStart - ros::WallTime::now().toSec()) / wait_period; while (ros::ok() && ros::WallTime::now().toSec() < currentMessage.dispatch_time + planStart) { ros::spinOnce(); loop_rate.sleep(); double remaining = planStart + currentMessage.dispatch_time - ros::WallTime::now().toSec(); if(wait_print > (int)remaining / wait_period) { ROS_INFO("KCL: (PS) Waiting %f before dispatching action: [%i, %s, %f, %f]", remaining,currentMessage.action_id, currentMessage.name.c_str(), (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration); wait_print--; } } } if(!checkPreconditions(currentMessage)) { ROS_INFO("KCL: (PS) Preconditions not achieved [%i, %s]", currentMessage.action_id, currentMessage.name.c_str()); } // dispatch action ROS_INFO("KCL: (PS) Dispatching action [%i, %s, %f, %f]", currentMessage.action_id, currentMessage.name.c_str(), (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration); action_publisher.publish(currentMessage); double late_print = (ros::WallTime::now().toSec() - (currentMessage.dispatch_time + planStart)); if(late_print>0.1) ROS_INFO("KCL: (PS) Action [%i] is %f second(s) late", currentMessage.action_id, late_print); // wait for action to complete if(!dispatch_concurrent) { int counter = 0; while (ros::ok() && !action_completed[current_action]) { ros::spinOnce(); loop_rate.sleep(); counter++; if (counter == 2000) { ROS_INFO("KCL: (PS) Action %i timed out now. Cancelling...", currentMessage.action_id); rosplan_dispatch_msgs::ActionDispatch cancelMessage; cancelMessage.action_id = currentMessage.action_id; cancelMessage.name = "cancel_action"; action_publisher.publish(cancelMessage); } } } // get ready for next action if(!repeatAction) current_action++; repeatAction = false; action_received[current_action] = false; action_completed[current_action] = false; // finish dispatch and replan if(replan_requested) return false; } return true; } bool PlanDispatcher::checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg) { // setup service call ros::NodeHandle nh; ros::ServiceClient queryKnowledgeClient = nh.serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>("/kcl_rosplan/query_knowledge_base"); rosplan_knowledge_msgs::KnowledgeQueryService querySrv; std::map<std::string, std::vector<std::vector<std::string> > >::iterator oit; oit = environment.domain_operator_precondition_map.find(msg.name); if(oit==environment.domain_operator_precondition_map.end()) return false; // iterate through conditions std::vector<std::vector<std::string> >::iterator cit = oit->second.begin(); for(; cit!=oit->second.end(); cit++) { rosplan_knowledge_msgs::KnowledgeItem condition; // set fact or function std::map<std::string,std::vector<std::string> >::iterator dit = environment.domain_predicates.find((*cit)[0]); if(dit!=environment.domain_predicates.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE; dit = environment.domain_functions.find((*cit)[0]); if(dit!=environment.domain_functions.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION; // populate parameters condition.attribute_name = (*cit)[0]; std::vector<diagnostic_msgs::KeyValue>::iterator pit; int index = 0; for(pit = msg.parameters.begin(); pit!=msg.parameters.end(); pit++) { diagnostic_msgs::KeyValue param; param.key = domain_predicates[(*cit)[0]][index]; param.value = pit->value; condition.values.push_back(param); index++; } querySrv.request.knowledge.push_back(condition); } // check conditions in knowledge base if (queryKnowledgeClient.call(querySrv)) { if(!querySrv.response.all_true) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator kit; for(kit=querySrv.response.false_knowledge.begin(); kit != querySrv.response.false_knowledge.end(); kit++) ROS_INFO("KCL: (PS) [%s]", kit->attribute_name.c_str()); } return querySrv.response.all_true; } else { ROS_ERROR("KCL: (PS) Failed to call service /kcl_rosplan/query_knowledge_base"); } } /*------------------*/ /* general feedback */ /*------------------*/ /** * listen to and process actionFeedback topic. */ void PlanDispatcher::feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) { // create error if the action is unrecognised ROS_INFO("KCL: (PS) Feedback received [%i,%s]", msg->action_id, msg->status.c_str()); if(current_action != (unsigned int)msg->action_id) ROS_ERROR("KCL: (PS) Unexpected action ID: %d; current action: %zu", msg->action_id, current_action); // action enabled if(!action_received[msg->action_id] && (0 == msg->status.compare("action enabled"))) action_received[msg->action_id] = true; // more specific feedback actionFeedback(msg); // action completed (successfuly) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action achieved")) action_completed[msg->action_id] = true; // action completed (failed) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action failed")) { replan_requested = true; action_completed[msg->action_id] = true; } } /*---------------------------*/ /* Specific action responses */ /*---------------------------*/ /** * processes single action feedback message. * This method serves as the hook for defining more interesting behaviour on action feedback. */ void PlanDispatcher::actionFeedback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) { // nothing yet... } } // close namespace <commit_msg>Erroneous parameter assignments<commit_after>#include "rosplan_planning_system/PlanDispatcher.h" #include <map> namespace KCL_rosplan { int PlanDispatcher::getCurrentAction() { return current_action; } void PlanDispatcher::reset() { dispatch_paused = false; current_action = 0; action_received.clear(); action_completed.clear(); replan_requested = false; } /*-----------------*/ /* action dispatch */ /*-----------------*/ /* * Loop through and publish planned actions */ bool PlanDispatcher::dispatchPlan(const std::vector<rosplan_dispatch_msgs::ActionDispatch> &actionList, double missionStart, double planStart) { ros::NodeHandle nh("~"); ros::Rate loop_rate(10); ROS_INFO("KCL: (PS) Dispatching plan"); replan_requested = false; bool repeatAction = false; while (ros::ok() && actionList.size() > current_action) { // get next action rosplan_dispatch_msgs::ActionDispatch currentMessage = actionList[current_action]; if((unsigned int)currentMessage.action_id != current_action) ROS_ERROR("KCL: (PS) Message action_id [%d] does not meet expected [%zu]", currentMessage.action_id, current_action); // loop while waiting for dispatch time if(!dispatch_on_completion) { double wait_period = 10.0; int wait_print = (int)(currentMessage.dispatch_time + planStart - ros::WallTime::now().toSec()) / wait_period; while (ros::ok() && ros::WallTime::now().toSec() < currentMessage.dispatch_time + planStart) { ros::spinOnce(); loop_rate.sleep(); double remaining = planStart + currentMessage.dispatch_time - ros::WallTime::now().toSec(); if(wait_print > (int)remaining / wait_period) { ROS_INFO("KCL: (PS) Waiting %f before dispatching action: [%i, %s, %f, %f]", remaining,currentMessage.action_id, currentMessage.name.c_str(), (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration); wait_print--; } } } if(!checkPreconditions(currentMessage)) { ROS_INFO("KCL: (PS) Preconditions not achieved [%i, %s]", currentMessage.action_id, currentMessage.name.c_str()); } // dispatch action ROS_INFO("KCL: (PS) Dispatching action [%i, %s, %f, %f]", currentMessage.action_id, currentMessage.name.c_str(), (currentMessage.dispatch_time+planStart-missionStart), currentMessage.duration); action_publisher.publish(currentMessage); double late_print = (ros::WallTime::now().toSec() - (currentMessage.dispatch_time + planStart)); if(late_print>0.1) ROS_INFO("KCL: (PS) Action [%i] is %f second(s) late", currentMessage.action_id, late_print); // wait for action to complete if(!dispatch_concurrent) { int counter = 0; while (ros::ok() && !action_completed[current_action]) { ros::spinOnce(); loop_rate.sleep(); counter++; if (counter == 2000) { ROS_INFO("KCL: (PS) Action %i timed out now. Cancelling...", currentMessage.action_id); rosplan_dispatch_msgs::ActionDispatch cancelMessage; cancelMessage.action_id = currentMessage.action_id; cancelMessage.name = "cancel_action"; action_publisher.publish(cancelMessage); } } } // get ready for next action if(!repeatAction) current_action++; repeatAction = false; action_received[current_action] = false; action_completed[current_action] = false; // finish dispatch and replan if(replan_requested) return false; } return true; } bool PlanDispatcher::checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg) { // setup service call ros::NodeHandle nh; ros::ServiceClient queryKnowledgeClient = nh.serviceClient<rosplan_knowledge_msgs::KnowledgeQueryService>("/kcl_rosplan/query_knowledge_base"); rosplan_knowledge_msgs::KnowledgeQueryService querySrv; std::map<std::string, std::vector<std::vector<std::string> > >::iterator oit; oit = environment.domain_operator_precondition_map.find(msg.name); if(oit==environment.domain_operator_precondition_map.end()) return false; // iterate through conditions std::vector<std::vector<std::string> >::iterator cit = oit->second.begin(); for(; cit!=oit->second.end(); cit++) { rosplan_knowledge_msgs::KnowledgeItem condition; // set fact or function std::map<std::string,std::vector<std::string> >::iterator dit = environment.domain_predicates.find((*cit)[0]); if(dit!=environment.domain_predicates.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE; dit = environment.domain_functions.find((*cit)[0]); if(dit!=environment.domain_functions.end()) condition.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION; // populate parameters condition.attribute_name = (*cit)[0]; std::vector<diagnostic_msgs::KeyValue>::iterator pit; int index = 0; for(pit = msg.parameters.begin(); pit!=msg.parameters.end(); pit++) { diagnostic_msgs::KeyValue param; std::cout << pit->key << " " << environment.domain_predicates[(*cit)[0]].size() << " " << std::endl; param.key = environment.domain_predicates[(*cit)[0]][index]; param.value = pit->value; condition.values.push_back(param); index++; } querySrv.request.knowledge.push_back(condition); } // check conditions in knowledge base if (queryKnowledgeClient.call(querySrv)) { if(!querySrv.response.all_true) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator kit; for(kit=querySrv.response.false_knowledge.begin(); kit != querySrv.response.false_knowledge.end(); kit++) ROS_INFO("KCL: (PS) [%s]", kit->attribute_name.c_str()); } return querySrv.response.all_true; } else { ROS_ERROR("KCL: (PS) Failed to call service /kcl_rosplan/query_knowledge_base"); } } /*------------------*/ /* general feedback */ /*------------------*/ /** * listen to and process actionFeedback topic. */ void PlanDispatcher::feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) { // create error if the action is unrecognised ROS_INFO("KCL: (PS) Feedback received [%i,%s]", msg->action_id, msg->status.c_str()); if(current_action != (unsigned int)msg->action_id) ROS_ERROR("KCL: (PS) Unexpected action ID: %d; current action: %zu", msg->action_id, current_action); // action enabled if(!action_received[msg->action_id] && (0 == msg->status.compare("action enabled"))) action_received[msg->action_id] = true; // more specific feedback actionFeedback(msg); // action completed (successfuly) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action achieved")) action_completed[msg->action_id] = true; // action completed (failed) if(!action_completed[msg->action_id] && 0 == msg->status.compare("action failed")) { replan_requested = true; action_completed[msg->action_id] = true; } } /*---------------------------*/ /* Specific action responses */ /*---------------------------*/ /** * processes single action feedback message. * This method serves as the hook for defining more interesting behaviour on action feedback. */ void PlanDispatcher::actionFeedback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) { // nothing yet... } } // close namespace <|endoftext|>
<commit_before>/* * SRT - Secure, Reliable, Transport * Copyright (c) 2018 Haivision Systems Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #ifndef INC__SOCKETOPTIONS_HPP #define INC__SOCKETOPTIONS_HPP #include <string> #include <map> #include <set> #include <vector> #include "../srtcore/srt.h" // Devel path #ifdef _WIN32 #include "winsock2.h" #endif struct OptionValue { std::string s; union { int i; int64_t l; bool b; }; const void* value = nullptr; size_t size = 0; }; extern const std::set<std::string> false_names, true_names; struct SocketOption { enum Type { STRING = 0, INT, INT64, BOOL, ENUM }; enum Binding { PRE = 0, POST }; enum Domain { SYSTEM, SRT }; enum Mode {FAILURE = -1, LISTENER = 0, CALLER = 1, RENDEZVOUS = 2}; std::string name; int protocol; int symbol; Binding binding; Type type; const std::map<std::string, int>* valmap; template <Domain D> bool apply(int socket, std::string value) const; template <Domain D, Type T> bool applyt(int socket, std::string value) const; template <Domain D> static int setso(int socket, int protocol, int symbol, const void* data, size_t size); template<Type T> void extract(std::string value, OptionValue& val) const; }; template<> inline int SocketOption::setso<SocketOption::SRT>(int socket, int /*ignored*/, int sym, const void* data, size_t size) { return srt_setsockopt(socket, 0, SRT_SOCKOPT(sym), data, size); } template<> inline int SocketOption::setso<SocketOption::SYSTEM>(int socket, int proto, int sym, const void* data, size_t size) { return ::setsockopt(socket, proto, sym, (const char *)data, size); } template<> inline void SocketOption::extract<SocketOption::STRING>(std::string value, OptionValue& o) const { o.s = value; o.value = o.s.data(); o.size = o.s.size(); } template<> inline void SocketOption::extract<SocketOption::INT>(std::string value, OptionValue& o) const { try { o.i = stoi(value, 0, 0); o.value = &o.i; o.size = sizeof o.i; return; } catch (...) // stoi throws { return; // do not change o } } template<> inline void SocketOption::extract<SocketOption::INT64>(std::string value, OptionValue& o) const { try { long long vall = stoll(value); o.l = vall; // int64_t resolves to either 'long long', or 'long' being 64-bit integer o.value = &o.l; o.size = sizeof o.l; return ; } catch (...) // stoll throws { return ; } } template<> inline void SocketOption::extract<SocketOption::BOOL>(std::string value, OptionValue& o) const { bool val; if ( false_names.count(value) ) val = false; else if ( true_names.count(value) ) val = true; else return; o.b = val; o.value = &o.b; o.size = sizeof o.b; } template<> inline void SocketOption::extract<SocketOption::ENUM>(std::string value, OptionValue& o) const { if (valmap) { // Search value in the map. If found, set to o. auto p = valmap->find(value); if ( p != valmap->end() ) { o.i = p->second; o.value = &o.i; o.size = sizeof o.i; return; } } // Fallback: try interpreting it as integer. try { o.i = stoi(value, 0, 0); o.value = &o.i; o.size = sizeof o.i; return; } catch (...) // stoi throws { return; // do not change o } } template <SocketOption::Domain D, SocketOption::Type T> inline bool SocketOption::applyt(int socket, std::string value) const { OptionValue o; // common meet point extract<T>(value, o); int result = setso<D>(socket, protocol, symbol, o.value, o.size); return result != -1; } template<SocketOption::Domain D> inline bool SocketOption::apply(int socket, std::string value) const { switch ( type ) { #define SRT_HANDLE_TYPE(ty) case ty: return applyt<D, ty>(socket, value) SRT_HANDLE_TYPE(STRING); SRT_HANDLE_TYPE(INT); SRT_HANDLE_TYPE(INT64); SRT_HANDLE_TYPE(BOOL); SRT_HANDLE_TYPE(ENUM); #undef SRT_HANDLE_TYPE } return false; } extern const std::map<std::string, int> enummap_transtype; namespace { const SocketOption srt_options [] { { "maxbw", 0, SRTO_MAXBW, SocketOption::PRE, SocketOption::INT64, nullptr}, { "pbkeylen", 0, SRTO_PBKEYLEN, SocketOption::PRE, SocketOption::INT, nullptr}, { "passphrase", 0, SRTO_PASSPHRASE, SocketOption::PRE, SocketOption::STRING, nullptr}, { "mss", 0, SRTO_MSS, SocketOption::PRE, SocketOption::INT, nullptr}, { "fc", 0, SRTO_FC, SocketOption::PRE, SocketOption::INT, nullptr}, { "sndbuf", 0, SRTO_SNDBUF, SocketOption::PRE, SocketOption::INT, nullptr}, { "rcvbuf", 0, SRTO_RCVBUF, SocketOption::PRE, SocketOption::INT, nullptr}, { "ipttl", 0, SRTO_IPTTL, SocketOption::PRE, SocketOption::INT, nullptr}, { "iptos", 0, SRTO_IPTOS, SocketOption::PRE, SocketOption::INT, nullptr}, { "inputbw", 0, SRTO_INPUTBW, SocketOption::POST, SocketOption::INT64, nullptr}, { "oheadbw", 0, SRTO_OHEADBW, SocketOption::POST, SocketOption::INT, nullptr}, { "latency", 0, SRTO_LATENCY, SocketOption::PRE, SocketOption::INT, nullptr}, { "tsbpddelay", 0, SRTO_TSBPDDELAY, SocketOption::PRE, SocketOption::INT, nullptr}, { "tlpktdrop", 0, SRTO_TLPKTDROP, SocketOption::PRE, SocketOption::BOOL, nullptr}, { "snddropdelay", 0, SRTO_SNDDROPDELAY, SocketOption::POST, SocketOption::INT, nullptr}, { "nakreport", 0, SRTO_NAKREPORT, SocketOption::PRE, SocketOption::BOOL, nullptr}, { "conntimeo", 0, SRTO_CONNTIMEO, SocketOption::PRE, SocketOption::INT, nullptr}, { "lossmaxttl", 0, SRTO_LOSSMAXTTL, SocketOption::PRE, SocketOption::INT, nullptr}, { "rcvlatency", 0, SRTO_RCVLATENCY, SocketOption::PRE, SocketOption::INT, nullptr}, { "peerlatency", 0, SRTO_PEERLATENCY, SocketOption::PRE, SocketOption::INT, nullptr}, { "minversion", 0, SRTO_MINVERSION, SocketOption::PRE, SocketOption::INT, nullptr}, { "streamid", 0, SRTO_STREAMID, SocketOption::PRE, SocketOption::STRING, nullptr}, { "smoother", 0, SRTO_SMOOTHER, SocketOption::PRE, SocketOption::STRING, nullptr}, { "messageapi", 0, SRTO_MESSAGEAPI, SocketOption::PRE, SocketOption::BOOL, nullptr}, { "payloadsize", 0, SRTO_PAYLOADSIZE, SocketOption::PRE, SocketOption::INT, nullptr}, { "transtype", 0, SRTO_TRANSTYPE, SocketOption::PRE, SocketOption::ENUM, &enummap_transtype }, { "kmrefreshrate", 0, SRTO_KMREFRESHRATE, SocketOption::PRE, SocketOption::INT, nullptr }, { "kmpreannounce", 0, SRTO_KMPREANNOUNCE, SocketOption::PRE, SocketOption::INT, nullptr }, { "strictenc", 0, SRTO_STRICTENC, SocketOption::PRE, SocketOption::BOOL, nullptr } }; } SocketOption::Mode SrtConfigurePre(SRTSOCKET socket, std::string host, std::map<std::string, std::string> options, std::vector<std::string>* failures = 0); void SrtConfigurePost(SRTSOCKET socket, std::map<std::string, std::string> options, std::vector<std::string>* failures = 0); #endif <commit_msg>test app: transtype socket option should be set first<commit_after>/* * SRT - Secure, Reliable, Transport * Copyright (c) 2018 Haivision Systems Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #ifndef INC__SOCKETOPTIONS_HPP #define INC__SOCKETOPTIONS_HPP #include <string> #include <map> #include <set> #include <vector> #include "../srtcore/srt.h" // Devel path #ifdef _WIN32 #include "winsock2.h" #endif struct OptionValue { std::string s; union { int i; int64_t l; bool b; }; const void* value = nullptr; size_t size = 0; }; extern const std::set<std::string> false_names, true_names; struct SocketOption { enum Type { STRING = 0, INT, INT64, BOOL, ENUM }; enum Binding { PRE = 0, POST }; enum Domain { SYSTEM, SRT }; enum Mode {FAILURE = -1, LISTENER = 0, CALLER = 1, RENDEZVOUS = 2}; std::string name; int protocol; int symbol; Binding binding; Type type; const std::map<std::string, int>* valmap; template <Domain D> bool apply(int socket, std::string value) const; template <Domain D, Type T> bool applyt(int socket, std::string value) const; template <Domain D> static int setso(int socket, int protocol, int symbol, const void* data, size_t size); template<Type T> void extract(std::string value, OptionValue& val) const; }; template<> inline int SocketOption::setso<SocketOption::SRT>(int socket, int /*ignored*/, int sym, const void* data, size_t size) { return srt_setsockopt(socket, 0, SRT_SOCKOPT(sym), data, size); } template<> inline int SocketOption::setso<SocketOption::SYSTEM>(int socket, int proto, int sym, const void* data, size_t size) { return ::setsockopt(socket, proto, sym, (const char *)data, size); } template<> inline void SocketOption::extract<SocketOption::STRING>(std::string value, OptionValue& o) const { o.s = value; o.value = o.s.data(); o.size = o.s.size(); } template<> inline void SocketOption::extract<SocketOption::INT>(std::string value, OptionValue& o) const { try { o.i = stoi(value, 0, 0); o.value = &o.i; o.size = sizeof o.i; return; } catch (...) // stoi throws { return; // do not change o } } template<> inline void SocketOption::extract<SocketOption::INT64>(std::string value, OptionValue& o) const { try { long long vall = stoll(value); o.l = vall; // int64_t resolves to either 'long long', or 'long' being 64-bit integer o.value = &o.l; o.size = sizeof o.l; return ; } catch (...) // stoll throws { return ; } } template<> inline void SocketOption::extract<SocketOption::BOOL>(std::string value, OptionValue& o) const { bool val; if ( false_names.count(value) ) val = false; else if ( true_names.count(value) ) val = true; else return; o.b = val; o.value = &o.b; o.size = sizeof o.b; } template<> inline void SocketOption::extract<SocketOption::ENUM>(std::string value, OptionValue& o) const { if (valmap) { // Search value in the map. If found, set to o. auto p = valmap->find(value); if ( p != valmap->end() ) { o.i = p->second; o.value = &o.i; o.size = sizeof o.i; return; } } // Fallback: try interpreting it as integer. try { o.i = stoi(value, 0, 0); o.value = &o.i; o.size = sizeof o.i; return; } catch (...) // stoi throws { return; // do not change o } } template <SocketOption::Domain D, SocketOption::Type T> inline bool SocketOption::applyt(int socket, std::string value) const { OptionValue o; // common meet point extract<T>(value, o); int result = setso<D>(socket, protocol, symbol, o.value, o.size); return result != -1; } template<SocketOption::Domain D> inline bool SocketOption::apply(int socket, std::string value) const { switch ( type ) { #define SRT_HANDLE_TYPE(ty) case ty: return applyt<D, ty>(socket, value) SRT_HANDLE_TYPE(STRING); SRT_HANDLE_TYPE(INT); SRT_HANDLE_TYPE(INT64); SRT_HANDLE_TYPE(BOOL); SRT_HANDLE_TYPE(ENUM); #undef SRT_HANDLE_TYPE } return false; } extern const std::map<std::string, int> enummap_transtype; namespace { const SocketOption srt_options [] { { "transtype", 0, SRTO_TRANSTYPE, SocketOption::PRE, SocketOption::ENUM, &enummap_transtype }, { "maxbw", 0, SRTO_MAXBW, SocketOption::PRE, SocketOption::INT64, nullptr}, { "pbkeylen", 0, SRTO_PBKEYLEN, SocketOption::PRE, SocketOption::INT, nullptr}, { "passphrase", 0, SRTO_PASSPHRASE, SocketOption::PRE, SocketOption::STRING, nullptr}, { "mss", 0, SRTO_MSS, SocketOption::PRE, SocketOption::INT, nullptr}, { "fc", 0, SRTO_FC, SocketOption::PRE, SocketOption::INT, nullptr}, { "sndbuf", 0, SRTO_SNDBUF, SocketOption::PRE, SocketOption::INT, nullptr}, { "rcvbuf", 0, SRTO_RCVBUF, SocketOption::PRE, SocketOption::INT, nullptr}, { "ipttl", 0, SRTO_IPTTL, SocketOption::PRE, SocketOption::INT, nullptr}, { "iptos", 0, SRTO_IPTOS, SocketOption::PRE, SocketOption::INT, nullptr}, { "inputbw", 0, SRTO_INPUTBW, SocketOption::POST, SocketOption::INT64, nullptr}, { "oheadbw", 0, SRTO_OHEADBW, SocketOption::POST, SocketOption::INT, nullptr}, { "latency", 0, SRTO_LATENCY, SocketOption::PRE, SocketOption::INT, nullptr}, { "tsbpddelay", 0, SRTO_TSBPDDELAY, SocketOption::PRE, SocketOption::INT, nullptr}, { "tlpktdrop", 0, SRTO_TLPKTDROP, SocketOption::PRE, SocketOption::BOOL, nullptr}, { "snddropdelay", 0, SRTO_SNDDROPDELAY, SocketOption::POST, SocketOption::INT, nullptr}, { "nakreport", 0, SRTO_NAKREPORT, SocketOption::PRE, SocketOption::BOOL, nullptr}, { "conntimeo", 0, SRTO_CONNTIMEO, SocketOption::PRE, SocketOption::INT, nullptr}, { "lossmaxttl", 0, SRTO_LOSSMAXTTL, SocketOption::PRE, SocketOption::INT, nullptr}, { "rcvlatency", 0, SRTO_RCVLATENCY, SocketOption::PRE, SocketOption::INT, nullptr}, { "peerlatency", 0, SRTO_PEERLATENCY, SocketOption::PRE, SocketOption::INT, nullptr}, { "minversion", 0, SRTO_MINVERSION, SocketOption::PRE, SocketOption::INT, nullptr}, { "streamid", 0, SRTO_STREAMID, SocketOption::PRE, SocketOption::STRING, nullptr}, { "smoother", 0, SRTO_SMOOTHER, SocketOption::PRE, SocketOption::STRING, nullptr}, { "messageapi", 0, SRTO_MESSAGEAPI, SocketOption::PRE, SocketOption::BOOL, nullptr}, { "payloadsize", 0, SRTO_PAYLOADSIZE, SocketOption::PRE, SocketOption::INT, nullptr}, { "kmrefreshrate", 0, SRTO_KMREFRESHRATE, SocketOption::PRE, SocketOption::INT, nullptr }, { "kmpreannounce", 0, SRTO_KMPREANNOUNCE, SocketOption::PRE, SocketOption::INT, nullptr }, { "strictenc", 0, SRTO_STRICTENC, SocketOption::PRE, SocketOption::BOOL, nullptr } }; } SocketOption::Mode SrtConfigurePre(SRTSOCKET socket, std::string host, std::map<std::string, std::string> options, std::vector<std::string>* failures = 0); void SrtConfigurePost(SRTSOCKET socket, std::map<std::string, std::string> options, std::vector<std::string>* failures = 0); #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <mapnik/text_symbolizer.hpp> #include "mapnik_enumeration.hpp" #include <mapnik/expression_string.hpp> using namespace mapnik; using mapnik::color; using mapnik::text_symbolizer; using mapnik::expr_node; using mapnik::expression_ptr; using mapnik::to_expression_string; namespace { using namespace boost::python; tuple get_text_displacement(const text_symbolizer& t) { position pos = t.get_displacement(); return boost::python::make_tuple(boost::get<0>(pos),boost::get<1>(pos)); } void set_text_displacement(text_symbolizer & t, boost::python::tuple arg) { t.set_displacement(extract<double>(arg[0]),extract<double>(arg[1])); } } struct text_symbolizer_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const text_symbolizer& t) { return boost::python::make_tuple("TODO",//t.get_name(), t.get_face_name(),t.get_text_size(),t.get_fill()); } static boost::python::tuple getstate(const text_symbolizer& t) { boost::python::tuple disp = get_text_displacement(t); // so we do not exceed max args accepted by make_tuple, // lets put the increasing list of parameters in a list boost::python::list extras; extras.append(t.get_wrap_char_string()); extras.append(t.get_line_spacing()); extras.append(t.get_character_spacing()); extras.append(t.get_text_transform()); extras.append(t.get_wrap_before()); extras.append(t.get_horizontal_alignment()); extras.append(t.get_justify_alignment()); extras.append(t.get_text_opacity()); extras.append(t.get_minimum_padding()); extras.append(t.get_minimum_path_length()); return boost::python::make_tuple(disp,t.get_label_placement(), t.get_vertical_alignment(),t.get_halo_radius(),t.get_halo_fill(),t.get_text_ratio(), t.get_wrap_width(),t.get_label_spacing(),t.get_minimum_distance(),t.get_allow_overlap(), t.get_force_odd_labels(),t.get_max_char_angle_delta(),extras ); } static void setstate (text_symbolizer& t, boost::python::tuple state) { using namespace boost::python; if (len(state) != 14) { PyErr_SetObject(PyExc_ValueError, ("expected 15-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } tuple disp = extract<tuple>(state[0]); double dx = extract<double>(disp[0]); double dy = extract<double>(disp[1]); t.set_displacement(dx,dy); t.set_label_placement(extract<label_placement_e>(state[1])); t.set_vertical_alignment(extract<vertical_alignment_e>(state[2])); t.set_halo_radius(extract<unsigned>(state[3])); t.set_halo_fill(extract<color>(state[4])); t.set_text_ratio(extract<unsigned>(state[5])); t.set_wrap_width(extract<unsigned>(state[6])); t.set_label_spacing(extract<unsigned>(state[7])); t.set_minimum_distance(extract<double>(state[8])); t.set_allow_overlap(extract<bool>(state[9])); t.set_force_odd_labels(extract<bool>(state[10])); t.set_max_char_angle_delta(extract<double>(state[11])); list extras = extract<list>(state[12]); t.set_wrap_char_from_string(extract<std::string>(extras[0])); t.set_line_spacing(extract<unsigned>(extras[1])); t.set_character_spacing(extract<unsigned>(extras[2])); t.set_text_transform(extract<text_transform_e>(extras[3])); t.set_wrap_before(extract<bool>(extras[4])); t.set_horizontal_alignment(extract<horizontal_alignment_e>(extras[5])); t.set_justify_alignment(extract<justify_alignment_e>(extras[6])); t.set_text_opacity(extract<double>(extras[7])); t.set_minimum_padding(extract<double>(extras[8])); t.set_minimum_path_length(extract<double>(extras[9])); } }; void export_text_symbolizer() { using namespace boost::python; enumeration_<label_placement_e>("label_placement") .value("LINE_PLACEMENT",LINE_PLACEMENT) .value("POINT_PLACEMENT",POINT_PLACEMENT) .value("VERTEX_PLACEMENT",VERTEX_PLACEMENT) .value("INTERIOR_PLACEMENT",INTERIOR_PLACEMENT) ; enumeration_<vertical_alignment_e>("vertical_alignment") .value("TOP",V_TOP) .value("MIDDLE",V_MIDDLE) .value("BOTTOM",V_BOTTOM) .value("AUTO",V_AUTO) ; enumeration_<horizontal_alignment_e>("horizontal_alignment") .value("LEFT",H_LEFT) .value("MIDDLE",H_MIDDLE) .value("RIGHT",H_RIGHT) ; enumeration_<justify_alignment_e>("justify_alignment") .value("LEFT",J_LEFT) .value("MIDDLE",J_MIDDLE) .value("RIGHT",J_RIGHT) ; enumeration_<text_transform_e>("text_transform") .value("NONE",NONE) .value("UPPERCASE",UPPERCASE) .value("LOWERCASE",LOWERCASE) .value("CAPITALIZE",CAPITALIZE) ; class_<text_symbolizer>("TextSymbolizer",init<expression_ptr,std::string const&, unsigned,color const&>()) /* // todo - all python classes can have kwargs and default constructors class_<text_symbolizer>("TextSymbolizer", init<expression_ptr,std::string const&, unsigned,color const&>( ( arg("name"), arg("font_face")="DejaVu Sans Book", arg("size")=10, arg("color")=color("black") ), "Create a TextSymbolizer\n" )) */ //.def_pickle(text_symbolizer_pickle_suite()) .add_property("allow_overlap", &text_symbolizer::get_allow_overlap, &text_symbolizer::set_allow_overlap, "Set/get the allow_overlap property of the label") .add_property("displacement", &get_text_displacement, &set_text_displacement) .add_property("avoid_edges", &text_symbolizer::get_avoid_edges, &text_symbolizer::set_avoid_edges, "Set/get the avoid_edge property of the label") .add_property("character_spacing", &text_symbolizer::get_character_spacing, &text_symbolizer::set_character_spacing, "Set/get the character_spacing property of the label") .add_property("face_name", make_function(&text_symbolizer::get_face_name,return_value_policy<copy_const_reference>()), &text_symbolizer::set_face_name, "Set/get the face_name property of the label") .add_property("fill", make_function(&text_symbolizer::get_fill,return_value_policy<copy_const_reference>()), &text_symbolizer::set_fill) .add_property("fontset", make_function(&text_symbolizer::get_fontset,return_value_policy<copy_const_reference>()), &text_symbolizer::set_fontset) .add_property("force_odd_labels", &text_symbolizer::get_force_odd_labels, &text_symbolizer::set_force_odd_labels) .add_property("halo_fill", make_function(&text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()), &text_symbolizer::set_halo_fill) .add_property("halo_radius", &text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius) .add_property("horizontal_alignment", &text_symbolizer::get_horizontal_alignment, &text_symbolizer::set_horizontal_alignment, "Set/get the horizontal alignment of the label") .add_property("justify_alignment", &text_symbolizer::get_justify_alignment, &text_symbolizer::set_justify_alignment, "Set/get the text justification") .add_property("label_placement", &text_symbolizer::get_label_placement, &text_symbolizer::set_label_placement, "Set/get the placement of the label") .add_property("label_position_tolerance", &text_symbolizer::get_label_position_tolerance, &text_symbolizer::set_label_position_tolerance) .add_property("label_spacing", &text_symbolizer::get_label_spacing, &text_symbolizer::set_label_spacing) .add_property("line_spacing", &text_symbolizer::get_line_spacing, &text_symbolizer::set_line_spacing) .add_property("max_char_angle_delta", &text_symbolizer::get_max_char_angle_delta, &text_symbolizer::set_max_char_angle_delta) .add_property("minimum_distance", &text_symbolizer::get_minimum_distance, &text_symbolizer::set_minimum_distance) .add_property("minimum_padding", &text_symbolizer::get_minimum_padding, &text_symbolizer::set_minimum_padding) .add_property("minimum_path_length", &text_symbolizer::get_minimum_path_length, &text_symbolizer::set_minimum_path_length) .add_property("name",&text_symbolizer::get_name, &text_symbolizer::set_name) .add_property("opacity", &text_symbolizer::get_text_opacity, &text_symbolizer::set_text_opacity, "Set/get the text opacity") .add_property("text_transform", &text_symbolizer::get_text_transform, &text_symbolizer::set_text_transform, "Set/get the text conversion method") .add_property("text_ratio", &text_symbolizer::get_text_ratio, &text_symbolizer::set_text_ratio) .add_property("text_size", &text_symbolizer::get_text_size, &text_symbolizer::set_text_size) .add_property("vertical_alignment", &text_symbolizer::get_vertical_alignment, &text_symbolizer::set_vertical_alignment, "Set/get the vertical alignment of the label") .add_property("wrap_width", &text_symbolizer::get_wrap_width, &text_symbolizer::set_wrap_width) .add_property("wrap_character", &text_symbolizer::get_wrap_char_string, &text_symbolizer::set_wrap_char_from_string) .add_property("wrap_before", &text_symbolizer::get_wrap_before, &text_symbolizer::set_wrap_before) ; } <commit_msg>Add H_AUTO to python bindings.<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <mapnik/text_symbolizer.hpp> #include "mapnik_enumeration.hpp" #include <mapnik/expression_string.hpp> using namespace mapnik; using mapnik::color; using mapnik::text_symbolizer; using mapnik::expr_node; using mapnik::expression_ptr; using mapnik::to_expression_string; namespace { using namespace boost::python; tuple get_text_displacement(const text_symbolizer& t) { position pos = t.get_displacement(); return boost::python::make_tuple(boost::get<0>(pos),boost::get<1>(pos)); } void set_text_displacement(text_symbolizer & t, boost::python::tuple arg) { t.set_displacement(extract<double>(arg[0]),extract<double>(arg[1])); } } struct text_symbolizer_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const text_symbolizer& t) { return boost::python::make_tuple("TODO",//t.get_name(), t.get_face_name(),t.get_text_size(),t.get_fill()); } static boost::python::tuple getstate(const text_symbolizer& t) { boost::python::tuple disp = get_text_displacement(t); // so we do not exceed max args accepted by make_tuple, // lets put the increasing list of parameters in a list boost::python::list extras; extras.append(t.get_wrap_char_string()); extras.append(t.get_line_spacing()); extras.append(t.get_character_spacing()); extras.append(t.get_text_transform()); extras.append(t.get_wrap_before()); extras.append(t.get_horizontal_alignment()); extras.append(t.get_justify_alignment()); extras.append(t.get_text_opacity()); extras.append(t.get_minimum_padding()); extras.append(t.get_minimum_path_length()); return boost::python::make_tuple(disp,t.get_label_placement(), t.get_vertical_alignment(),t.get_halo_radius(),t.get_halo_fill(),t.get_text_ratio(), t.get_wrap_width(),t.get_label_spacing(),t.get_minimum_distance(),t.get_allow_overlap(), t.get_force_odd_labels(),t.get_max_char_angle_delta(),extras ); } static void setstate (text_symbolizer& t, boost::python::tuple state) { using namespace boost::python; if (len(state) != 14) { PyErr_SetObject(PyExc_ValueError, ("expected 15-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } tuple disp = extract<tuple>(state[0]); double dx = extract<double>(disp[0]); double dy = extract<double>(disp[1]); t.set_displacement(dx,dy); t.set_label_placement(extract<label_placement_e>(state[1])); t.set_vertical_alignment(extract<vertical_alignment_e>(state[2])); t.set_halo_radius(extract<unsigned>(state[3])); t.set_halo_fill(extract<color>(state[4])); t.set_text_ratio(extract<unsigned>(state[5])); t.set_wrap_width(extract<unsigned>(state[6])); t.set_label_spacing(extract<unsigned>(state[7])); t.set_minimum_distance(extract<double>(state[8])); t.set_allow_overlap(extract<bool>(state[9])); t.set_force_odd_labels(extract<bool>(state[10])); t.set_max_char_angle_delta(extract<double>(state[11])); list extras = extract<list>(state[12]); t.set_wrap_char_from_string(extract<std::string>(extras[0])); t.set_line_spacing(extract<unsigned>(extras[1])); t.set_character_spacing(extract<unsigned>(extras[2])); t.set_text_transform(extract<text_transform_e>(extras[3])); t.set_wrap_before(extract<bool>(extras[4])); t.set_horizontal_alignment(extract<horizontal_alignment_e>(extras[5])); t.set_justify_alignment(extract<justify_alignment_e>(extras[6])); t.set_text_opacity(extract<double>(extras[7])); t.set_minimum_padding(extract<double>(extras[8])); t.set_minimum_path_length(extract<double>(extras[9])); } }; void export_text_symbolizer() { using namespace boost::python; enumeration_<label_placement_e>("label_placement") .value("LINE_PLACEMENT",LINE_PLACEMENT) .value("POINT_PLACEMENT",POINT_PLACEMENT) .value("VERTEX_PLACEMENT",VERTEX_PLACEMENT) .value("INTERIOR_PLACEMENT",INTERIOR_PLACEMENT) ; enumeration_<vertical_alignment_e>("vertical_alignment") .value("TOP",V_TOP) .value("MIDDLE",V_MIDDLE) .value("BOTTOM",V_BOTTOM) .value("AUTO",V_AUTO) ; enumeration_<horizontal_alignment_e>("horizontal_alignment") .value("LEFT",H_LEFT) .value("MIDDLE",H_MIDDLE) .value("RIGHT",H_RIGHT) .value("AUTO",H_AUTO) ; enumeration_<justify_alignment_e>("justify_alignment") .value("LEFT",J_LEFT) .value("MIDDLE",J_MIDDLE) .value("RIGHT",J_RIGHT) ; enumeration_<text_transform_e>("text_transform") .value("NONE",NONE) .value("UPPERCASE",UPPERCASE) .value("LOWERCASE",LOWERCASE) .value("CAPITALIZE",CAPITALIZE) ; class_<text_symbolizer>("TextSymbolizer",init<expression_ptr,std::string const&, unsigned,color const&>()) /* // todo - all python classes can have kwargs and default constructors class_<text_symbolizer>("TextSymbolizer", init<expression_ptr,std::string const&, unsigned,color const&>( ( arg("name"), arg("font_face")="DejaVu Sans Book", arg("size")=10, arg("color")=color("black") ), "Create a TextSymbolizer\n" )) */ //.def_pickle(text_symbolizer_pickle_suite()) .add_property("allow_overlap", &text_symbolizer::get_allow_overlap, &text_symbolizer::set_allow_overlap, "Set/get the allow_overlap property of the label") .add_property("displacement", &get_text_displacement, &set_text_displacement) .add_property("avoid_edges", &text_symbolizer::get_avoid_edges, &text_symbolizer::set_avoid_edges, "Set/get the avoid_edge property of the label") .add_property("character_spacing", &text_symbolizer::get_character_spacing, &text_symbolizer::set_character_spacing, "Set/get the character_spacing property of the label") .add_property("face_name", make_function(&text_symbolizer::get_face_name,return_value_policy<copy_const_reference>()), &text_symbolizer::set_face_name, "Set/get the face_name property of the label") .add_property("fill", make_function(&text_symbolizer::get_fill,return_value_policy<copy_const_reference>()), &text_symbolizer::set_fill) .add_property("fontset", make_function(&text_symbolizer::get_fontset,return_value_policy<copy_const_reference>()), &text_symbolizer::set_fontset) .add_property("force_odd_labels", &text_symbolizer::get_force_odd_labels, &text_symbolizer::set_force_odd_labels) .add_property("halo_fill", make_function(&text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()), &text_symbolizer::set_halo_fill) .add_property("halo_radius", &text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius) .add_property("horizontal_alignment", &text_symbolizer::get_horizontal_alignment, &text_symbolizer::set_horizontal_alignment, "Set/get the horizontal alignment of the label") .add_property("justify_alignment", &text_symbolizer::get_justify_alignment, &text_symbolizer::set_justify_alignment, "Set/get the text justification") .add_property("label_placement", &text_symbolizer::get_label_placement, &text_symbolizer::set_label_placement, "Set/get the placement of the label") .add_property("label_position_tolerance", &text_symbolizer::get_label_position_tolerance, &text_symbolizer::set_label_position_tolerance) .add_property("label_spacing", &text_symbolizer::get_label_spacing, &text_symbolizer::set_label_spacing) .add_property("line_spacing", &text_symbolizer::get_line_spacing, &text_symbolizer::set_line_spacing) .add_property("max_char_angle_delta", &text_symbolizer::get_max_char_angle_delta, &text_symbolizer::set_max_char_angle_delta) .add_property("minimum_distance", &text_symbolizer::get_minimum_distance, &text_symbolizer::set_minimum_distance) .add_property("minimum_padding", &text_symbolizer::get_minimum_padding, &text_symbolizer::set_minimum_padding) .add_property("minimum_path_length", &text_symbolizer::get_minimum_path_length, &text_symbolizer::set_minimum_path_length) .add_property("name",&text_symbolizer::get_name, &text_symbolizer::set_name) .add_property("opacity", &text_symbolizer::get_text_opacity, &text_symbolizer::set_text_opacity, "Set/get the text opacity") .add_property("text_transform", &text_symbolizer::get_text_transform, &text_symbolizer::set_text_transform, "Set/get the text conversion method") .add_property("text_ratio", &text_symbolizer::get_text_ratio, &text_symbolizer::set_text_ratio) .add_property("text_size", &text_symbolizer::get_text_size, &text_symbolizer::set_text_size) .add_property("vertical_alignment", &text_symbolizer::get_vertical_alignment, &text_symbolizer::set_vertical_alignment, "Set/get the vertical alignment of the label") .add_property("wrap_width", &text_symbolizer::get_wrap_width, &text_symbolizer::set_wrap_width) .add_property("wrap_character", &text_symbolizer::get_wrap_char_string, &text_symbolizer::set_wrap_char_from_string) .add_property("wrap_before", &text_symbolizer::get_wrap_before, &text_symbolizer::set_wrap_before) ; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////// // multifstream.cpp // #include "cxxtools/multifstream.h" multifstreambuf::multifstreambuf(const char* pattern, int flags) : current(0) { glob(pattern, flags, 0, &mglob); if (mglob.gl_pathv[current]) file.open(mglob.gl_pathv[current], std::ios::in); } multifstreambuf::~multifstreambuf() { globfree(&mglob); } std::streambuf::int_type multifstreambuf::overflow(std::streambuf::int_type c) { return traits_type::eof(); } std::streambuf::int_type multifstreambuf::underflow() { int_type r; do { r = file.sbumpc(); } while (r == traits_type::eof() && open_next()); if (r != traits_type::eof()) { ch = static_cast<char>(r); setg(&ch, &ch, &ch + 1); } return r; } int multifstreambuf::sync() { return 0; } bool multifstreambuf::open_next() { file.close(); if (mglob.gl_pathv[current] && mglob.gl_pathv[current + 1]) { ++current; file.open(mglob.gl_pathv[current], std::ios::in); return true; } else return false; } <commit_msg>segfault, wenn keine Dateien gefunden wurden korrigiert<commit_after>//////////////////////////////////////////////////////////////////////// // multifstream.cpp // #include "cxxtools/multifstream.h" multifstreambuf::multifstreambuf(const char* pattern, int flags) : current(0) { glob(pattern, flags, 0, &mglob); if (mglob.gl_pathv && mglob.gl_pathv[current]) file.open(mglob.gl_pathv[current], std::ios::in); } multifstreambuf::~multifstreambuf() { globfree(&mglob); } std::streambuf::int_type multifstreambuf::overflow(std::streambuf::int_type c) { return traits_type::eof(); } std::streambuf::int_type multifstreambuf::underflow() { if (mglob.gl_pathv == 0 || mglob.gl_pathv[current] == 0) return traits_type::eof(); int_type r; do { r = file.sbumpc(); } while (r == traits_type::eof() && open_next()); if (r != traits_type::eof()) { ch = static_cast<char>(r); setg(&ch, &ch, &ch + 1); } return r; } int multifstreambuf::sync() { return 0; } bool multifstreambuf::open_next() { file.close(); if (mglob.gl_pathv[current] && mglob.gl_pathv[current + 1]) { ++current; file.open(mglob.gl_pathv[current], std::ios::in); return true; } else return false; } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright (c) 2014, 2015 IBM Corporation and others * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ #include "StatusInitializerImpl.hpp" namespace loc{ StatusInitializerImpl& StatusInitializerImpl::dataStore(std::shared_ptr<DataStore> dataStore){ mDataStore = dataStore; return *this; } StatusInitializerImpl& StatusInitializerImpl::poseProperty(PoseProperty poseProperty){ mPoseProperty = poseProperty; return *this; } StatusInitializerImpl& StatusInitializerImpl::stateProperty(StateProperty stateProperty){ mStateProperty = stateProperty; return *this; } Location StatusInitializerImpl::perturbLocation(const Location& location){ Location locNew(location); double x = locNew.x() + mPoseProperty.stdX() * rand.nextGaussian(); double y = locNew.y() + mPoseProperty.stdY() * rand.nextGaussian(); locNew.x(x); locNew.y(y); return locNew; } Location StatusInitializerImpl::perturbLocation(const Location& location, const Building& building){ bool hasBuilding = building.nFloors()>0? true: false; for(int i=0; i<nPerturbationMax; i++){ Location locNew = this->perturbLocation(location); if(hasBuilding){ if(building.isMovable(locNew)){ return locNew; } }else{ return locNew; } } return location; } Locations StatusInitializerImpl::initializeLocations(int n){ assert(n>0); const Samples& samples = mDataStore->getSamples(); const Building& building = mDataStore->getBuilding(); std::vector<Location> uniqueLocations = Sample::extractUniqueLocations(samples); std::vector<Location> movableLocations; // Filter movable points int countNonMovable = 0; bool hasBuilding = building.nFloors()>0? true : false; if(hasBuilding){ for(Location loc: uniqueLocations){ if(building.isMovable(loc)){ movableLocations.push_back(Location(loc)); }else{ countNonMovable++; //std::cout << "Location="<<loc<< " is not a movable point." <<std::endl; } } }else{ movableLocations.insert(movableLocations.end(), uniqueLocations.begin(), uniqueLocations.end()); } std::cout << "Invalid " << countNonMovable << " points are not used for initialization." << std::endl; // Random sampling Locations locs; int nSamples = (int) movableLocations.size(); assert(nSamples>0); std::vector<int> indices = rand.randomSet(nSamples, n); for(int i=0; i<n; i++){ int idx = indices.at(i); //std::cout << "idx=" << idx << std::endl; Location loc = movableLocations.at(idx); loc = perturbLocation(loc, building); locs.push_back(Location(loc)); } assert(locs.size()==n); if(hasBuilding){ for(Location loc: locs){ assert(building.isMovable(loc)); } }else{ // pass } return locs; } Poses StatusInitializerImpl::initializePosesFromLocations(Locations locs){ size_t n = locs.size(); Poses poses(n); for(int i=0; i<n; i++){ Location loc = locs.at(i); Pose pose(loc); double orientation = 2.0*M_PI*rand.nextDouble(); double velocity = 0.0; double normalVelocity = rand.nextTruncatedGaussian(mPoseProperty.meanVelocity(), mPoseProperty.stdVelocity(), mPoseProperty.minVelocity(), mPoseProperty.maxVelocity()); pose.orientation(orientation) .velocity(velocity) .normalVelocity(normalVelocity); poses[i]=pose; } return poses; } Poses StatusInitializerImpl::initializePoses(int n){ Locations locs = initializeLocations(n); return initializePosesFromLocations(locs); } States StatusInitializerImpl::initializeStatesFromPoses(Poses poses){ size_t n = poses.size(); States states(n); for(int i=0; i<n; i++){ Pose pose = poses.at(i); State state(pose); double orientationBias = 2.0*M_PI*rand.nextDouble(); double rssiBias = mStateProperty.meanRssiBias() + mStateProperty.stdRssiBias()*rand.nextGaussian(); state.orientationBias(orientationBias).rssiBias(rssiBias); state.weight(1.0/n); states[i]=state; } return states; } States StatusInitializerImpl::initializeStatesFromLocations(const std::vector<Location> &locations){ const Poses& poses = initializePosesFromLocations(locations); return initializeStatesFromPoses(poses); } States StatusInitializerImpl::initializeStates(int n){ Poses poses = initializePoses(n); return initializeStatesFromPoses(poses); } States StatusInitializerImpl::resetStates(int n, Pose pose, double orientationMeasured){ double xReset = pose.x(); double yReset = pose.y(); double zReset = pose.z(); double floorReset = pose.floor(); double orientationReset = pose.orientation(); double orientationBiasReset = orientationMeasured - orientationReset; //std::cout << "Reset status(PoseReset="<<pose<<", yaw="<<orientationMeasured<< ",orientationBias=" << orientationBiasReset << std::endl; States states = initializeStates(n); for(int i=0; i<n; i++){ State state = states.at(i); state.x(xReset).y(yReset).z(zReset).floor(floorReset).orientation(orientationReset); state.orientationBias(orientationBiasReset); state.weight(1.0/n); states[i] = state; } return states; } States StatusInitializerImpl::resetStates(int n, Pose meanPose, Pose stdevPose, double orientationMeasured){ Building building = mDataStore->getBuilding(); if(building.nFloors()>0){ assert(building.isValid(meanPose)); assert(!building.isWall(meanPose)); assert(building.isMovable(meanPose)); } States statesTmp = resetStates(n, meanPose, orientationMeasured); States states(n); for(int i=0; i<n; ){ while(true){ State s = statesTmp.at(i); double x = s.x() + stdevPose.x()*rand.nextGaussian(); double y = s.y() + stdevPose.y()*rand.nextGaussian(); double z = s.z() + stdevPose.z()*rand.nextGaussian(); double floor = s.floor() + stdevPose.floor()*rand.nextGaussian(); double orientation = s.orientation() + stdevPose.orientation()*rand.nextGaussian(); double orientationBias = orientationMeasured - s.orientation(); // State stateNew(s); s.x(x).y(y).z(z).floor(floor).orientation(orientation); s.orientationBias(orientationBias); // only if meanPose.normalVelocity is valid, normalVelocity is updated. if(mPoseProperty.minVelocity() < meanPose.normalVelocity() && meanPose.normalVelocity() < mPoseProperty.maxVelocity()){ double normalVelocity = rand.nextTruncatedGaussian(meanPose.normalVelocity(), stdevPose.normalVelocity(), mPoseProperty.minVelocity(), mPoseProperty.maxVelocity()); s.normalVelocity(normalVelocity); } if(building.nFloors()>0){ if(building.isMovable(s)){ states[i] = s; i++; break; } }else{ states[i] = s; i++; break; } } } return states; } Locations StatusInitializerImpl::extractLocationsCloseToBeacons(const std::vector<Beacon> &beacons, double radius2D){ auto samples = mDataStore->getSamples(); auto bleBeacons = mDataStore->getBLEBeacons(); std::map<long, int> idToIndexMap = BLEBeacon::constructBeaconIdToIndexMap(bleBeacons); std::vector<Location> selectedLocations; std::vector<BLEBeacon> observedBLEBeacons; for(auto& b: beacons){ long id = b.id(); if(idToIndexMap.count(id)>0){ observedBLEBeacons.push_back(bleBeacons.at(idToIndexMap.at(id))); } } for(auto& s: samples){ auto loc = s.location(); for(auto& bloc: observedBLEBeacons){ double dist = Location::distance2D(loc, bloc); double floorDiff = Location::floorDifference(loc, bloc); if(dist <= radius2D && floorDiff==0){ selectedLocations.push_back(loc); continue; } } } return selectedLocations; } }<commit_msg>fix initialization of orientation (orientationBias)<commit_after>/******************************************************************************* * Copyright (c) 2014, 2015 IBM Corporation and others * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ #include "StatusInitializerImpl.hpp" namespace loc{ StatusInitializerImpl& StatusInitializerImpl::dataStore(std::shared_ptr<DataStore> dataStore){ mDataStore = dataStore; return *this; } StatusInitializerImpl& StatusInitializerImpl::poseProperty(PoseProperty poseProperty){ mPoseProperty = poseProperty; return *this; } StatusInitializerImpl& StatusInitializerImpl::stateProperty(StateProperty stateProperty){ mStateProperty = stateProperty; return *this; } Location StatusInitializerImpl::perturbLocation(const Location& location){ Location locNew(location); double x = locNew.x() + mPoseProperty.stdX() * rand.nextGaussian(); double y = locNew.y() + mPoseProperty.stdY() * rand.nextGaussian(); locNew.x(x); locNew.y(y); return locNew; } Location StatusInitializerImpl::perturbLocation(const Location& location, const Building& building){ bool hasBuilding = building.nFloors()>0? true: false; for(int i=0; i<nPerturbationMax; i++){ Location locNew = this->perturbLocation(location); if(hasBuilding){ if(building.isMovable(locNew)){ return locNew; } }else{ return locNew; } } return location; } Locations StatusInitializerImpl::initializeLocations(int n){ assert(n>0); const Samples& samples = mDataStore->getSamples(); const Building& building = mDataStore->getBuilding(); std::vector<Location> uniqueLocations = Sample::extractUniqueLocations(samples); std::vector<Location> movableLocations; // Filter movable points int countNonMovable = 0; bool hasBuilding = building.nFloors()>0? true : false; if(hasBuilding){ for(Location loc: uniqueLocations){ if(building.isMovable(loc)){ movableLocations.push_back(Location(loc)); }else{ countNonMovable++; //std::cout << "Location="<<loc<< " is not a movable point." <<std::endl; } } }else{ movableLocations.insert(movableLocations.end(), uniqueLocations.begin(), uniqueLocations.end()); } std::cout << "Invalid " << countNonMovable << " points are not used for initialization." << std::endl; // Random sampling Locations locs; int nSamples = (int) movableLocations.size(); assert(nSamples>0); std::vector<int> indices = rand.randomSet(nSamples, n); for(int i=0; i<n; i++){ int idx = indices.at(i); //std::cout << "idx=" << idx << std::endl; Location loc = movableLocations.at(idx); loc = perturbLocation(loc, building); locs.push_back(Location(loc)); } assert(locs.size()==n); if(hasBuilding){ for(Location loc: locs){ assert(building.isMovable(loc)); } }else{ // pass } return locs; } Poses StatusInitializerImpl::initializePosesFromLocations(Locations locs){ size_t n = locs.size(); Poses poses(n); for(int i=0; i<n; i++){ Location loc = locs.at(i); Pose pose(loc); double orientation = 2.0*M_PI*rand.nextDouble(); double velocity = 0.0; double normalVelocity = rand.nextTruncatedGaussian(mPoseProperty.meanVelocity(), mPoseProperty.stdVelocity(), mPoseProperty.minVelocity(), mPoseProperty.maxVelocity()); pose.orientation(orientation) .velocity(velocity) .normalVelocity(normalVelocity); poses[i]=pose; } return poses; } Poses StatusInitializerImpl::initializePoses(int n){ Locations locs = initializeLocations(n); return initializePosesFromLocations(locs); } States StatusInitializerImpl::initializeStatesFromPoses(Poses poses){ size_t n = poses.size(); States states(n); for(int i=0; i<n; i++){ Pose pose = poses.at(i); State state(pose); double orientationBias = 2.0*M_PI*rand.nextDouble(); double rssiBias = mStateProperty.meanRssiBias() + mStateProperty.stdRssiBias()*rand.nextGaussian(); state.orientationBias(orientationBias).rssiBias(rssiBias); state.weight(1.0/n); states[i]=state; } return states; } States StatusInitializerImpl::initializeStatesFromLocations(const std::vector<Location> &locations){ const Poses& poses = initializePosesFromLocations(locations); return initializeStatesFromPoses(poses); } States StatusInitializerImpl::initializeStates(int n){ Poses poses = initializePoses(n); return initializeStatesFromPoses(poses); } States StatusInitializerImpl::resetStates(int n, Pose pose, double orientationMeasured){ double xReset = pose.x(); double yReset = pose.y(); double zReset = pose.z(); double floorReset = pose.floor(); double orientationReset = pose.orientation(); double orientationBiasReset = orientationMeasured - orientationReset; //std::cout << "Reset status(PoseReset="<<pose<<", yaw="<<orientationMeasured<< ",orientationBias=" << orientationBiasReset << std::endl; States states = initializeStates(n); for(int i=0; i<n; i++){ State state = states.at(i); state.x(xReset).y(yReset).z(zReset).floor(floorReset).orientation(orientationReset); state.orientationBias(orientationBiasReset); state.weight(1.0/n); states[i] = state; } return states; } States StatusInitializerImpl::resetStates(int n, Pose meanPose, Pose stdevPose, double orientationMeasured){ Building building = mDataStore->getBuilding(); if(building.nFloors()>0){ assert(building.isValid(meanPose)); assert(!building.isWall(meanPose)); assert(building.isMovable(meanPose)); } States statesTmp = resetStates(n, meanPose, orientationMeasured); States states(n); for(int i=0; i<n; ){ while(true){ State s = statesTmp.at(i); double x = s.x() + stdevPose.x()*rand.nextGaussian(); double y = s.y() + stdevPose.y()*rand.nextGaussian(); double z = s.z() + stdevPose.z()*rand.nextGaussian(); double floor = s.floor() + stdevPose.floor()*rand.nextGaussian(); double orientation = s.orientation() + stdevPose.orientation()*rand.nextGaussian(); double orientationBias = orientationMeasured - orientation; // State stateNew(s); s.x(x).y(y).z(z).floor(floor).orientation(orientation); s.orientationBias(orientationBias); // only if meanPose.normalVelocity is valid, normalVelocity is updated. if(mPoseProperty.minVelocity() < meanPose.normalVelocity() && meanPose.normalVelocity() < mPoseProperty.maxVelocity()){ double normalVelocity = rand.nextTruncatedGaussian(meanPose.normalVelocity(), stdevPose.normalVelocity(), mPoseProperty.minVelocity(), mPoseProperty.maxVelocity()); s.normalVelocity(normalVelocity); } if(building.nFloors()>0){ if(building.isMovable(s)){ states[i] = s; i++; break; } }else{ states[i] = s; i++; break; } } } return states; } Locations StatusInitializerImpl::extractLocationsCloseToBeacons(const std::vector<Beacon> &beacons, double radius2D){ auto samples = mDataStore->getSamples(); auto bleBeacons = mDataStore->getBLEBeacons(); std::map<long, int> idToIndexMap = BLEBeacon::constructBeaconIdToIndexMap(bleBeacons); std::vector<Location> selectedLocations; std::vector<BLEBeacon> observedBLEBeacons; for(auto& b: beacons){ long id = b.id(); if(idToIndexMap.count(id)>0){ observedBLEBeacons.push_back(bleBeacons.at(idToIndexMap.at(id))); } } for(auto& s: samples){ auto loc = s.location(); for(auto& bloc: observedBLEBeacons){ double dist = Location::distance2D(loc, bloc); double floorDiff = Location::floorDifference(loc, bloc); if(dist <= radius2D && floorDiff==0){ selectedLocations.push_back(loc); continue; } } } return selectedLocations; } }<|endoftext|>
<commit_before>#include "framework/configfile.h" #include "framework/data.h" #include "framework/framework.h" #include "framework/trace.h" #include "game/state/battle/battlemapsector.h" #include "game/state/battle/battlemaptileset.h" #include "game/state/battle/battleunitimagepack.h" #include "game/state/gamestate.h" #include "library/strings_format.h" #include "tools/extractors/extractors.h" #include <SDL_main.h> using namespace OpenApoc; int main(int argc, char *argv[]) { if (config().parseOptions(argc, argv)) { return EXIT_FAILURE; } LogInfo("Starting OpenApoc_DataExtractor"); { Trace::setThreadName("main"); TraceObj obj("main"); Framework *fw = new Framework(UString(argv[0]), false); InitialGameStateExtractor e; { auto bullet_sprites = e.extractBulletSpritesCity(); for (auto &sprite_pair : bullet_sprites) { auto path = "data/" + sprite_pair.first; fw->data->writeImage(path, sprite_pair.second); } } { auto bullet_sprites = e.extractBulletSpritesBattle(); for (auto &sprite_pair : bullet_sprites) { auto path = "data/" + sprite_pair.first; fw->data->writeImage(path, sprite_pair.second, fw->data->loadPalette("xcom3/tacdata/tactical.pal")); } } std::map<UString, InitialGameStateExtractor::Difficulty> difficultyOutputFiles = { {"data/difficulty1", InitialGameStateExtractor::Difficulty::DIFFICULTY_1}, {"data/difficulty2", InitialGameStateExtractor::Difficulty::DIFFICULTY_2}, {"data/difficulty3", InitialGameStateExtractor::Difficulty::DIFFICULTY_3}, {"data/difficulty4", InitialGameStateExtractor::Difficulty::DIFFICULTY_4}, {"data/difficulty5", InitialGameStateExtractor::Difficulty::DIFFICULTY_5}, }; { GameState s; LogWarning("Extracting common gamestate"); e.extractCommon(s); LogWarning("Importing common patch"); s.loadGame("data/common_patch"); LogWarning("Saving common gamestate"); s.saveGame("data/gamestate_common", false); LogWarning("Saved common gamestate"); } for (auto &dpair : difficultyOutputFiles) { GameState s; LogWarning("Extracting initial game state for \"%s\"", dpair.first.cStr()); e.extract(s, dpair.second); LogWarning("Finished extracting initial game state for \"%s\"", dpair.first.cStr()); LogWarning("Importing common patch"); s.loadGame("data/common_patch"); LogWarning("Done importing common patch"); UString patchName = dpair.first + "_patch"; LogWarning("Trying to import patch \"%s\"", patchName.cStr()); s.loadGame(patchName); LogWarning("Patching finished"); UString patchedOutputName = dpair.first + "_patched"; LogWarning("Saving patched state to \"%s\"", patchedOutputName.cStr()); s.saveGame(patchedOutputName, false); LogWarning("Done saving patched state"); } LogWarning("Extracting Unit Image Packs"); for (auto &imagePackStrings : e.unitImagePackPaths) { GameState s; LogInfo("Extracting image pack \"%s\"", imagePackStrings.first.cStr()); auto imagePack = e.extractImagePack(s, imagePackStrings.second, false); if (!imagePack) { LogError("Failed to extract image pack \"%s\"", imagePackStrings.first.cStr()); } else { if (!imagePack->saveImagePack(BattleUnitImagePack::getImagePackPath() + "/" + imagePackStrings.first, false)) { LogError("Failed to save image pack \"%s\"", imagePackStrings.first.cStr()); } } } LogWarning("Extracting Item Image Packs"); int itemImagePacksCount = e.getItemImagePacksCount(); for (int i = 0; i < itemImagePacksCount; i++) { GameState s; LogInfo("Extracting item image pack \"%d\"", i); auto imagePack = e.extractItemImagePack(s, i); if (!imagePack) { LogError("Failed to extract item image pack \"%d\"", i); } else { if (!imagePack->saveImagePack( format("%s%s%d", BattleUnitImagePack::getImagePackPath(), "/item", i), false)) { LogError("Failed to save item image pack \"%d\"", i); } } } LogWarning("Extracting Unit Shadow Packs"); for (auto &imagePackStrings : e.unitShadowPackPaths) { GameState s; LogInfo("Extracting image pack \"%s\"", imagePackStrings.first.cStr()); auto imagePack = e.extractImagePack(s, imagePackStrings.second, true); if (!imagePack) { LogError("Failed to extract image pack \"%s\"", imagePackStrings.first.cStr()); } else { if (!imagePack->saveImagePack(BattleUnitImagePack::getImagePackPath() + "/" + imagePackStrings.first, false)) { LogError("Failed to save image pack \"%s\"", imagePackStrings.first.cStr()); } } } LogWarning("Extracting Unit Animation Packs"); for (auto &animationPackStrings : e.unitAnimationPackPaths) { GameState s; LogInfo("Extracting animation pack \"%s\"", animationPackStrings.first.cStr()); auto animationPack = e.extractAnimationPack(s, animationPackStrings.second, animationPackStrings.first); if (!animationPack) { LogError("Failed to extract animation pack \"%s\"", animationPackStrings.first.cStr()); } else { if (!animationPack->saveAnimationPack( BattleUnitAnimationPack::getAnimationPackPath() + "/" + animationPackStrings.first, false)) { LogError("Failed to save animation pack \"%s\"", animationPackStrings.first.cStr()); } } } LogWarning("Extracting Battle Map Tilesets"); for (auto &tileSetName : e.battleMapPaths) { // Some indices are empty? if (tileSetName.empty()) continue; GameState s; LogInfo("Extracting tileset \"%s\"", tileSetName.cStr()); auto tileSet = e.extractTileSet(s, tileSetName); if (!tileSet) { LogError("Failed to extract tileset \"%s\"", tileSetName.cStr()); } else { if (!tileSet->saveTileset(BattleMapTileset::getTilesetPath() + "/" + tileSetName, false)) { LogError("Failed to save tileset \"%s\"", tileSetName.cStr()); } } } LogWarning("Extracting Battle Map Sectors"); for (auto &mapName : e.battleMapPaths) { // Some indices are empty? if (mapName.empty()) continue; GameState s; LogInfo("Extracting map sectors from \"%s\"", mapName.cStr()); auto sectors = e.extractMapSectors(s, mapName); LogInfo("Extracted %u sectors from \"%s\"", (unsigned)sectors.size(), mapName.cStr()); if (sectors.empty()) { LogError("Failed to sectors from map \"%s\"", mapName.cStr()); } for (auto &sectorPair : sectors) { auto &sectorName = sectorPair.first; auto &sector = sectorPair.second; auto path = BattleMapSectorTiles::getMapSectorPath(); if (!sector->saveSector(path + "/" + sectorName, false)) { LogError("Failed to save map sector \"%s\"", sectorName.cStr()); } } } delete fw; } return 0; } <commit_msg>Allow the dataextractor to only extract subsets of all data<commit_after>#include "framework/configfile.h" #include "framework/data.h" #include "framework/framework.h" #include "framework/trace.h" #include "game/state/battle/battlemapsector.h" #include "game/state/battle/battlemaptileset.h" #include "game/state/battle/battleunitimagepack.h" #include "game/state/gamestate.h" #include "library/strings_format.h" #include "tools/extractors/extractors.h" #include <SDL_main.h> #include <list> using namespace OpenApoc; static void extractDifficulty(const InitialGameStateExtractor &e, UString outputPath, InitialGameStateExtractor::Difficulty difficulty, UString patchPath) { GameState s; e.extract(s, difficulty); s.loadGame("data/common_patch"); if (!patchPath.empty()) { s.loadGame(patchPath); } s.saveGame(outputPath, false); } std::map<UString, std::function<void(const InitialGameStateExtractor &e)>> thingsToExtract = { {"difficulty1", [](const InitialGameStateExtractor &e) { extractDifficulty(e, "data/difficulty1_patched", InitialGameStateExtractor::Difficulty::DIFFICULTY_1, "data/difficulty1_patch"); }}, {"difficulty2", [](const InitialGameStateExtractor &e) { extractDifficulty(e, "data/difficulty2_patched", InitialGameStateExtractor::Difficulty::DIFFICULTY_2, "data/difficulty2_patch"); }}, {"difficulty3", [](const InitialGameStateExtractor &e) { extractDifficulty(e, "data/difficulty3_patched", InitialGameStateExtractor::Difficulty::DIFFICULTY_3, "data/difficulty3_patch"); }}, {"difficulty4", [](const InitialGameStateExtractor &e) { extractDifficulty(e, "data/difficulty4_patched", InitialGameStateExtractor::Difficulty::DIFFICULTY_4, "data/difficulty4_patch"); }}, {"difficulty5", [](const InitialGameStateExtractor &e) { extractDifficulty(e, "data/difficulty5_patched", InitialGameStateExtractor::Difficulty::DIFFICULTY_5, "data/difficulty5_patch"); }}, {"common_gamestate", [](const InitialGameStateExtractor &e) { GameState s; e.extractCommon(s); s.loadGame("data/common_patch"); s.saveGame("data/gamestate_common", false); }}, {"city_bullet_sprites", [](const InitialGameStateExtractor &e) { auto bullet_sprites = e.extractBulletSpritesCity(); for (auto &sprite_pair : bullet_sprites) { auto path = "data/" + sprite_pair.first; fw().data->writeImage(path, sprite_pair.second); } }}, {"battle_bullet_sprites", [](const InitialGameStateExtractor &e) { auto bullet_sprites = e.extractBulletSpritesBattle(); for (auto &sprite_pair : bullet_sprites) { auto path = "data/" + sprite_pair.first; fw().data->writeImage(path, sprite_pair.second, fw().data->loadPalette("xcom3/tacdata/tactical.pal")); } }}, {"unit_image_packs", [](const InitialGameStateExtractor &e) { for (auto &imagePackStrings : e.unitImagePackPaths) { GameState s; LogInfo("Extracting image pack \"%s\"", imagePackStrings.first.cStr()); auto imagePack = e.extractImagePack(s, imagePackStrings.second, false); if (!imagePack) { LogError("Failed to extract image pack \"%s\"", imagePackStrings.first.cStr()); } else { if (!imagePack->saveImagePack(BattleUnitImagePack::getImagePackPath() + "/" + imagePackStrings.first, false)) { LogError("Failed to save image pack \"%s\"", imagePackStrings.first.cStr()); } } } }}, {"item_image_packs", [](const InitialGameStateExtractor &e) { int itemImagePacksCount = e.getItemImagePacksCount(); for (int i = 0; i < itemImagePacksCount; i++) { GameState s; LogInfo("Extracting item image pack \"%d\"", i); auto imagePack = e.extractItemImagePack(s, i); if (!imagePack) { LogError("Failed to extract item image pack \"%d\"", i); } else { if (!imagePack->saveImagePack( format("%s%s%d", BattleUnitImagePack::getImagePackPath(), "/item", i), false)) { LogError("Failed to save item image pack \"%d\"", i); } } } }}, {"unit_shadow_packs", [](const InitialGameStateExtractor &e) { for (auto &imagePackStrings : e.unitShadowPackPaths) { GameState s; LogInfo("Extracting image pack \"%s\"", imagePackStrings.first.cStr()); auto imagePack = e.extractImagePack(s, imagePackStrings.second, true); if (!imagePack) { LogError("Failed to extract image pack \"%s\"", imagePackStrings.first.cStr()); } else { if (!imagePack->saveImagePack(BattleUnitImagePack::getImagePackPath() + "/" + imagePackStrings.first, false)) { LogError("Failed to save image pack \"%s\"", imagePackStrings.first.cStr()); } } } }}, {"unit_animation_packs", [](const InitialGameStateExtractor &e) { for (auto &animationPackStrings : e.unitAnimationPackPaths) { GameState s; LogInfo("Extracting animation pack \"%s\"", animationPackStrings.first.cStr()); auto animationPack = e.extractAnimationPack(s, animationPackStrings.second, animationPackStrings.first); if (!animationPack) { LogError("Failed to extract animation pack \"%s\"", animationPackStrings.first.cStr()); } else { if (!animationPack->saveAnimationPack( BattleUnitAnimationPack::getAnimationPackPath() + "/" + animationPackStrings.first, false)) { LogError("Failed to save animation pack \"%s\"", animationPackStrings.first.cStr()); } } } }}, {"battle_map_tilesets", [](const InitialGameStateExtractor &e) { for (auto &tileSetName : e.battleMapPaths) { // Some indices are empty? if (tileSetName.empty()) continue; GameState s; LogInfo("Extracting tileset \"%s\"", tileSetName.cStr()); auto tileSet = e.extractTileSet(s, tileSetName); if (!tileSet) { LogError("Failed to extract tileset \"%s\"", tileSetName.cStr()); } else { if (!tileSet->saveTileset(BattleMapTileset::getTilesetPath() + "/" + tileSetName, false)) { LogError("Failed to save tileset \"%s\"", tileSetName.cStr()); } } } }}, {"battle_map_sectors", [](const InitialGameStateExtractor &e) { for (auto &mapName : e.battleMapPaths) { // Some indices are empty? if (mapName.empty()) continue; GameState s; LogInfo("Extracting map sectors from \"%s\"", mapName.cStr()); auto sectors = e.extractMapSectors(s, mapName); LogInfo("Extracted %u sectors from \"%s\"", (unsigned)sectors.size(), mapName.cStr()); if (sectors.empty()) { LogError("Failed to sectors from map \"%s\"", mapName.cStr()); } for (auto &sectorPair : sectors) { auto &sectorName = sectorPair.first; auto &sector = sectorPair.second; auto path = BattleMapSectorTiles::getMapSectorPath(); if (!sector->saveSector(path + "/" + sectorName, false)) { LogError("Failed to save map sector \"%s\"", sectorName.cStr()); } } } }}, }; ConfigOptionString extractList( "Extractor", "extract", "Comma-separated list of things to extract - \"all\" is special meaning everything", "all"); int main(int argc, char *argv[]) { if (config().parseOptions(argc, argv)) { return EXIT_FAILURE; } auto extractListString = extractList.get(); std::list<std::pair<UString, std::function<void(const InitialGameStateExtractor &e)>>> extractorsToRun; if (extractListString == "all") { LogWarning("Running all extractors"); for (auto &ePair : thingsToExtract) { extractorsToRun.push_back(ePair); } } else { auto list = extractListString.split(","); for (auto &extractorName : list) { auto extractor = thingsToExtract.find(extractorName); if (extractor == thingsToExtract.end()) { LogError("Unknown extractor %s", extractorName.cStr()); return EXIT_FAILURE; } else { extractorsToRun.push_back(*extractor); } } } Framework fw(UString(argv[0]), false); InitialGameStateExtractor initialGameStateExtractor; for (auto ePair : extractorsToRun) { LogWarning("Running %s", ePair.first.cStr()); ePair.second(initialGameStateExtractor); } return 0; } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/gpu_fusible.h" #include <iterator> #include <vector> #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/shape_util.h" namespace xla { namespace gpu { namespace { void AppendParams(const HloInstruction& instr, std::vector<HloInstruction*>* params) { if (instr.opcode() == HloOpcode::kFusion) { params->insert(std::end(*params), std::begin(instr.fused_parameters()), std::end(instr.fused_parameters())); } else { for (HloInstruction* operand : instr.operands()) { params->push_back(operand); } } } } // namespace bool LayoutsAreReduceInputFusionFriendly(const HloInstruction& producer, const HloInstruction& reduce) { std::vector<HloInstruction*> params; AppendParams(producer, &params); AppendParams(reduce, &params); int64 max_rank = -1; const Layout* max_rank_layout; for (HloInstruction* param : params) { if (param->shape().IsArray() && param->shape().rank() > max_rank) { max_rank = param->shape().rank(); max_rank_layout = &param->shape().layout(); } } return absl::c_all_of(params, [&](HloInstruction* param) { return (!param->shape().IsArray()) || (param->shape().rank() < max_rank) || (LayoutUtil::Equal(param->shape().layout(), *max_rank_layout)); }); } bool IsReduceInputFusion(const HloInstruction& instr) { if (instr.IsMultiOutputFusion()) { for (const HloInstruction* operand : instr.fused_expression_root()->operands()) { if (IsReductionFromOrToContiguousDimensions(*operand)) { CHECK(instr.IsInputFusion()) << " Multi-output fusion rooted at reduction-to-vector ops must be " "of kind kInput: " << instr.ToString(); return true; } } } else if (instr.opcode() == HloOpcode::kFusion && IsReductionFromOrToContiguousDimensions( *instr.fused_expression_root())) { CHECK(instr.IsInputFusion()) << " Fusion rooted at reduction-to-vector op must be of kind kInput: " << instr.ToString(); return true; } return false; } bool IsInputFusibleReduction(const HloInstruction& instr) { // TODO(b/129089333): Don't fuse variadic reduce. if (instr.opcode() == HloOpcode::kReduce && instr.shape().IsTuple()) { return false; } return IsReduceInputFusion(instr) || IsReductionFromOrToContiguousDimensions(instr); } bool ShapesCompatibleForMultiOutputFusion(const HloInstruction& instr1, const HloInstruction& instr2) { // Returns the instructions that determines the emitter used for lowering, // sometimes referred to as "the real hero". auto get_real_hero = [&](const HloInstruction* instr) -> const HloInstruction* { if (instr->opcode() == HloOpcode::kFusion) { auto fused_expression_root = instr->fused_expression_root(); if (instr->IsMultiOutputFusion()) { // If possible, we want to pick a reduction-to-vector operand of the // fusion root, because it has the most constraints. for (const auto* inst : fused_expression_root->operands()) { if (IsReductionFromOrToContiguousDimensions(*inst)) { return inst; } } return fused_expression_root->operands()[0]; } return fused_expression_root; } return instr; }; // Multi-output fusion kernels share a common parallel loop. The loop // dimenstions are determined by instruction shapes. auto get_loop_shape = [&](const HloInstruction* element_instr) { // Special-case reduction-to-vector ops: The loop dimensions are determined // by the shape of the first operand. if (IsReductionFromOrToContiguousDimensions(*element_instr)) { return element_instr->operand(0)->shape(); } return element_instr->shape(); }; // All shapes of the root tuple of multi-output fusions should agree, i.e. all // root ops should have equal output shapes. An exception are // reduction-to-vector ops. Here the input shapes of the reduction (first // operand shape) and the reduction dimensions need to match. auto* instr_1 = get_real_hero(&instr1); auto* instr_2 = get_real_hero(&instr2); // TODO(tjoerg): Relax the shape constraint. The datatype does not matter. if (IsReductionFromOrToContiguousDimensions(*instr_1) && IsReductionFromOrToContiguousDimensions(*instr_2) && (!ShapeUtil::Equal(instr_1->shape(), instr_2->shape()) || instr_1->dimensions() != instr_2->dimensions())) { return false; } // The elementwise output shapes must be the same (including layout). // TODO(tjoerg): Further relax the constraint. The datatype does not matter. return ShapeUtil::EqualIgnoringFpPrecision(get_loop_shape(instr_1), get_loop_shape(instr_2)); } bool IsInputFusibleScatter(const HloInstruction& instr) { if (instr.opcode() == HloOpcode::kScatter || (instr.opcode() == HloOpcode::kFusion && instr.fusion_kind() == HloInstruction::FusionKind::kInput && instr.fused_expression_root()->opcode() == HloOpcode::kScatter)) { return true; } return false; } bool IsInputFusible(const HloInstruction& instr) { // Input fusion only handles non-elemental reduction and scatter operations. return instr.IsFusible() && (IsInputFusibleReduction(instr) || IsInputFusibleScatter(instr)); } bool IsLoopFusible(const HloInstruction& instr) { // Don't fuse get-tuple-element on GPU: We can, but it's slower than not // fusing. We never generate kernels for unfused GTEs. Instead, if an // unfused GTE is an input to a kernel (including a fusion kernel), we // compute the address of the GTE at the top of the kernel. Often we know the // address of the GTE result statically, so we can do this without chasing any // pointers. return instr.IsFusible() && ((instr.IsElementwise() && instr.operand_count() > 0) || instr.opcode() == HloOpcode::kBitcast || instr.opcode() == HloOpcode::kBroadcast || instr.opcode() == HloOpcode::kConcatenate || instr.opcode() == HloOpcode::kDynamicSlice || instr.opcode() == HloOpcode::kDynamicUpdateSlice || (instr.opcode() == HloOpcode::kFusion && instr.fusion_kind() == HloInstruction::FusionKind::kLoop) || instr.opcode() == HloOpcode::kGather || instr.opcode() == HloOpcode::kIota || instr.opcode() == HloOpcode::kPad || (instr.opcode() == HloOpcode::kReduce && !IsReductionFromOrToContiguousDimensions(instr) && !instr.shape().IsTuple()) || // TODO(b/129089333): Don't fuse // variadic reductions. instr.opcode() == HloOpcode::kReduceWindow || instr.opcode() == HloOpcode::kReshape || instr.opcode() == HloOpcode::kReverse || instr.opcode() == HloOpcode::kSlice || instr.opcode() == HloOpcode::kConstant || instr.opcode() == HloOpcode::kTranspose); } bool IsFusible(const HloInstruction& instr) { return IsInputFusible(instr) || IsLoopFusible(instr); } bool IsProducerConsumerFusible(const HloInstruction& producer, const HloInstruction& consumer) { if (!IsLoopFusible(producer) || !IsFusible(consumer)) { return false; } // Skip multiple output fusion. It's not yet supported. if (producer.IsMultiOutputFusion()) { return false; } // Do not fuse into reduce input fusions if the resulting kernel would suffer // from poor data locality (due to unfriendly input layouts). if (IsInputFusibleReduction(consumer) && !LayoutsAreReduceInputFusionFriendly(producer, consumer)) { return false; } // We can't fuse library calls, so if a user of such an op could become a // bitcast, leave it unfused. See `xla::InstructionFusion::ShouldFuse` for // further rationale. if (producer.CouldBeBitcast() && ImplementedAsLibraryCall(*producer.operand(0))) { return false; } // Fuse scalar constants into loop fusion nodes. This reduces the number of // parameters and makes matching scalar broadcasts easier. // // Don't fuse other constants: Unfused constants in GPU land can be // represented as an external constant (i.e. not emitted in LLVM IR / PTX), // but fused constants are handled by shrared CPU/GPU code and always emitted // in the IR/PTX. The external constant representation makes for faster // compiles and significantly smaller assembly code. if (producer.opcode() == HloOpcode::kConstant) { return ShapeUtil::IsEffectiveScalar(producer.shape()) && consumer.opcode() == HloOpcode::kFusion; } return true; } bool IsProducerConsumerMultiOutputFusible(const HloInstruction& producer, const HloInstruction& consumer) { if (!IsLoopFusible(producer) || !IsFusibleAsMultiOutputFusionRoot(consumer)) { return false; } if (!ShapesCompatibleForMultiOutputFusion(producer, consumer)) { return false; } if (!LayoutsAreReduceInputFusionFriendly(producer, consumer)) { return false; } return true; } // This function limits the maximum number of operands to a fusion. // // There's a cap on how many parameters we can pass to a CUDA kernel, but // exactly what that limit is hazy, as it depends on (among other things) how // much GPU constant memory is in use for other purposes. // // Moreover, we don't even know at the point that we're running fusion how many // arguments the CUDA kernel for a fusion node will have: It depends on buffer // assignment, where we will decide which of the fusion's operands live in XLA's // big temp buffer versus in other allocations. // // As a heuristic, we simply cap the number of fusion operands plus outputs at // kMaxOperandsAndOutputsPerFusion. This puts an upper bound on the number of // parameters to the kernel, working around the correctness problem. // // This limit is also often good for performance. In a fusion with many // operands, each GPU thread likely has to do a lot of work, and so possibly // uses a lot of registers, thus limiting occupancy. bool FusionWouldBeTooLarge(const HloInstruction& instr1, const HloInstruction& instr2) { // Compute the number of outputs of the (possibly multi-output) fusion node // we're considering creating. // // This isn't precise; we may be off by one if // - We're creating a multi-output fusion out of two non-MOFs. Creating a // MOF adds a new buffer, namely, the tuple buffer. // - We're merging two MOFs. In this case, we should count the tuple buffer // only once. // - WLOG there's an edge from `a` to `b` and `b` is the only consumer of // `a`. In this case the result of `a` is not part of the output of the // fusion. // // But because this is a heuristic and our limit // kMaxOperandsAndOutputsPerFusion is a large value (so +/- 1 doesn't make a // big difference), we ignore this small inaccuracy in favor of simplicity. int64 num_output_buffers = ShapeUtil::SubshapeCount(instr1.shape()) + ShapeUtil::SubshapeCount(instr2.shape()); // The new fusion will have no more operands and outputs than // producer_operands + consumer_operands - 1 + num_output_buffers // (minus one because we may be fusing a producer->consumer edge between `a` // and `b`). // // This fact may be enough to let us avoid having to compute the true total // number of operands, which can be expensive. if (instr1.operand_count() + instr2.operand_count() - 1 + num_output_buffers <= kMaxOperandsAndOutputsPerFusion) { return false; } // Compute the precise number of operands to the new fusion. absl::flat_hash_set<const HloInstruction*> operands(instr1.operands().begin(), instr1.operands().end()); operands.insert(instr2.operands().begin(), instr2.operands().end()); // If there's an edge between `a` and `b`, don't count it: We're fusing that // producer -> consumer relationship. operands.erase(&instr1); operands.erase(&instr2); return operands.size() + num_output_buffers > kMaxOperandsAndOutputsPerFusion; } bool IsFusibleAsMultiOutputFusionRoot(const HloInstruction& instr) { // We can fuse reduces and loop fusions. Elementwise instructions can be fused // with any other instruction. // Note that scatter cannot be the root of a multi-output fusion because // its emitter doesn't support it. return instr.IsFusible() && (IsInputFusibleReduction(instr) || instr.IsLoopFusion() || // TODO(b/130013493): Use IsLoopFusible here. instr.IsElementwise()); } HloInstruction::FusionKind ChooseFusionKind(const HloInstruction& /*producer*/, const HloInstruction& consumer) { return IsInputFusible(consumer) ? HloInstruction::FusionKind::kInput : HloInstruction::FusionKind::kLoop; } } // namespace gpu } // namespace xla <commit_msg>[XLA:GPU] Skip multi-output fusion in IsProducerConsumerMultiOutputFusible().<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/gpu_fusible.h" #include <iterator> #include <vector> #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/shape_util.h" namespace xla { namespace gpu { namespace { void AppendParams(const HloInstruction& instr, std::vector<HloInstruction*>* params) { if (instr.opcode() == HloOpcode::kFusion) { params->insert(std::end(*params), std::begin(instr.fused_parameters()), std::end(instr.fused_parameters())); } else { for (HloInstruction* operand : instr.operands()) { params->push_back(operand); } } } } // namespace bool LayoutsAreReduceInputFusionFriendly(const HloInstruction& producer, const HloInstruction& reduce) { std::vector<HloInstruction*> params; AppendParams(producer, &params); AppendParams(reduce, &params); int64 max_rank = -1; const Layout* max_rank_layout; for (HloInstruction* param : params) { if (param->shape().IsArray() && param->shape().rank() > max_rank) { max_rank = param->shape().rank(); max_rank_layout = &param->shape().layout(); } } return absl::c_all_of(params, [&](HloInstruction* param) { return (!param->shape().IsArray()) || (param->shape().rank() < max_rank) || (LayoutUtil::Equal(param->shape().layout(), *max_rank_layout)); }); } bool IsReduceInputFusion(const HloInstruction& instr) { if (instr.IsMultiOutputFusion()) { for (const HloInstruction* operand : instr.fused_expression_root()->operands()) { if (IsReductionFromOrToContiguousDimensions(*operand)) { CHECK(instr.IsInputFusion()) << " Multi-output fusion rooted at reduction-to-vector ops must be " "of kind kInput: " << instr.ToString(); return true; } } } else if (instr.opcode() == HloOpcode::kFusion && IsReductionFromOrToContiguousDimensions( *instr.fused_expression_root())) { CHECK(instr.IsInputFusion()) << " Fusion rooted at reduction-to-vector op must be of kind kInput: " << instr.ToString(); return true; } return false; } bool IsInputFusibleReduction(const HloInstruction& instr) { // TODO(b/129089333): Don't fuse variadic reduce. if (instr.opcode() == HloOpcode::kReduce && instr.shape().IsTuple()) { return false; } return IsReduceInputFusion(instr) || IsReductionFromOrToContiguousDimensions(instr); } bool ShapesCompatibleForMultiOutputFusion(const HloInstruction& instr1, const HloInstruction& instr2) { // Returns the instructions that determines the emitter used for lowering, // sometimes referred to as "the real hero". auto get_real_hero = [&](const HloInstruction* instr) -> const HloInstruction* { if (instr->opcode() == HloOpcode::kFusion) { auto fused_expression_root = instr->fused_expression_root(); if (instr->IsMultiOutputFusion()) { // If possible, we want to pick a reduction-to-vector operand of the // fusion root, because it has the most constraints. for (const auto* inst : fused_expression_root->operands()) { if (IsReductionFromOrToContiguousDimensions(*inst)) { return inst; } } return fused_expression_root->operands()[0]; } return fused_expression_root; } return instr; }; // Multi-output fusion kernels share a common parallel loop. The loop // dimenstions are determined by instruction shapes. auto get_loop_shape = [&](const HloInstruction* element_instr) { // Special-case reduction-to-vector ops: The loop dimensions are determined // by the shape of the first operand. if (IsReductionFromOrToContiguousDimensions(*element_instr)) { return element_instr->operand(0)->shape(); } return element_instr->shape(); }; // All shapes of the root tuple of multi-output fusions should agree, i.e. all // root ops should have equal output shapes. An exception are // reduction-to-vector ops. Here the input shapes of the reduction (first // operand shape) and the reduction dimensions need to match. auto* instr_1 = get_real_hero(&instr1); auto* instr_2 = get_real_hero(&instr2); // TODO(tjoerg): Relax the shape constraint. The datatype does not matter. if (IsReductionFromOrToContiguousDimensions(*instr_1) && IsReductionFromOrToContiguousDimensions(*instr_2) && (!ShapeUtil::Equal(instr_1->shape(), instr_2->shape()) || instr_1->dimensions() != instr_2->dimensions())) { return false; } // The elementwise output shapes must be the same (including layout). // TODO(tjoerg): Further relax the constraint. The datatype does not matter. return ShapeUtil::EqualIgnoringFpPrecision(get_loop_shape(instr_1), get_loop_shape(instr_2)); } bool IsInputFusibleScatter(const HloInstruction& instr) { if (instr.opcode() == HloOpcode::kScatter || (instr.opcode() == HloOpcode::kFusion && instr.fusion_kind() == HloInstruction::FusionKind::kInput && instr.fused_expression_root()->opcode() == HloOpcode::kScatter)) { return true; } return false; } bool IsInputFusible(const HloInstruction& instr) { // Input fusion only handles non-elemental reduction and scatter operations. return instr.IsFusible() && (IsInputFusibleReduction(instr) || IsInputFusibleScatter(instr)); } bool IsLoopFusible(const HloInstruction& instr) { // Don't fuse get-tuple-element on GPU: We can, but it's slower than not // fusing. We never generate kernels for unfused GTEs. Instead, if an // unfused GTE is an input to a kernel (including a fusion kernel), we // compute the address of the GTE at the top of the kernel. Often we know the // address of the GTE result statically, so we can do this without chasing any // pointers. return instr.IsFusible() && ((instr.IsElementwise() && instr.operand_count() > 0) || instr.opcode() == HloOpcode::kBitcast || instr.opcode() == HloOpcode::kBroadcast || instr.opcode() == HloOpcode::kConcatenate || instr.opcode() == HloOpcode::kDynamicSlice || instr.opcode() == HloOpcode::kDynamicUpdateSlice || (instr.opcode() == HloOpcode::kFusion && instr.fusion_kind() == HloInstruction::FusionKind::kLoop) || instr.opcode() == HloOpcode::kGather || instr.opcode() == HloOpcode::kIota || instr.opcode() == HloOpcode::kPad || (instr.opcode() == HloOpcode::kReduce && !IsReductionFromOrToContiguousDimensions(instr) && !instr.shape().IsTuple()) || // TODO(b/129089333): Don't fuse // variadic reductions. instr.opcode() == HloOpcode::kReduceWindow || instr.opcode() == HloOpcode::kReshape || instr.opcode() == HloOpcode::kReverse || instr.opcode() == HloOpcode::kSlice || instr.opcode() == HloOpcode::kConstant || instr.opcode() == HloOpcode::kTranspose); } bool IsFusible(const HloInstruction& instr) { return IsInputFusible(instr) || IsLoopFusible(instr); } bool IsProducerConsumerFusible(const HloInstruction& producer, const HloInstruction& consumer) { if (!IsLoopFusible(producer) || !IsFusible(consumer)) { return false; } // Skip multiple output fusion. It's not yet supported. if (producer.IsMultiOutputFusion()) { return false; } // Do not fuse into reduce input fusions if the resulting kernel would suffer // from poor data locality (due to unfriendly input layouts). if (IsInputFusibleReduction(consumer) && !LayoutsAreReduceInputFusionFriendly(producer, consumer)) { return false; } // We can't fuse library calls, so if a user of such an op could become a // bitcast, leave it unfused. See `xla::InstructionFusion::ShouldFuse` for // further rationale. if (producer.CouldBeBitcast() && ImplementedAsLibraryCall(*producer.operand(0))) { return false; } // Fuse scalar constants into loop fusion nodes. This reduces the number of // parameters and makes matching scalar broadcasts easier. // // Don't fuse other constants: Unfused constants in GPU land can be // represented as an external constant (i.e. not emitted in LLVM IR / PTX), // but fused constants are handled by shrared CPU/GPU code and always emitted // in the IR/PTX. The external constant representation makes for faster // compiles and significantly smaller assembly code. if (producer.opcode() == HloOpcode::kConstant) { return ShapeUtil::IsEffectiveScalar(producer.shape()) && consumer.opcode() == HloOpcode::kFusion; } return true; } bool IsProducerConsumerMultiOutputFusible(const HloInstruction& producer, const HloInstruction& consumer) { // Skip multiple output fusion. It's not yet supported. if (producer.IsMultiOutputFusion()) { return false; } if (!IsLoopFusible(producer) || !IsFusibleAsMultiOutputFusionRoot(consumer)) { return false; } if (!ShapesCompatibleForMultiOutputFusion(producer, consumer)) { return false; } if (!LayoutsAreReduceInputFusionFriendly(producer, consumer)) { return false; } return true; } // This function limits the maximum number of operands to a fusion. // // There's a cap on how many parameters we can pass to a CUDA kernel, but // exactly what that limit is hazy, as it depends on (among other things) how // much GPU constant memory is in use for other purposes. // // Moreover, we don't even know at the point that we're running fusion how many // arguments the CUDA kernel for a fusion node will have: It depends on buffer // assignment, where we will decide which of the fusion's operands live in XLA's // big temp buffer versus in other allocations. // // As a heuristic, we simply cap the number of fusion operands plus outputs at // kMaxOperandsAndOutputsPerFusion. This puts an upper bound on the number of // parameters to the kernel, working around the correctness problem. // // This limit is also often good for performance. In a fusion with many // operands, each GPU thread likely has to do a lot of work, and so possibly // uses a lot of registers, thus limiting occupancy. bool FusionWouldBeTooLarge(const HloInstruction& instr1, const HloInstruction& instr2) { // Compute the number of outputs of the (possibly multi-output) fusion node // we're considering creating. // // This isn't precise; we may be off by one if // - We're creating a multi-output fusion out of two non-MOFs. Creating a // MOF adds a new buffer, namely, the tuple buffer. // - We're merging two MOFs. In this case, we should count the tuple buffer // only once. // - WLOG there's an edge from `a` to `b` and `b` is the only consumer of // `a`. In this case the result of `a` is not part of the output of the // fusion. // // But because this is a heuristic and our limit // kMaxOperandsAndOutputsPerFusion is a large value (so +/- 1 doesn't make a // big difference), we ignore this small inaccuracy in favor of simplicity. int64 num_output_buffers = ShapeUtil::SubshapeCount(instr1.shape()) + ShapeUtil::SubshapeCount(instr2.shape()); // The new fusion will have no more operands and outputs than // producer_operands + consumer_operands - 1 + num_output_buffers // (minus one because we may be fusing a producer->consumer edge between `a` // and `b`). // // This fact may be enough to let us avoid having to compute the true total // number of operands, which can be expensive. if (instr1.operand_count() + instr2.operand_count() - 1 + num_output_buffers <= kMaxOperandsAndOutputsPerFusion) { return false; } // Compute the precise number of operands to the new fusion. absl::flat_hash_set<const HloInstruction*> operands(instr1.operands().begin(), instr1.operands().end()); operands.insert(instr2.operands().begin(), instr2.operands().end()); // If there's an edge between `a` and `b`, don't count it: We're fusing that // producer -> consumer relationship. operands.erase(&instr1); operands.erase(&instr2); return operands.size() + num_output_buffers > kMaxOperandsAndOutputsPerFusion; } bool IsFusibleAsMultiOutputFusionRoot(const HloInstruction& instr) { // We can fuse reduces and loop fusions. Elementwise instructions can be fused // with any other instruction. // Note that scatter cannot be the root of a multi-output fusion because // its emitter doesn't support it. return instr.IsFusible() && (IsInputFusibleReduction(instr) || instr.IsLoopFusion() || // TODO(b/130013493): Use IsLoopFusible here. instr.IsElementwise()); } HloInstruction::FusionKind ChooseFusionKind(const HloInstruction& /*producer*/, const HloInstruction& consumer) { return IsInputFusible(consumer) ? HloInstruction::FusionKind::kInput : HloInstruction::FusionKind::kLoop; } } // namespace gpu } // namespace xla <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_URL_HPP_ #define _QIMESSAGING_URL_HPP_ #include <string> #include <vector> #include <qimessaging/api.hpp> namespace qi { class UrlPrivate; /** qi::Url is an address represented by a protocol, a host and a port. * @warning The class isn't compliant with RFC 3986. * * qi::Url can parse the following formats : * - protocol://host:port * - protocol://host * - host:port * - host * - protocol://:port * - protocol:// * - :port * - *empty string* */ class QIMESSAGING_API Url { public: /** Creates an empty url. */ Url(); /** * @param url The url string, the port and the protocol will be extracted * if they're present. */ Url(const std::string &url); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, unsigned short defaultPort); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. */ Url(const std::string &url, const std::string &defaultProtocol); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, const std::string &defaultProtocol, unsigned short defaultPort); /** * @param url The url string, the port and the protocol will be extracted * if they're present. */ Url(const char *url); /** Compares the url strings. */ bool operator ==(const Url& url); virtual ~Url(); Url(const qi::Url& url); Url& operator= (const Url& rhs); /** Equivalent to this->str() < rhs.str(). */ bool operator< (const Url& rhs) const; /** * @return True if the port and the protocol had been set. */ bool isValid() const; /** * @return The url string used by the Url class, the port and/or the * protocol may have been appended if they had been given in the * constructor. */ const std::string& str() const; /** * @return The protocol of the url or an empty string if no protocol was * set. */ const std::string& protocol() const; /** * @return The host part of the url or an empty string if no host part was * found. */ const std::string& host() const; /** * @return The port of the url, 0 if no port were given. */ unsigned short port() const; UrlPrivate* _p; }; typedef std::vector<Url> UrlVector; } #endif // _QIMESSAGING_URL_HPP_ <commit_msg>Setting _p qi::Url's member in private.<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_URL_HPP_ #define _QIMESSAGING_URL_HPP_ #include <string> #include <vector> #include <qimessaging/api.hpp> namespace qi { class UrlPrivate; /** qi::Url is an address represented by a protocol, a host and a port. * @warning The class isn't compliant with RFC 3986. * * qi::Url can parse the following formats : * - protocol://host:port * - protocol://host * - host:port * - host * - protocol://:port * - protocol:// * - :port * - *empty string* */ class QIMESSAGING_API Url { public: /** Creates an empty url. */ Url(); /** * @param url The url string, the port and the protocol will be extracted * if they're present. */ Url(const std::string &url); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, unsigned short defaultPort); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. */ Url(const std::string &url, const std::string &defaultProtocol); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, const std::string &defaultProtocol, unsigned short defaultPort); /** * @param url The url string, the port and the protocol will be extracted * if they're present. */ Url(const char *url); /** Compares the url strings. */ bool operator ==(const Url& url); virtual ~Url(); Url(const qi::Url& url); Url& operator= (const Url& rhs); /** Equivalent to this->str() < rhs.str(). */ bool operator< (const Url& rhs) const; /** * @return True if the port and the protocol had been set. */ bool isValid() const; /** * @return The url string used by the Url class, the port and/or the * protocol may have been appended if they had been given in the * constructor. */ const std::string& str() const; /** * @return The protocol of the url or an empty string if no protocol was * set. */ const std::string& protocol() const; /** * @return The host part of the url or an empty string if no host part was * found. */ const std::string& host() const; /** * @return The port of the url, 0 if no port were given. */ unsigned short port() const; private: UrlPrivate* _p; }; typedef std::vector<Url> UrlVector; } #endif // _QIMESSAGING_URL_HPP_ <|endoftext|>
<commit_before>/* * Part of Appstream, a library for accessing AppStream on-disk database * Copyright 2014 Sune Vuorela <sune@vuorela.dk> * * Based upon database-read.hpp * Copyright (C) 2012-2014 Matthias Klumpp <matthias@tenstral.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #define QT_NO_KEYWORDS #include "database.h" #include "screenshotxmlparser_p.h" #include <database-common.hpp> #include <xapian.h> #include <QStringList> #include <QUrl> #include <QMultiHash> using namespace Appstream; class Appstream::DatabasePrivate { public: DatabasePrivate(const QString& dbpath) : m_dbPath(dbpath) { } QString m_dbPath; QString m_errorString; Xapian::Database m_db; bool open() { try { m_db = Xapian::Database (m_dbPath.trimmed().toStdString()); } catch (const Xapian::Error &error) { m_errorString = QString::fromStdString (error.get_msg()); return false; } return true; } ~DatabasePrivate() { m_db.close(); } }; Database::Database(const QString& dbPath) : d(new DatabasePrivate(dbPath)) { } bool Database::open() { return d->open(); } QString Database::errorString() const { return d->m_errorString; } Database::~Database() { // empty. needed for the scoped pointer for the private pointer } QString value(Xapian::Document document, XapianValues::XapianValues index) { return QString::fromStdString(document.get_value(index)); } QSize parseSizeString(QString s) { QStringList sl = s.split("x"); if (sl.count() != 2) return QSize(); return QSize(sl[0].toInt(),sl[1].toInt()); } Component xapianDocToComponent(Xapian::Document document) { Component component; // kind QString kindString = value (document, XapianValues::TYPE); component.setKind(Component::stringToKind(kindString)); // Identifier QString id = value(document, XapianValues::IDENTIFIER); component.setId(id); // Component name QString name = value(document,XapianValues::CPTNAME); component.setName(name); // Package name QStringList packageNames = value(document,XapianValues::PKGNAME).split("\n",QString::SkipEmptyParts); component.setPackageNames(packageNames); // URLs QString concatUrlStrings = value(document, XapianValues::URLS); QStringList urlStrings = concatUrlStrings.split('\n',QString::SkipEmptyParts); if(urlStrings.size() %2 == 0) { QMultiHash<Component::UrlKind, QUrl> urls; for(int i = 0; i < urlStrings.size(); i=i+2) { Component::UrlKind ukind = Component::stringToUrlKind(urlStrings.at(i)); QUrl url = QUrl::fromUserInput(urlStrings.at(i+1)); urls.insertMulti(ukind, url); } component.setUrls(urls); } else { qWarning("Bad url strings for component: '%s' (%s)", qPrintable(id), qPrintable(concatUrlStrings)); } // Provided items QString concatProvides = value(document, XapianValues::PROVIDED_ITEMS); QStringList providesList = concatProvides.split('\n',QString::SkipEmptyParts); QList<Provides> provideslist; Q_FOREACH(const QString& string, providesList) { QStringList providesParts = string.split(';',QString::SkipEmptyParts); if(providesParts.size() < 2) { qWarning("Bad component parts for component: '%s' (%s)", qPrintable(id), qPrintable(string)); continue; } QString kindString = providesParts.takeFirst(); Provides::Kind kind = Provides::stringToKind(kindString); Provides provides; provides.setKind(kind); QString value = providesParts.takeFirst(); provides.setValue(value); QString extraData = providesParts.join(";"); provides.setExtraData(extraData); provideslist << provides; } component.setProvides(provideslist); // Bundles QString concatBundleIds = value(document, XapianValues::BUNDLES); QStringList bundleIds = concatBundleIds.split('\n',QString::SkipEmptyParts); if(bundleIds.size() %2 == 0) { QHash<Component::BundleKind, QString> bundles; for(int i = 0; i < bundleIds.size(); i=i+2) { Component::BundleKind bkind = Component::stringToBundleKind(bundleIds.at(i)); QString bdid = QString(bundleIds.at(i+1)); bundles.insertMulti(bkind, bdid); } component.setBundles(bundles); } else { qWarning("Bad bundle strings for component: '%s' (%s)", qPrintable(id), qPrintable(concatBundleIds)); } // Stock icon QString icon = value(document,XapianValues::ICON); component.setIcon(icon); // Icon urls QString concatIconUrlStrings = value(document, XapianValues::ICON_URLS); QStringList iconUrlStrings = concatIconUrlStrings.split('\n',QString::SkipEmptyParts); if(iconUrlStrings.size() %2 == 0) { for(int i = 0; i < iconUrlStrings.size(); i=i+2) { QString sizeStr = iconUrlStrings.at(i); QUrl url = QUrl::fromUserInput(iconUrlStrings.at(i+1)); QSize size = parseSizeString(sizeStr); component.addIconUrl(url, size); } } else { qWarning("Bad icon-url strings for component: '%s' (%s)", qPrintable(id), qPrintable(concatIconUrlStrings)); } // Summary QString summary = value(document,XapianValues::SUMMARY); component.setSummary(summary); // Long description QString description = value(document,XapianValues::DESCRIPTION); component.setDescription(description); // Categories QStringList categories = value(document, XapianValues::CATEGORIES).split(";"); component.setCategories(categories); // Screenshot data QString screenshotXml = value(document,XapianValues::SCREENSHOT_DATA); QXmlStreamReader reader(screenshotXml); QList<Appstream::Screenshot> screenshots = parseScreenshotsXml(&reader); component.setScreenshots(screenshots); // Compulsory-for-desktop information QStringList compulsory = value(document, XapianValues::COMPULSORY_FOR).split(";"); component.setCompulsoryForDesktops(compulsory); // License QString license = value(document,XapianValues::LICENSE); component.setProjectLicense(license); // Project group QString projectGroup = value(document,XapianValues::PROJECT_GROUP); component.setProjectGroup(projectGroup); // Developer name QString developerName = value(document,XapianValues::DEVELOPER_NAME); component.setDeveloperName(developerName); // Releases data QString releasesXml = value(document,XapianValues::RELEASES_DATA); Q_UNUSED(releasesXml); return component; } QList<Component> parseSearchResults(Xapian::MSet matches) { QList<Component> components; for (Xapian::MSetIterator it = matches.begin(); it != matches.end(); ++it) { Xapian::Document document = it.get_document (); components << xapianDocToComponent(document); } return components; } QList< Component > Database::allComponents() const { QList<Component> components; // Iterate through all Xapian documents Xapian::PostingIterator it = d->m_db.postlist_begin (std::string()); for (Xapian::PostingIterator it = d->m_db.postlist_begin(std::string());it != d->m_db.postlist_end(std::string()); ++it) { Xapian::Document doc = d->m_db.get_document (*it); Component component = xapianDocToComponent (doc); components << component; } return components; } Component Database::componentById(const QString& id) const { Xapian::Query id_query = Xapian::Query (Xapian::Query::OP_OR, Xapian::Query("AI" + id.trimmed().toStdString()), Xapian::Query ()); id_query.serialise (); Xapian::Enquire enquire = Xapian::Enquire (d->m_db); enquire.set_query (id_query); Xapian::MSet matches = enquire.get_mset (0, d->m_db.get_doccount ()); if (matches.size () > 1) { qWarning ("Found more than one component with id '%s'! Returning the first one.", qPrintable(id)); Q_ASSERT(false); } if (matches.empty()) { return Component(); } Xapian::Document document = matches[matches.get_firstitem ()].get_document (); return xapianDocToComponent(document); } QList< Component > Database::componentsByKind(Component::Kind kind) const { Xapian::Query item_query; item_query = Xapian::Query ("AT" + Component::kindToString(kind).toStdString()); item_query.serialise (); Xapian::Enquire enquire = Xapian::Enquire (d->m_db); enquire.set_query (item_query); Xapian::MSet matches = enquire.get_mset (0, d->m_db.get_doccount ()); return parseSearchResults(matches); } Xapian::QueryParser newAppStreamParser (Xapian::Database db) { Xapian::QueryParser xapian_parser = Xapian::QueryParser (); xapian_parser.set_database (db); xapian_parser.add_boolean_prefix ("pkg", "XP"); xapian_parser.add_boolean_prefix ("pkg", "AP"); xapian_parser.add_boolean_prefix ("mime", "AM"); xapian_parser.add_boolean_prefix ("section", "XS"); xapian_parser.add_boolean_prefix ("origin", "XOC"); xapian_parser.add_prefix ("pkg_wildcard", "XP"); xapian_parser.add_prefix ("pkg_wildcard", "AP"); xapian_parser.set_default_op (Xapian::Query::OP_AND); return xapian_parser; } typedef QPair<Xapian::Query, Xapian::Query> QueryPair; QueryPair buildQueries(QString searchTerm, const QStringList& categories, Xapian::Database db) { // empty query returns a query that matches nothing (for performance // reasons) if (searchTerm.isEmpty() && categories.isEmpty()) { return QueryPair(); } // generate category query Xapian::Query categoryQuery = Xapian::Query (); Q_FOREACH(const QString& category, categories) { categoryQuery = Xapian::Query(Xapian::Query::OP_OR, categoryQuery, Xapian::Query(category.trimmed().toLower().toStdString())); } // we cheat and return a match-all query for single letter searches if (searchTerm.size() < 2) { Xapian::Query allQuery = Xapian::Query(Xapian::Query::OP_OR,Xapian::Query (""), categoryQuery); return QueryPair(allQuery,allQuery); } // get a pkg query Xapian::Query pkgQuery = Xapian::Query (); // try split on one magic char if(searchTerm.contains(',')) { QStringList parts = searchTerm.split(','); Q_FOREACH(const QString& part, parts) { pkgQuery = Xapian::Query (Xapian::Query::OP_OR, pkgQuery, Xapian::Query ("XP" + part.trimmed().toStdString())); pkgQuery = Xapian::Query (Xapian::Query::OP_OR, pkgQuery, Xapian::Query ("AP" + part.trimmed().toStdString())); } } else { // try another QStringList parts = searchTerm.split('\n'); Q_FOREACH(const QString& part, parts) { pkgQuery = Xapian::Query (Xapian::Query::OP_OR, Xapian::Query("XP" + part.trimmed().toStdString()), pkgQuery); } } if(!categoryQuery.empty()) { pkgQuery = Xapian::Query(Xapian::Query::OP_AND,pkgQuery, categoryQuery); } // get a search query if (!searchTerm.contains (':')) { // ie, not a mimetype query // we need this to work around xapian oddness searchTerm = searchTerm.replace('-','_'); } Xapian::QueryParser parser = newAppStreamParser (db); Xapian::Query fuzzyQuery = parser.parse_query (searchTerm.trimmed().toStdString(), Xapian::QueryParser::FLAG_PARTIAL | Xapian::QueryParser::FLAG_BOOLEAN); // if the query size goes out of hand, omit the FLAG_PARTIAL // (LP: #634449) if (fuzzyQuery.get_length () > 1000) { fuzzyQuery = parser.parse_query(searchTerm.trimmed().toStdString(), Xapian::QueryParser::FLAG_BOOLEAN); } // now add categories if(!categoryQuery.empty()) { fuzzyQuery = Xapian::Query(Xapian::Query::OP_AND,fuzzyQuery, categoryQuery); } return QueryPair(pkgQuery, fuzzyQuery); } QList< Component > Database::findComponentsByString(const QString& searchTerm, const QStringList& categories) { QPair<Xapian::Query, Xapian::Query> queryPair = buildQueries(searchTerm.trimmed(), categories, d->m_db); // "normal" query Xapian::Query query = queryPair.first; query.serialise (); Xapian::Enquire enquire = Xapian::Enquire (d->m_db); enquire.set_query (query); QList<Component> result = parseSearchResults (enquire.get_mset(0,d->m_db.get_doccount())); // do fuzzy query if we got no results if (result.isEmpty()) { query = queryPair.second; query.serialise (); enquire = Xapian::Enquire (d->m_db); enquire.set_query (query); result = parseSearchResults(enquire.get_mset(0,d->m_db.get_doccount())); } return result; } QList<Component> Database::findComponentsByPackageName(const QString& packageName) const { Xapian::Query pkgQuery(Xapian::Query::OP_OR, pkgQuery, Xapian::Query ("AP" + packageName.trimmed().toStdString())); Xapian::Enquire enquire(d->m_db); enquire.set_query (pkgQuery); QList<Component> result = parseSearchResults (enquire.get_mset(0,d->m_db.get_doccount())); return result; } Database::Database() : d(new DatabasePrivate(QLatin1String("/var/cache/app-info/xapian/C"))) { } #include "database.moc" <commit_msg>Add QLoggingCategory appstreamqt.database<commit_after>/* * Part of Appstream, a library for accessing AppStream on-disk database * Copyright 2014 Sune Vuorela <sune@vuorela.dk> * * Based upon database-read.hpp * Copyright (C) 2012-2014 Matthias Klumpp <matthias@tenstral.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #define QT_NO_KEYWORDS #include "database.h" #include "screenshotxmlparser_p.h" #include <database-common.hpp> #include <xapian.h> #include <QStringList> #include <QUrl> #include <QMultiHash> #include <QLoggingCategory> Q_LOGGING_CATEGORY(APPSTREAMQT_DB, "appstreamqt.database") using namespace Appstream; class Appstream::DatabasePrivate { public: DatabasePrivate(const QString& dbpath) : m_dbPath(dbpath) { } QString m_dbPath; QString m_errorString; Xapian::Database m_db; bool open() { try { m_db = Xapian::Database (m_dbPath.trimmed().toStdString()); } catch (const Xapian::Error &error) { m_errorString = QString::fromStdString (error.get_msg()); return false; } return true; } ~DatabasePrivate() { m_db.close(); } }; Database::Database(const QString& dbPath) : d(new DatabasePrivate(dbPath)) { } bool Database::open() { return d->open(); } QString Database::errorString() const { return d->m_errorString; } Database::~Database() { // empty. needed for the scoped pointer for the private pointer } QString value(Xapian::Document document, XapianValues::XapianValues index) { return QString::fromStdString(document.get_value(index)); } QSize parseSizeString(QString s) { QStringList sl = s.split("x"); if (sl.count() != 2) return QSize(); return QSize(sl[0].toInt(),sl[1].toInt()); } Component xapianDocToComponent(Xapian::Document document) { Component component; // kind QString kindString = value (document, XapianValues::TYPE); component.setKind(Component::stringToKind(kindString)); // Identifier QString id = value(document, XapianValues::IDENTIFIER); component.setId(id); // Component name QString name = value(document,XapianValues::CPTNAME); component.setName(name); // Package name QStringList packageNames = value(document,XapianValues::PKGNAME).split("\n",QString::SkipEmptyParts); component.setPackageNames(packageNames); // URLs QString concatUrlStrings = value(document, XapianValues::URLS); QStringList urlStrings = concatUrlStrings.split('\n',QString::SkipEmptyParts); if(urlStrings.size() %2 == 0) { QMultiHash<Component::UrlKind, QUrl> urls; for(int i = 0; i < urlStrings.size(); i=i+2) { Component::UrlKind ukind = Component::stringToUrlKind(urlStrings.at(i)); QUrl url = QUrl::fromUserInput(urlStrings.at(i+1)); urls.insertMulti(ukind, url); } component.setUrls(urls); } else { qCWarning(APPSTREAMQT_DB, "Bad url strings for component: '%s' (%s)", qPrintable(id), qPrintable(concatUrlStrings)); } // Provided items QString concatProvides = value(document, XapianValues::PROVIDED_ITEMS); QStringList providesList = concatProvides.split('\n',QString::SkipEmptyParts); QList<Provides> provideslist; Q_FOREACH(const QString& string, providesList) { QStringList providesParts = string.split(';',QString::SkipEmptyParts); if(providesParts.size() < 2) { qCWarning(APPSTREAMQT_DB, "Bad component parts for component: '%s' (%s)", qPrintable(id), qPrintable(string)); continue; } QString kindString = providesParts.takeFirst(); Provides::Kind kind = Provides::stringToKind(kindString); Provides provides; provides.setKind(kind); QString value = providesParts.takeFirst(); provides.setValue(value); QString extraData = providesParts.join(";"); provides.setExtraData(extraData); provideslist << provides; } component.setProvides(provideslist); // Bundles QString concatBundleIds = value(document, XapianValues::BUNDLES); QStringList bundleIds = concatBundleIds.split('\n',QString::SkipEmptyParts); if(bundleIds.size() %2 == 0) { QHash<Component::BundleKind, QString> bundles; for(int i = 0; i < bundleIds.size(); i=i+2) { Component::BundleKind bkind = Component::stringToBundleKind(bundleIds.at(i)); QString bdid = QString(bundleIds.at(i+1)); bundles.insertMulti(bkind, bdid); } component.setBundles(bundles); } else { qCWarning(APPSTREAMQT_DB, "Bad bundle strings for component: '%s' (%s)", qPrintable(id), qPrintable(concatBundleIds)); } // Stock icon QString icon = value(document,XapianValues::ICON); component.setIcon(icon); // Icon urls QString concatIconUrlStrings = value(document, XapianValues::ICON_URLS); QStringList iconUrlStrings = concatIconUrlStrings.split('\n',QString::SkipEmptyParts); if(iconUrlStrings.size() %2 == 0) { for(int i = 0; i < iconUrlStrings.size(); i=i+2) { QString sizeStr = iconUrlStrings.at(i); QUrl url = QUrl::fromUserInput(iconUrlStrings.at(i+1)); QSize size = parseSizeString(sizeStr); component.addIconUrl(url, size); } } else { qCWarning(APPSTREAMQT_DB, "Bad icon-url strings for component: '%s' (%s)", qPrintable(id), qPrintable(concatIconUrlStrings)); } // Summary QString summary = value(document,XapianValues::SUMMARY); component.setSummary(summary); // Long description QString description = value(document,XapianValues::DESCRIPTION); component.setDescription(description); // Categories QStringList categories = value(document, XapianValues::CATEGORIES).split(";"); component.setCategories(categories); // Screenshot data QString screenshotXml = value(document,XapianValues::SCREENSHOT_DATA); QXmlStreamReader reader(screenshotXml); QList<Appstream::Screenshot> screenshots = parseScreenshotsXml(&reader); component.setScreenshots(screenshots); // Compulsory-for-desktop information QStringList compulsory = value(document, XapianValues::COMPULSORY_FOR).split(";"); component.setCompulsoryForDesktops(compulsory); // License QString license = value(document,XapianValues::LICENSE); component.setProjectLicense(license); // Project group QString projectGroup = value(document,XapianValues::PROJECT_GROUP); component.setProjectGroup(projectGroup); // Developer name QString developerName = value(document,XapianValues::DEVELOPER_NAME); component.setDeveloperName(developerName); // Releases data QString releasesXml = value(document,XapianValues::RELEASES_DATA); Q_UNUSED(releasesXml); return component; } QList<Component> parseSearchResults(Xapian::MSet matches) { QList<Component> components; for (Xapian::MSetIterator it = matches.begin(); it != matches.end(); ++it) { Xapian::Document document = it.get_document (); components << xapianDocToComponent(document); } return components; } QList< Component > Database::allComponents() const { QList<Component> components; // Iterate through all Xapian documents Xapian::PostingIterator it = d->m_db.postlist_begin (std::string()); for (Xapian::PostingIterator it = d->m_db.postlist_begin(std::string());it != d->m_db.postlist_end(std::string()); ++it) { Xapian::Document doc = d->m_db.get_document (*it); Component component = xapianDocToComponent (doc); components << component; } return components; } Component Database::componentById(const QString& id) const { Xapian::Query id_query = Xapian::Query (Xapian::Query::OP_OR, Xapian::Query("AI" + id.trimmed().toStdString()), Xapian::Query ()); id_query.serialise (); Xapian::Enquire enquire = Xapian::Enquire (d->m_db); enquire.set_query (id_query); Xapian::MSet matches = enquire.get_mset (0, d->m_db.get_doccount ()); if (matches.size () > 1) { qCWarning(APPSTREAMQT_DB, "Found more than one component with id '%s'! Returning the first one.", qPrintable(id)); Q_ASSERT(false); } if (matches.empty()) { return Component(); } Xapian::Document document = matches[matches.get_firstitem ()].get_document (); return xapianDocToComponent(document); } QList< Component > Database::componentsByKind(Component::Kind kind) const { Xapian::Query item_query; item_query = Xapian::Query ("AT" + Component::kindToString(kind).toStdString()); item_query.serialise (); Xapian::Enquire enquire = Xapian::Enquire (d->m_db); enquire.set_query (item_query); Xapian::MSet matches = enquire.get_mset (0, d->m_db.get_doccount ()); return parseSearchResults(matches); } Xapian::QueryParser newAppStreamParser (Xapian::Database db) { Xapian::QueryParser xapian_parser = Xapian::QueryParser (); xapian_parser.set_database (db); xapian_parser.add_boolean_prefix ("pkg", "XP"); xapian_parser.add_boolean_prefix ("pkg", "AP"); xapian_parser.add_boolean_prefix ("mime", "AM"); xapian_parser.add_boolean_prefix ("section", "XS"); xapian_parser.add_boolean_prefix ("origin", "XOC"); xapian_parser.add_prefix ("pkg_wildcard", "XP"); xapian_parser.add_prefix ("pkg_wildcard", "AP"); xapian_parser.set_default_op (Xapian::Query::OP_AND); return xapian_parser; } typedef QPair<Xapian::Query, Xapian::Query> QueryPair; QueryPair buildQueries(QString searchTerm, const QStringList& categories, Xapian::Database db) { // empty query returns a query that matches nothing (for performance // reasons) if (searchTerm.isEmpty() && categories.isEmpty()) { return QueryPair(); } // generate category query Xapian::Query categoryQuery = Xapian::Query (); Q_FOREACH(const QString& category, categories) { categoryQuery = Xapian::Query(Xapian::Query::OP_OR, categoryQuery, Xapian::Query(category.trimmed().toLower().toStdString())); } // we cheat and return a match-all query for single letter searches if (searchTerm.size() < 2) { Xapian::Query allQuery = Xapian::Query(Xapian::Query::OP_OR,Xapian::Query (""), categoryQuery); return QueryPair(allQuery,allQuery); } // get a pkg query Xapian::Query pkgQuery = Xapian::Query (); // try split on one magic char if(searchTerm.contains(',')) { QStringList parts = searchTerm.split(','); Q_FOREACH(const QString& part, parts) { pkgQuery = Xapian::Query (Xapian::Query::OP_OR, pkgQuery, Xapian::Query ("XP" + part.trimmed().toStdString())); pkgQuery = Xapian::Query (Xapian::Query::OP_OR, pkgQuery, Xapian::Query ("AP" + part.trimmed().toStdString())); } } else { // try another QStringList parts = searchTerm.split('\n'); Q_FOREACH(const QString& part, parts) { pkgQuery = Xapian::Query (Xapian::Query::OP_OR, Xapian::Query("XP" + part.trimmed().toStdString()), pkgQuery); } } if(!categoryQuery.empty()) { pkgQuery = Xapian::Query(Xapian::Query::OP_AND,pkgQuery, categoryQuery); } // get a search query if (!searchTerm.contains (':')) { // ie, not a mimetype query // we need this to work around xapian oddness searchTerm = searchTerm.replace('-','_'); } Xapian::QueryParser parser = newAppStreamParser (db); Xapian::Query fuzzyQuery = parser.parse_query (searchTerm.trimmed().toStdString(), Xapian::QueryParser::FLAG_PARTIAL | Xapian::QueryParser::FLAG_BOOLEAN); // if the query size goes out of hand, omit the FLAG_PARTIAL // (LP: #634449) if (fuzzyQuery.get_length () > 1000) { fuzzyQuery = parser.parse_query(searchTerm.trimmed().toStdString(), Xapian::QueryParser::FLAG_BOOLEAN); } // now add categories if(!categoryQuery.empty()) { fuzzyQuery = Xapian::Query(Xapian::Query::OP_AND,fuzzyQuery, categoryQuery); } return QueryPair(pkgQuery, fuzzyQuery); } QList< Component > Database::findComponentsByString(const QString& searchTerm, const QStringList& categories) { QPair<Xapian::Query, Xapian::Query> queryPair = buildQueries(searchTerm.trimmed(), categories, d->m_db); // "normal" query Xapian::Query query = queryPair.first; query.serialise (); Xapian::Enquire enquire = Xapian::Enquire (d->m_db); enquire.set_query (query); QList<Component> result = parseSearchResults (enquire.get_mset(0,d->m_db.get_doccount())); // do fuzzy query if we got no results if (result.isEmpty()) { query = queryPair.second; query.serialise (); enquire = Xapian::Enquire (d->m_db); enquire.set_query (query); result = parseSearchResults(enquire.get_mset(0,d->m_db.get_doccount())); } return result; } QList<Component> Database::findComponentsByPackageName(const QString& packageName) const { Xapian::Query pkgQuery(Xapian::Query::OP_OR, pkgQuery, Xapian::Query ("AP" + packageName.trimmed().toStdString())); Xapian::Enquire enquire(d->m_db); enquire.set_query (pkgQuery); QList<Component> result = parseSearchResults (enquire.get_mset(0,d->m_db.get_doccount())); return result; } Database::Database() : d(new DatabasePrivate(QLatin1String("/var/cache/app-info/xapian/C"))) { } #include "database.moc" <|endoftext|>
<commit_before>// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: -T semihosted.lds \ // RUN: -L some/directory/user/asked/for \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-C %s // CHECK-V6M-C: "[[PREFIX_DIR:.*]]/bin/clang" "-cc1" "-triple" "thumbv6m-none--eabi" // CHECK-V6M-C-SAME: "-resource-dir" "[[PREFIX_DIR]]/lib/clang/[[VERSION:[^"]*]]" // CHECK-V6M-C-SAME: "-isysroot" "[[SYSROOT:[^"]*]]" // CHECK-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]/include/c++/v1" // CHECk-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]/include" // CHECK-V6M-C-SAME: "-x" "c++" "{{.*}}baremetal.cpp" // CHECK-V6M-C-NEXT: "[[PREFIX_DIR:.*]]/bin/ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-C-SAME: "-L[[PREFIX_DIR]]/lib/clang/[[VERSION]]/lib/baremetal" // CHECK-V6M-C-SAME: "-T" "semihosted.lds" "-Lsome/directory/user/asked/for" // CHECK-V6M-C-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-C-SAME: "-o" "{{.*}}.o" // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: -nostdlibinc -nobuiltininc \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBINC %s // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: -nostdinc \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBINC %s // CHECK-V6M-LIBINC-NOT: "-internal-isystem" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-DEFAULTCXX %s // CHECK-V6M-DEFAULTCXX: "[[PREFIX_DIR:.*]]/bin/ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-DEFAULTCXX-SAME: "-L[[PREFIX_DIR]]/lib/clang/{{.*}}/lib/baremetal" // CHECK-V6M-DEFAULTCXX-SAME: "-lc++" "-lc++abi" "-lunwind" // CHECK-V6M-DEFAULTCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-DEFAULTCXX-SAME: "-o" "{{.*}}.o" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: -stdlib=libc++ \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBCXX %s // CHECK-V6M-LIBCXX-NOT: "-internal-isystem" "{{[^"]+}}/include/c++/{{[^v].*}}" // CHECK-V6M-LIBCXX: "-internal-isystem" "{{[^"]+}}/include/c++/v1" // CHECK-V6M-LIBCXX: "[[PREFIX_DIR:.*]]/bin/ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-LIBCXX-SAME: "-L[[PREFIX_DIR]]/lib/clang/{{.*}}/lib/baremetal" // CHECK-V6M-LIBCXX-SAME: "-lc++" "-lc++abi" "-lunwind" // CHECK-V6M-LIBCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-LIBCXX-SAME: "-o" "{{.*}}.o" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: -stdlib=libstdc++ \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBSTDCXX %s // CHECK-V6M-LIBSTDCXX-NOT: "-internal-isystem" "{{[^"]+}}/include/c++/v1" // CHECK-V6M-LIBSTDCXX: "-internal-isystem" "{{[^"]+}}/include/c++/6.0.0" // CHECK-V6M-LIBSTDCXX: "[[PREFIX_DIR:.*]]/bin/ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-LIBSTDCXX-SAME: "-L[[PREFIX_DIR]]/lib/clang/{{.*}}/lib/baremetal" // CHECK-V6M-LIBSTDCXX-SAME: "-lstdc++" "-lsupc++" "-lunwind" // CHECK-V6M-LIBSTDCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-LIBSTDCXX-SAME: "-o" "{{.*}}.o" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: -nodefaultlibs \ // RUN: | FileCheck --check-prefix=CHECK-V6M-NDL %s // CHECK-V6M-NDL: "[[PREFIX_DIR:.*]]/bin/ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-NDL-SAME: "-L[[PREFIX_DIR]]/lib/clang/{{.*}}/lib/baremetal" "-o" "{{.*}}.o" // RUN: %clangxx -target arm-none-eabi -v 2>&1 \ // RUN: | FileCheck %s --check-prefix=CHECK-THREAD-MODEL // CHECK-THREAD-MODEL: Thread model: single <commit_msg>Relax testcase to appease buildbots<commit_after>// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: -T semihosted.lds \ // RUN: -L some/directory/user/asked/for \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-C %s // CHECK-V6M-C: "[[PREFIX_DIR:.*]]/bin/clang" "-cc1" "-triple" "thumbv6m-none--eabi" // CHECK-V6M-C-SAME: "-resource-dir" "[[PREFIX_DIR]]/lib/clang/[[VERSION:[^"]*]]" // CHECK-V6M-C-SAME: "-isysroot" "[[SYSROOT:[^"]*]]" // CHECK-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]/include/c++/v1" // CHECk-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]/include" // CHECK-V6M-C-SAME: "-x" "c++" "{{.*}}baremetal.cpp" // CHECK-V6M-C-NEXT: "{{[^"]*}}ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-C-SAME: "-L[[PREFIX_DIR]]/lib/clang/[[VERSION]]/lib/baremetal" // CHECK-V6M-C-SAME: "-T" "semihosted.lds" "-Lsome/directory/user/asked/for" // CHECK-V6M-C-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-C-SAME: "-o" "{{.*}}.o" // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: -nostdlibinc -nobuiltininc \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBINC %s // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: -nostdinc \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBINC %s // CHECK-V6M-LIBINC-NOT: "-internal-isystem" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-DEFAULTCXX %s // CHECK-V6M-DEFAULTCXX: "{{[^"]*}}ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-DEFAULTCXX-SAME: "-L{{[^"]*}}/lib/clang/{{.*}}/lib/baremetal" // CHECK-V6M-DEFAULTCXX-SAME: "-lc++" "-lc++abi" "-lunwind" // CHECK-V6M-DEFAULTCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-DEFAULTCXX-SAME: "-o" "{{.*}}.o" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: -stdlib=libc++ \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBCXX %s // CHECK-V6M-LIBCXX-NOT: "-internal-isystem" "{{[^"]+}}/include/c++/{{[^v].*}}" // CHECK-V6M-LIBCXX: "-internal-isystem" "{{[^"]+}}/include/c++/v1" // CHECK-V6M-LIBCXX: "{{[^"]*}}ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-LIBCXX-SAME: "-L{{[^"]*}}/lib/clang/{{.*}}/lib/baremetal" // CHECK-V6M-LIBCXX-SAME: "-lc++" "-lc++abi" "-lunwind" // CHECK-V6M-LIBCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-LIBCXX-SAME: "-o" "{{.*}}.o" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: -stdlib=libstdc++ \ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBSTDCXX %s // CHECK-V6M-LIBSTDCXX-NOT: "-internal-isystem" "{{[^"]+}}/include/c++/v1" // CHECK-V6M-LIBSTDCXX: "-internal-isystem" "{{[^"]+}}/include/c++/6.0.0" // CHECK-V6M-LIBSTDCXX: "{{[^"]*}}ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-LIBSTDCXX-SAME: "-L{{[^"]*}}/lib/clang/{{.*}}/lib/baremetal" // CHECK-V6M-LIBSTDCXX-SAME: "-lstdc++" "-lsupc++" "-lunwind" // CHECK-V6M-LIBSTDCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" // CHECK-V6M-LIBSTDCXX-SAME: "-o" "{{.*}}.o" // RUN: %clangxx -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: -nodefaultlibs \ // RUN: | FileCheck --check-prefix=CHECK-V6M-NDL %s // CHECK-V6M-NDL: "{{[^"]*}}ld.lld" "{{.*}}.o" "-Bstatic" // CHECK-V6M-NDL-SAME: "-L{{[^"]*}}/lib/clang/{{.*}}/lib/baremetal" "-o" "{{.*}}.o" // RUN: %clangxx -target arm-none-eabi -v 2>&1 \ // RUN: | FileCheck %s --check-prefix=CHECK-THREAD-MODEL // CHECK-THREAD-MODEL: Thread model: single <|endoftext|>
<commit_before>// // Copyright (c) 2015, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include <boost/test/unit_test.hpp> #include <envire_smurf/GraphLoader.hpp> #include <envire_core/graph/EnvireGraph.hpp> #include <envire_core/graph/GraphDrawing.hpp> #include <envire_core/items/Item.hpp> #include <smurf/Robot.hpp> BOOST_AUTO_TEST_CASE(constructor_Test) { std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::smurf::GraphLoader graphLoader(transformGraph); } BOOST_AUTO_TEST_CASE(loadStructure_noPos) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::smurf::GraphLoader graphLoader(transformGraph); graphLoader.loadStructure(*robot); envire::core::GraphDrawing::writeSVG(*transformGraph, "loadStructure_noPos_Test.svg"); } BOOST_AUTO_TEST_CASE(loadStructure_withPos) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::core::Transform iniPose; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; envire::smurf::GraphLoader graphLoader(transformGraph, iniPose); envire::core::FrameId center = "center"; transformGraph->addFrame(center); graphLoader.loadStructure(transformGraph->getVertex(center), (*robot)); envire::core::GraphDrawing::writeSVG(*transformGraph, "loadStructure_withPos_Test.svg"); } BOOST_AUTO_TEST_CASE(loadStructre_withDynamicJoint) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_dynamic_joint.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::core::Transform iniPose; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; envire::smurf::GraphLoader graphLoader(transformGraph, iniPose); envire::core::FrameId center = "center"; transformGraph->addFrame(center); graphLoader.loadStructure(transformGraph->getVertex(center), (*robot)); envire::core::GraphDrawing::writeSVG(*transformGraph, "loadStructure_withDynamicJoint_test.svg"); } envire::smurf::GraphLoader getLoaderWithStructuredGraph(const smurf::Robot & robot) { envire::core::Transform iniPose; std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; envire::smurf::GraphLoader graphLoader(transformGraph, iniPose); envire::core::FrameId center = "center"; transformGraph->addFrame(center); graphLoader.loadStructure(transformGraph->getVertex(center), robot); return graphLoader; } BOOST_AUTO_TEST_CASE(loadFrames) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; std::cout << "Initial Group ID: " << nextGroupId << std::endl; graphLoader.loadFrames(nextGroupId, *robot); std::cout << "Final Group ID: "<< nextGroupId << std::endl; envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadFrames_Test.svg"); } BOOST_AUTO_TEST_CASE(loadFrames_withDynamicJoint) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_dynamic_joint.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadFrames_withDynamicJoint_Test.svg"); } BOOST_AUTO_TEST_CASE(loadFixedJoints) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadFixedJoints(*robot); //NOTE Fixed joints are loaded in the source frame envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadFixedJoints_Test.svg"); } BOOST_AUTO_TEST_CASE(loadCollidables) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); std::cout << "An error message should appear because the Frames where not loaded " << path << std::endl; graphLoader.loadCollidables(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadCollidables(*robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadCollidables_Test.svg"); } BOOST_AUTO_TEST_CASE(loadInertials) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); std::cout << "An error message should appear because the Frames where not loaded " << path << std::endl; graphLoader.loadInertials(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadInertials(*robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadInertials_Test.svg"); } BOOST_AUTO_TEST_CASE(loadInertialsAndCollidables) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadCollidables(*robot); graphLoader.loadInertials(*robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadInertialsAndCollidables_Test.svg"); } BOOST_AUTO_TEST_CASE(loadVisuals) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadVisuals(*robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadVisuals_Test.svg"); } BOOST_AUTO_TEST_CASE(loadDynamicJoints) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_dynamic_joint.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadDynamicJoints(*robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadDynamicJoints_Test.svg"); } BOOST_AUTO_TEST_CASE(loadMotors) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_with_motor.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadDynamicJoints(*robot); graphLoader.loadMotors(*robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadMotors_Test.svg"); } BOOST_AUTO_TEST_CASE(loadSensors) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_with_sensor.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadSensors(*robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadSensors_Test.svg"); } BOOST_AUTO_TEST_CASE(loadRobot) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_with_motor.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::core::Transform iniPose; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; std::shared_ptr<envire::core::EnvireGraph> targetGraph(new envire::core::EnvireGraph) ; envire::smurf::GraphLoader graphLoader(targetGraph); envire::core::FrameId center = "center"; targetGraph->addFrame(center); int nextGroupId = 0; graphLoader.loadRobot(nextGroupId, targetGraph->getVertex(center), iniPose, *robot); envire::core::GraphDrawing::writeSVG(*(graphLoader.getGraph()), "loadRobot_Test.svg"); }<commit_msg>adapt to new interface<commit_after>// // Copyright (c) 2015, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include <boost/test/unit_test.hpp> #include <envire_smurf/GraphLoader.hpp> #include <envire_core/graph/EnvireGraph.hpp> #include <envire_core/graph/GraphDrawing.hpp> #include <envire_core/items/Item.hpp> #include <smurf/Robot.hpp> BOOST_AUTO_TEST_CASE(constructor_Test) { std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::smurf::GraphLoader graphLoader(transformGraph); } BOOST_AUTO_TEST_CASE(loadStructure_noPos) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::smurf::GraphLoader graphLoader(transformGraph); graphLoader.loadStructure(*robot); envire::core::GraphDrawing::write(*transformGraph, "loadStructure_noPos_Test.dot"); } BOOST_AUTO_TEST_CASE(loadStructure_withPos) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::core::Transform iniPose; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; envire::smurf::GraphLoader graphLoader(transformGraph, iniPose); envire::core::FrameId center = "center"; transformGraph->addFrame(center); graphLoader.loadStructure(transformGraph->getVertex(center), (*robot)); envire::core::GraphDrawing::write(*transformGraph, "loadStructure_withPos_Test.dot"); } BOOST_AUTO_TEST_CASE(loadStructre_withDynamicJoint) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_dynamic_joint.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; envire::core::Transform iniPose; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; envire::smurf::GraphLoader graphLoader(transformGraph, iniPose); envire::core::FrameId center = "center"; transformGraph->addFrame(center); graphLoader.loadStructure(transformGraph->getVertex(center), (*robot)); envire::core::GraphDrawing::write(*transformGraph, "loadStructure_withDynamicJoint_test.dot"); } envire::smurf::GraphLoader getLoaderWithStructuredGraph(const smurf::Robot & robot) { envire::core::Transform iniPose; std::shared_ptr<envire::core::EnvireGraph> transformGraph(new envire::core::EnvireGraph) ; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; envire::smurf::GraphLoader graphLoader(transformGraph, iniPose); envire::core::FrameId center = "center"; transformGraph->addFrame(center); graphLoader.loadStructure(transformGraph->getVertex(center), robot); return graphLoader; } BOOST_AUTO_TEST_CASE(loadFrames) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; std::cout << "Initial Group ID: " << nextGroupId << std::endl; graphLoader.loadFrames(nextGroupId, *robot); std::cout << "Final Group ID: "<< nextGroupId << std::endl; envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadFrames_Test.dot"); } BOOST_AUTO_TEST_CASE(loadFrames_withDynamicJoint) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_dynamic_joint.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadFrames_withDynamicJoint_Test.dot"); } BOOST_AUTO_TEST_CASE(loadFixedJoints) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadFixedJoints(*robot); //NOTE Fixed joints are loaded in the source frame envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadFixedJoints_Test.dot"); } BOOST_AUTO_TEST_CASE(loadCollidables) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); std::cout << "An error message should appear because the Frames where not loaded " << path << std::endl; graphLoader.loadCollidables(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadCollidables(*robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadCollidables_Test.dot"); } BOOST_AUTO_TEST_CASE(loadInertials) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); std::cout << "An error message should appear because the Frames where not loaded " << path << std::endl; graphLoader.loadInertials(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadInertials(*robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadInertials_Test.dot"); } BOOST_AUTO_TEST_CASE(loadInertialsAndCollidables) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadCollidables(*robot); graphLoader.loadInertials(*robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadInertialsAndCollidables_Test.dot"); } BOOST_AUTO_TEST_CASE(loadVisuals) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); int nextGroupId = 0; graphLoader.loadFrames(nextGroupId, *robot); graphLoader.loadVisuals(*robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadVisuals_Test.dot"); } BOOST_AUTO_TEST_CASE(loadDynamicJoints) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_dynamic_joint.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadDynamicJoints(*robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadDynamicJoints_Test.dot"); } BOOST_AUTO_TEST_CASE(loadMotors) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_with_motor.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadDynamicJoints(*robot); graphLoader.loadMotors(*robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadMotors_Test.dot"); } BOOST_AUTO_TEST_CASE(loadSensors) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_with_sensor.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::smurf::GraphLoader graphLoader = getLoaderWithStructuredGraph(*robot); graphLoader.loadSensors(*robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadSensors_Test.dot"); } BOOST_AUTO_TEST_CASE(loadRobot) { const std::string path="./sample_smurfs/two_boxes_joined/smurf/two_boxes_with_motor.smurf"; smurf::Robot* robot = new(smurf::Robot); robot->loadFromSmurf(path); envire::core::Transform iniPose; iniPose.transform.orientation = base::Quaterniond::Identity(); iniPose.transform.translation << 1.0, 1.0, 1.0; std::shared_ptr<envire::core::EnvireGraph> targetGraph(new envire::core::EnvireGraph) ; envire::smurf::GraphLoader graphLoader(targetGraph); envire::core::FrameId center = "center"; targetGraph->addFrame(center); int nextGroupId = 0; graphLoader.loadRobot(nextGroupId, targetGraph->getVertex(center), iniPose, *robot); envire::core::GraphDrawing::write(*(graphLoader.getGraph()), "loadRobot_Test.dot"); }<|endoftext|>
<commit_before>//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a JITEventListener object that calls into OProfile to tell // it about JITted functions. For now, we only record function names and sizes, // but eventually we'll also record line number information. // // See http://oprofile.sourceforge.net/doc/devel/jit-interface.html for the // definition of the interface we're using. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "oprofile-jit-event-listener" #include "llvm/Function.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Errno.h" #include "llvm/Config/config.h" #include <stddef.h> using namespace llvm; #if USE_OPROFILE #include <opagent.h> namespace { class OProfileJITEventListener : public JITEventListener { op_agent_t Agent; public: OProfileJITEventListener(); ~OProfileJITEventListener(); virtual void NotifyFunctionEmitted(const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details); virtual void NotifyFreeingMachineCode(const Function &F, void *OldPtr); }; OProfileJITEventListener::OProfileJITEventListener() : Agent(op_open_agent()) { if (Agent == NULL) { const std::string err_str = sys::StrError(); DEBUG(errs() << "Failed to connect to OProfile agent: " << err_str << "\n"); } else { DEBUG(errs() << "Connected to OProfile agent.\n"); } } OProfileJITEventListener::~OProfileJITEventListener() { if (Agent != NULL) { if (op_close_agent(Agent) == -1) { const std::string err_str = sys::StrError(); DEBUG(errs() << "Failed to disconnect from OProfile agent: " << err_str << "\n"); } else { DEBUG(errs() << "Disconnected from OProfile agent.\n"); } } } class FilenameCache { // Holds the filename of each CompileUnit, so that we can pass the // pointer into oprofile. These char*s are freed in the destructor. DenseMap<MDNode*, char*> Filenames; public: const char *getFilename(MDNode *CompileUnit) { char *&Filename = Filenames[CompileUnit]; if (Filename == NULL) { DICompileUnit CU(CompileUnit); Filename = strdup(CU.getFilename()); } return Filename; } ~FilenameCache() { for (DenseMap<MDNode*, char*>::iterator I = Filenames.begin(), E = Filenames.end(); I != E; ++I) { free(I->second); } } }; static debug_line_info LineStartToOProfileFormat( const MachineFunction &MF, FilenameCache &Filenames, uintptr_t Address, DebugLoc Loc) { debug_line_info Result; Result.vma = Address; const DebugLocTuple &tuple = MF.getDebugLocTuple(Loc); Result.lineno = tuple.Line; Result.filename = Filenames.getFilename(tuple.CompileUnit); DEBUG(errs() << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to " << Result.filename << ":" << Result.lineno << "\n"); return Result; } // Adds the just-emitted function to the symbol table. void OProfileJITEventListener::NotifyFunctionEmitted( const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details) { assert(F.hasName() && FnStart != 0 && "Bad symbol to add"); if (op_write_native_code(Agent, F.getName().data(), reinterpret_cast<uint64_t>(FnStart), FnStart, FnSize) == -1) { DEBUG(errs() << "Failed to tell OProfile about native function " << F.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); return; } // Now we convert the line number information from the address/DebugLoc format // in Details to the address/filename/lineno format that OProfile expects. // OProfile 0.9.4 (and maybe later versions) has a bug that causes it to // ignore line numbers for addresses above 4G. FilenameCache Filenames; std::vector<debug_line_info> LineInfo; LineInfo.reserve(1 + Details.LineStarts.size()); if (!Details.MF->getDefaultDebugLoc().isUnknown()) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, reinterpret_cast<uintptr_t>(FnStart), Details.MF->getDefaultDebugLoc())); } for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator I = Details.LineStarts.begin(), E = Details.LineStarts.end(); I != E; ++I) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, I->Address, I->Loc)); } if (!LineInfo.empty()) { if (op_write_debug_line_info(Agent, FnStart, LineInfo.size(), &*LineInfo.begin()) == -1) { DEBUG(errs() << "Failed to tell OProfile about line numbers for native function " << F.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); } } } // Removes the to-be-deleted function from the symbol table. void OProfileJITEventListener::NotifyFreeingMachineCode( const Function &F, void *FnStart) { assert(FnStart && "Invalid function pointer"); if (op_unload_native_code(Agent, reinterpret_cast<uint64_t>(FnStart)) == -1) { DEBUG(errs() << "Failed to tell OProfile about unload of native function " << F.getName() << " at " << FnStart << "\n"); } } } // anonymous namespace. namespace llvm { JITEventListener *createOProfileJITEventListener() { return new OProfileJITEventListener; } } #else // USE_OPROFILE namespace llvm { // By defining this to return NULL, we can let clients call it unconditionally, // even if they haven't configured with the OProfile libraries. JITEventListener *createOProfileJITEventListener() { return NULL; } } // namespace llvm #endif // USE_OPROFILE <commit_msg>Fix OProfileJITEventListener after r84054 renamed CompileUnit to Scope.<commit_after>//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a JITEventListener object that calls into OProfile to tell // it about JITted functions. For now, we only record function names and sizes, // but eventually we'll also record line number information. // // See http://oprofile.sourceforge.net/doc/devel/jit-interface.html for the // definition of the interface we're using. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "oprofile-jit-event-listener" #include "llvm/Function.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Errno.h" #include "llvm/Config/config.h" #include <stddef.h> using namespace llvm; #if USE_OPROFILE #include <opagent.h> namespace { class OProfileJITEventListener : public JITEventListener { op_agent_t Agent; public: OProfileJITEventListener(); ~OProfileJITEventListener(); virtual void NotifyFunctionEmitted(const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details); virtual void NotifyFreeingMachineCode(const Function &F, void *OldPtr); }; OProfileJITEventListener::OProfileJITEventListener() : Agent(op_open_agent()) { if (Agent == NULL) { const std::string err_str = sys::StrError(); DEBUG(errs() << "Failed to connect to OProfile agent: " << err_str << "\n"); } else { DEBUG(errs() << "Connected to OProfile agent.\n"); } } OProfileJITEventListener::~OProfileJITEventListener() { if (Agent != NULL) { if (op_close_agent(Agent) == -1) { const std::string err_str = sys::StrError(); DEBUG(errs() << "Failed to disconnect from OProfile agent: " << err_str << "\n"); } else { DEBUG(errs() << "Disconnected from OProfile agent.\n"); } } } class FilenameCache { // Holds the filename of each Scope, so that we can pass the // pointer into oprofile. These char*s are freed in the destructor. DenseMap<MDNode*, char*> Filenames; public: const char *getFilename(MDNode *Scope) { char *&Filename = Filenames[Scope]; if (Filename == NULL) { DIScope S(Scope); Filename = strdup(S.getFilename()); } return Filename; } ~FilenameCache() { for (DenseMap<MDNode*, char*>::iterator I = Filenames.begin(), E = Filenames.end(); I != E; ++I) { free(I->second); } } }; static debug_line_info LineStartToOProfileFormat( const MachineFunction &MF, FilenameCache &Filenames, uintptr_t Address, DebugLoc Loc) { debug_line_info Result; Result.vma = Address; const DebugLocTuple &tuple = MF.getDebugLocTuple(Loc); Result.lineno = tuple.Line; Result.filename = Filenames.getFilename(tuple.Scope); DEBUG(errs() << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to " << Result.filename << ":" << Result.lineno << "\n"); return Result; } // Adds the just-emitted function to the symbol table. void OProfileJITEventListener::NotifyFunctionEmitted( const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details) { assert(F.hasName() && FnStart != 0 && "Bad symbol to add"); if (op_write_native_code(Agent, F.getName().data(), reinterpret_cast<uint64_t>(FnStart), FnStart, FnSize) == -1) { DEBUG(errs() << "Failed to tell OProfile about native function " << F.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); return; } // Now we convert the line number information from the address/DebugLoc format // in Details to the address/filename/lineno format that OProfile expects. // OProfile 0.9.4 (and maybe later versions) has a bug that causes it to // ignore line numbers for addresses above 4G. FilenameCache Filenames; std::vector<debug_line_info> LineInfo; LineInfo.reserve(1 + Details.LineStarts.size()); if (!Details.MF->getDefaultDebugLoc().isUnknown()) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, reinterpret_cast<uintptr_t>(FnStart), Details.MF->getDefaultDebugLoc())); } for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator I = Details.LineStarts.begin(), E = Details.LineStarts.end(); I != E; ++I) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, I->Address, I->Loc)); } if (!LineInfo.empty()) { if (op_write_debug_line_info(Agent, FnStart, LineInfo.size(), &*LineInfo.begin()) == -1) { DEBUG(errs() << "Failed to tell OProfile about line numbers for native function " << F.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); } } } // Removes the to-be-deleted function from the symbol table. void OProfileJITEventListener::NotifyFreeingMachineCode( const Function &F, void *FnStart) { assert(FnStart && "Invalid function pointer"); if (op_unload_native_code(Agent, reinterpret_cast<uint64_t>(FnStart)) == -1) { DEBUG(errs() << "Failed to tell OProfile about unload of native function " << F.getName() << " at " << FnStart << "\n"); } } } // anonymous namespace. namespace llvm { JITEventListener *createOProfileJITEventListener() { return new OProfileJITEventListener; } } #else // USE_OPROFILE namespace llvm { // By defining this to return NULL, we can let clients call it unconditionally, // even if they haven't configured with the OProfile libraries. JITEventListener *createOProfileJITEventListener() { return NULL; } } // namespace llvm #endif // USE_OPROFILE <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2014 Micah C Chambers (micahc.vt@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file opt.cpp Contains implementation for base optimizer * *****************************************************************************/ #include "opt.h" #include <iostream> #include <iomanip> namespace npl { /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param valgradfunc * Function which computes the both the energy and * gradient in the underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const ValGradFunc& valgradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0.00001; stop_X = 0; stop_F = 0; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = valgradfunc; m_callback = callback; }; /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0.00001; stop_X = 0; stop_F = 0; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = [&](const VectorXd& x, double& value, VectorXd& grad) -> int { return !(valfunc(x, value)==0 && gradfunc(x, grad)==0); }; m_callback = callback; }; std::string Optimizer::explainStop(StopReason r) { switch(r) { case ENDGRAD: return "Optimizer stopped due to gradient below threshold."; case ENDSTEP: return "Optimizer stopped due to step size below threshold."; case ENDVALUE: return "Optimizer stopped due to change in value below threshold."; case ENDITERS: return "Optimizer stopped due to number iterations."; case ENDFAIL: return "Optimizer due to failure of callback functions."; } return "Unknown stop condition!"; } /** * @brief Tests a gradient function using the value function. * * @param error Error between analytical and numeric gradient * @param x Position to test * @param stepsize Step to take when testing gradient (will be taken in each * dimension successively) * @param tol Tolerance, error below the tolerance will cause the * function to return 0, higher error will cause the function to return -1 * @param valfunc Function values compute * @param gradfunc Function gradient compute * * @return */ int testgrad(double& error, const VectorXd& x, double stepsize, double tol, const ValFunc& valfunc, const GradFunc& gradfunc) { //#ifndef NDEBUG size_t wid = 10; std::cerr << "Testing Gradient" << std::endl; std::cerr << std::setw(wid) << "Dim" << std::setw(wid) << "Analytic" << std::setw(wid) << "Numeric" << std::endl; //#endif //NDEBUG VectorXd g(x.rows()); if(gradfunc(x, g) != 0) return -1; double v = 0; double center = 0; if(valfunc(x, center) != 0) return -1; VectorXd step = VectorXd::Zero(x.rows()); VectorXd gbrute(x.rows()); for(size_t dd=0; dd<x.rows(); dd++) { step[dd] = stepsize; if(valfunc(x+step, v) != 0) return -1; step[dd] = 0; gbrute[dd] = (v-center)/stepsize; //#ifndef NDEBUG std::cerr << std::setw(wid) << dd << std::setw(wid) << g[dd] << std::setw(wid) << gbrute[dd] << std::endl; //#endif //NDEBUG } error = (gbrute - g).norm(); if(error > tol) return -2; return 0; } /** * @brief The number of calls to the Generalized Rosenbrock Gradient Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_G_calls = 0; /** * @brief The number of calls to the Generalized Rosenbrock Value Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_V_calls = 0; /** * @brief Returns the number of times the Value and Gradient functions for the * Generalized Rosenbrock Function were called. * * @param vcalls Value calls * @param gcalls Gradient calls */ void gRosenbrock_callCounts(size_t& vcalls, size_t& gcalls) { gcalls = gRosenbrock_G_calls; vcalls = gRosenbrock_V_calls; } /** * @brief Implements generized rosenbrock value * * @param x Position vector * @param v values * * @return */ int gRosenbrock_V(const VectorXd& x, double& v) { gRosenbrock_V_calls++;; v = 0; for(size_t ii=0; ii<x.rows()-1; ii++) v += pow(x[ii]-1,2)+100*pow(x[ii+1]-x[ii]*x[ii], 2); // i=N-1 size_t ii=x.rows()-1; v += pow(x[ii]-1,2)+100*pow(-x[ii]*x[ii], 2); return 0; } /** * @brief Implements generized rosenbrock gradient * * @param x Position vector * @param gradient Gradient at the position * * @return */ int gRosenbrock_G(const VectorXd& x, VectorXd& gradient) { gRosenbrock_G_calls++;; // gradient.resize(x.rows()); for(size_t ii=1; ii<x.rows()-1; ii++) gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); // boundaries size_t ii=0; gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]; ii=x.rows()-1; gradient[ii] = 2*(x[ii]-1)-400*(-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); return 0; } } <commit_msg>Increased width of Gradient test fields<commit_after>/****************************************************************************** * Copyright 2014 Micah C Chambers (micahc.vt@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file opt.cpp Contains implementation for base optimizer * *****************************************************************************/ #include "opt.h" #include <iostream> #include <iomanip> namespace npl { /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param valgradfunc * Function which computes the both the energy and * gradient in the underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const ValGradFunc& valgradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0.00001; stop_X = 0; stop_F = 0; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = valgradfunc; m_callback = callback; }; /** * @brief Constructor for optimizer function. * * @param dim Dimensionality of state vector * @param valfunc Function which computes the energy of the underlying * mathematical function * @param gradfunc Function which computes the gradient of energy in the * underlying mathematical function * @param callback Function which should be called at the end of each * iteration (for instance, to debug) */ Optimizer::Optimizer(size_t dim, const ValFunc& valfunc, const GradFunc& gradfunc, const CallBackFunc& callback) : state_x(dim) { stop_G = 0.00001; stop_X = 0; stop_F = 0; stop_Its = -1; m_compF = valfunc; m_compG = gradfunc; m_compFG = [&](const VectorXd& x, double& value, VectorXd& grad) -> int { return !(valfunc(x, value)==0 && gradfunc(x, grad)==0); }; m_callback = callback; }; std::string Optimizer::explainStop(StopReason r) { switch(r) { case ENDGRAD: return "Optimizer stopped due to gradient below threshold."; case ENDSTEP: return "Optimizer stopped due to step size below threshold."; case ENDVALUE: return "Optimizer stopped due to change in value below threshold."; case ENDITERS: return "Optimizer stopped due to number iterations."; case ENDFAIL: return "Optimizer due to failure of callback functions."; } return "Unknown stop condition!"; } /** * @brief Tests a gradient function using the value function. * * @param error Error between analytical and numeric gradient * @param x Position to test * @param stepsize Step to take when testing gradient (will be taken in each * dimension successively) * @param tol Tolerance, error below the tolerance will cause the * function to return 0, higher error will cause the function to return -1 * @param valfunc Function values compute * @param gradfunc Function gradient compute * * @return */ int testgrad(double& error, const VectorXd& x, double stepsize, double tol, const ValFunc& valfunc, const GradFunc& gradfunc) { //#ifndef NDEBUG size_t wid = 18; std::cerr << "Testing Gradient" << std::endl; std::cerr << std::setw(wid) << "Dim" << std::setw(wid) << "Analytic" << std::setw(wid) << "Numeric" << std::endl; //#endif //NDEBUG VectorXd g(x.rows()); if(gradfunc(x, g) != 0) return -1; double v = 0; double center = 0; if(valfunc(x, center) != 0) return -1; VectorXd step = VectorXd::Zero(x.rows()); VectorXd gbrute(x.rows()); for(size_t dd=0; dd<x.rows(); dd++) { step[dd] = stepsize; if(valfunc(x+step, v) != 0) return -1; step[dd] = 0; gbrute[dd] = (v-center)/stepsize; //#ifndef NDEBUG std::cerr << std::setw(wid) << dd << std::setw(wid) << g[dd] << std::setw(wid) << gbrute[dd] << std::endl; //#endif //NDEBUG } error = (gbrute - g).norm(); if(error > tol) return -2; return 0; } /** * @brief The number of calls to the Generalized Rosenbrock Gradient Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_G_calls = 0; /** * @brief The number of calls to the Generalized Rosenbrock Value Function. * This is only for benchmarking purposes, and is not thread safe. */ static size_t gRosenbrock_V_calls = 0; /** * @brief Returns the number of times the Value and Gradient functions for the * Generalized Rosenbrock Function were called. * * @param vcalls Value calls * @param gcalls Gradient calls */ void gRosenbrock_callCounts(size_t& vcalls, size_t& gcalls) { gcalls = gRosenbrock_G_calls; vcalls = gRosenbrock_V_calls; } /** * @brief Implements generized rosenbrock value * * @param x Position vector * @param v values * * @return */ int gRosenbrock_V(const VectorXd& x, double& v) { gRosenbrock_V_calls++;; v = 0; for(size_t ii=0; ii<x.rows()-1; ii++) v += pow(x[ii]-1,2)+100*pow(x[ii+1]-x[ii]*x[ii], 2); // i=N-1 size_t ii=x.rows()-1; v += pow(x[ii]-1,2)+100*pow(-x[ii]*x[ii], 2); return 0; } /** * @brief Implements generized rosenbrock gradient * * @param x Position vector * @param gradient Gradient at the position * * @return */ int gRosenbrock_G(const VectorXd& x, VectorXd& gradient) { gRosenbrock_G_calls++;; // gradient.resize(x.rows()); for(size_t ii=1; ii<x.rows()-1; ii++) gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); // boundaries size_t ii=0; gradient[ii] = 2*(x[ii]-1)-400*(x[ii+1]-x[ii]*x[ii])*x[ii]; ii=x.rows()-1; gradient[ii] = 2*(x[ii]-1)-400*(-x[ii]*x[ii])*x[ii]+ 200*(x[ii]-x[ii-1]*x[ii-1]); return 0; } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "ValuePrinterSynthesizer.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/ExprCXX.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/Sema.h" #include "llvm/Support/raw_os_ostream.h" #include <iostream> using namespace clang; namespace cling { ValuePrinterSynthesizer::ValuePrinterSynthesizer(clang::Sema* S, llvm::raw_ostream* Stream) : TransactionTransformer(S), m_Context(&S->getASTContext()) { if (Stream) m_ValuePrinterStream.reset(Stream); else m_ValuePrinterStream.reset(new llvm::raw_os_ostream(std::cout)); } // pin the vtable here. ValuePrinterSynthesizer::~ValuePrinterSynthesizer() { } void ValuePrinterSynthesizer::Transform() { if (!getTransaction()->getCompilationOpts().ValuePrinting) return; for (Transaction::const_iterator I = getTransaction()->decls_begin(), E = getTransaction()->decls_end(); I != E; ++I) if(!tryAttachVP(*I)) return setTransaction(0); // On error set the to NULL. } bool ValuePrinterSynthesizer::tryAttachVP(DeclGroupRef DGR) { for (DeclGroupRef::iterator I = DGR.begin(), E = DGR.end(); I != E; ++I) if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I)) { if (FD->getNameAsString().find("__cling_Un1Qu3")) return true; if (CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody())) { for (CompoundStmt::body_iterator J = CS->body_begin(), E = CS->body_end(); J != E; ++J) { if (J+1 == E || !isa<NullStmt>(*(J+1))) { Expr* To = 0; ReturnStmt* RS = dyn_cast<ReturnStmt>(*J); if (RS) To = RS->getRetValue(); else To = dyn_cast<Expr>(*J); if (To) { Expr* Result = 0; if (m_Sema->getLangOpts().CPlusPlus) Result = SynthesizeCppVP(To); else Result = SynthesizeVP(To); if (Result) { if (RS) RS->setRetValue(Result); else *J = Result; } } } } // Clear the artificial NullStmt-s if (!ClearNullStmts(CS)) { // if no body remove the wrapper DeclContext* DC = FD->getDeclContext(); Scope* S = m_Sema->getScopeForContext(DC); if (S) S->RemoveDecl(FD); DC->removeDecl(FD); } } } return true; } // We need to artificially create: // cling::valuePrinterInternal::PrintValue((void*) raw_ostream, // (ASTContext)Ctx, (Expr*)E, &i); Expr* ValuePrinterSynthesizer::SynthesizeCppVP(Expr* E) { QualType QT = E->getType(); // For now we skip void and function pointer types. if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType())) return 0; // 1. Call gCling->getValuePrinterStream() // 1.1. Find gCling SourceLocation NoSLoc = SourceLocation(); NamespaceDecl* NSD = utils::Lookup::Namespace(m_Sema, "cling"); NSD = utils::Lookup::Namespace(m_Sema, "valuePrinterInternal", NSD); DeclarationName PVName = &m_Context->Idents.get("PrintValue"); LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, NSD); assert(!R.empty() && "Cannot find PrintValue(...)"); CXXScopeSpec CSS; Expr* UnresolvedLookup = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); // 2.4. Prepare the params // 2.4.1 Lookup the llvm::raw_ostream CXXRecordDecl* RawOStreamRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "raw_ostream", utils::Lookup::Namespace(m_Sema, "llvm"))); assert(RawOStreamRD && "Declaration of the expr not found!"); QualType RawOStreamRDTy = m_Context->getTypeDeclType(RawOStreamRD); // 2.4.2 Lookup the expr type CXXRecordDecl* ExprRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr", utils::Lookup::Namespace(m_Sema, "clang"))); assert(ExprRD && "Declaration of the expr not found!"); QualType ExprRDTy = m_Context->getTypeDeclType(ExprRD); // 2.4.3 Lookup ASTContext type CXXRecordDecl* ASTContextRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "ASTContext", utils::Lookup::Namespace(m_Sema, "clang"))); assert(ASTContextRD && "Declaration of the expr not found!"); QualType ASTContextRDTy = m_Context->getTypeDeclType(ASTContextRD); Expr* RawOStreamTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, RawOStreamRDTy, (uint64_t)m_ValuePrinterStream.get() ); Expr* ExprTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)E); Expr* ASTContextTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ASTContextRDTy, (uint64_t)m_Context); // E might contain temporaries. This means that the topmost expr is // ExprWithCleanups. This contains the information about the temporaries and // signals when they should be destroyed. // Here we replace E with call to value printer and we must extend the life // time of those temporaries to the end of the new CallExpr. bool NeedsCleanup = false; if (ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(E)) { E = EWC->getSubExpr(); NeedsCleanup = true; } llvm::SmallVector<Expr*, 4> CallArgs; CallArgs.push_back(RawOStreamTy); CallArgs.push_back(ExprTy); CallArgs.push_back(ASTContextTy); CallArgs.push_back(E); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc, CallArgs, NoSLoc).take(); Result = m_Sema->ActOnFinishFullExpr(Result).take(); if (NeedsCleanup && !isa<ExprWithCleanups>(Result)) { llvm::ArrayRef<ExprWithCleanups::CleanupObject> Cleanups; ExprWithCleanups* EWC = ExprWithCleanups::Create(*m_Context, Result, Cleanups); Result = EWC; } assert(Result && "Cannot create value printer!"); return Result; } // We need to artificially create: // cling_PrintValue(void* (ASTContext)C, void* (Expr)E, const void* (&i) Expr* ValuePrinterSynthesizer::SynthesizeVP(Expr* E) { QualType QT = E->getType(); // For now we skip void and function pointer types. if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType())) return 0; // Find cling_PrintValue SourceLocation NoSLoc = SourceLocation(); DeclarationName PVName = &m_Context->Idents.get("cling_PrintValue"); LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); m_Sema->LookupName(R, S); assert(!R.empty() && "Cannot find PrintValue(...)"); CXXScopeSpec CSS; Expr* UnresolvedLookup = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); Expr* VoidEArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, (uint64_t)E); Expr* VoidCArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, (uint64_t)m_Context); if (!QT->isPointerType()) { while(ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E)) E = ICE->getSubExpr(); E = m_Sema->BuildUnaryOp(S, NoSLoc, UO_AddrOf, E).take(); } llvm::SmallVector<Expr*, 4> CallArgs; CallArgs.push_back(VoidEArg); CallArgs.push_back(VoidCArg); CallArgs.push_back(E); Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc, CallArgs, NoSLoc).take(); assert(Result && "Cannot create value printer!"); return Result; } unsigned ValuePrinterSynthesizer::ClearNullStmts(CompoundStmt* CS) { llvm::SmallVector<Stmt*, 8> FBody; for (StmtRange range = CS->children(); range; ++range) if (!isa<NullStmt>(*range)) FBody.push_back(*range); CS->setStmts(*m_Context, FBody.data(), FBody.size()); return FBody.size(); } } // namespace cling <commit_msg>Initialize the variable to avoid dereferencing 0 (cid #47244)<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "ValuePrinterSynthesizer.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/ExprCXX.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/Sema.h" #include "llvm/Support/raw_os_ostream.h" #include <iostream> using namespace clang; namespace cling { ValuePrinterSynthesizer::ValuePrinterSynthesizer(clang::Sema* S, llvm::raw_ostream* Stream) : TransactionTransformer(S), m_Context(&S->getASTContext()) { if (Stream) m_ValuePrinterStream.reset(Stream); else m_ValuePrinterStream.reset(new llvm::raw_os_ostream(std::cout)); } // pin the vtable here. ValuePrinterSynthesizer::~ValuePrinterSynthesizer() { } void ValuePrinterSynthesizer::Transform() { if (!getTransaction()->getCompilationOpts().ValuePrinting) return; for (Transaction::const_iterator I = getTransaction()->decls_begin(), E = getTransaction()->decls_end(); I != E; ++I) if(!tryAttachVP(*I)) return setTransaction(0); // On error set the to NULL. } bool ValuePrinterSynthesizer::tryAttachVP(DeclGroupRef DGR) { for (DeclGroupRef::iterator I = DGR.begin(), E = DGR.end(); I != E; ++I) if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I)) { if (FD->getNameAsString().find("__cling_Un1Qu3")) return true; if (CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody())) { for (CompoundStmt::body_iterator J = CS->body_begin(), E = CS->body_end(); J != E; ++J) { if (J+1 == E || !isa<NullStmt>(*(J+1))) { Expr* To = 0; ReturnStmt* RS = dyn_cast<ReturnStmt>(*J); if (RS) To = RS->getRetValue(); else To = dyn_cast<Expr>(*J); if (To) { Expr* Result = 0; if (m_Sema->getLangOpts().CPlusPlus) Result = SynthesizeCppVP(To); else Result = SynthesizeVP(To); if (Result) { if (RS) RS->setRetValue(Result); else *J = Result; } } } } // Clear the artificial NullStmt-s if (!ClearNullStmts(CS)) { // if no body remove the wrapper DeclContext* DC = FD->getDeclContext(); Scope* S = m_Sema->getScopeForContext(DC); if (S) S->RemoveDecl(FD); DC->removeDecl(FD); } } } return true; } // We need to artificially create: // cling::valuePrinterInternal::PrintValue((void*) raw_ostream, // (ASTContext)Ctx, (Expr*)E, &i); Expr* ValuePrinterSynthesizer::SynthesizeCppVP(Expr* E) { QualType QT = E->getType(); // For now we skip void and function pointer types. if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType())) return 0; // 1. Call gCling->getValuePrinterStream() // 1.1. Find gCling SourceLocation NoSLoc = SourceLocation(); DeclContext* DC = m_Context->getTranslationUnitDecl(); DC = utils::Lookup::Namespace(m_Sema, "cling"); DC = utils::Lookup::Namespace(m_Sema, "valuePrinterInternal", DC); DeclarationName PVName = &m_Context->Idents.get("PrintValue"); LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); m_Sema->LookupQualifiedName(R, DC); assert(!R.empty() && "Cannot find PrintValue(...)"); CXXScopeSpec CSS; Expr* UnresolvedLookup = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); // 2.4. Prepare the params // 2.4.1 Lookup the llvm::raw_ostream CXXRecordDecl* RawOStreamRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "raw_ostream", utils::Lookup::Namespace(m_Sema, "llvm"))); assert(RawOStreamRD && "Declaration of the expr not found!"); QualType RawOStreamRDTy = m_Context->getTypeDeclType(RawOStreamRD); // 2.4.2 Lookup the expr type CXXRecordDecl* ExprRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr", utils::Lookup::Namespace(m_Sema, "clang"))); assert(ExprRD && "Declaration of the expr not found!"); QualType ExprRDTy = m_Context->getTypeDeclType(ExprRD); // 2.4.3 Lookup ASTContext type CXXRecordDecl* ASTContextRD = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "ASTContext", utils::Lookup::Namespace(m_Sema, "clang"))); assert(ASTContextRD && "Declaration of the expr not found!"); QualType ASTContextRDTy = m_Context->getTypeDeclType(ASTContextRD); Expr* RawOStreamTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, RawOStreamRDTy, (uint64_t)m_ValuePrinterStream.get() ); Expr* ExprTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)E); Expr* ASTContextTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ASTContextRDTy, (uint64_t)m_Context); // E might contain temporaries. This means that the topmost expr is // ExprWithCleanups. This contains the information about the temporaries and // signals when they should be destroyed. // Here we replace E with call to value printer and we must extend the life // time of those temporaries to the end of the new CallExpr. bool NeedsCleanup = false; if (ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(E)) { E = EWC->getSubExpr(); NeedsCleanup = true; } llvm::SmallVector<Expr*, 4> CallArgs; CallArgs.push_back(RawOStreamTy); CallArgs.push_back(ExprTy); CallArgs.push_back(ASTContextTy); CallArgs.push_back(E); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc, CallArgs, NoSLoc).take(); Result = m_Sema->ActOnFinishFullExpr(Result).take(); if (NeedsCleanup && !isa<ExprWithCleanups>(Result)) { llvm::ArrayRef<ExprWithCleanups::CleanupObject> Cleanups; ExprWithCleanups* EWC = ExprWithCleanups::Create(*m_Context, Result, Cleanups); Result = EWC; } assert(Result && "Cannot create value printer!"); return Result; } // We need to artificially create: // cling_PrintValue(void* (ASTContext)C, void* (Expr)E, const void* (&i) Expr* ValuePrinterSynthesizer::SynthesizeVP(Expr* E) { QualType QT = E->getType(); // For now we skip void and function pointer types. if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType())) return 0; // Find cling_PrintValue SourceLocation NoSLoc = SourceLocation(); DeclarationName PVName = &m_Context->Idents.get("cling_PrintValue"); LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext); m_Sema->LookupName(R, S); assert(!R.empty() && "Cannot find PrintValue(...)"); CXXScopeSpec CSS; Expr* UnresolvedLookup = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); Expr* VoidEArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, (uint64_t)E); Expr* VoidCArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, (uint64_t)m_Context); if (!QT->isPointerType()) { while(ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E)) E = ICE->getSubExpr(); E = m_Sema->BuildUnaryOp(S, NoSLoc, UO_AddrOf, E).take(); } llvm::SmallVector<Expr*, 4> CallArgs; CallArgs.push_back(VoidEArg); CallArgs.push_back(VoidCArg); CallArgs.push_back(E); Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc, CallArgs, NoSLoc).take(); assert(Result && "Cannot create value printer!"); return Result; } unsigned ValuePrinterSynthesizer::ClearNullStmts(CompoundStmt* CS) { llvm::SmallVector<Stmt*, 8> FBody; for (StmtRange range = CS->children(); range; ++range) if (!isa<NullStmt>(*range)) FBody.push_back(*range); CS->setStmts(*m_Context, FBody.data(), FBody.size()); return FBody.size(); } } // namespace cling <|endoftext|>
<commit_before>#include "nw_screen_api.h" #include "base/lazy_instance.h" #include "base/values.h" #include "content/nw/src/api/nw_screen.h" #include "extensions/browser/extensions_browser_client.h" #include "ui/gfx/display_observer.h" #include "ui/gfx/screen.h" // For desktop capture APIs #include "base/base64.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/media/desktop_media_list_observer.h" #include "chrome/browser/media/desktop_streams_registry.h" #include "chrome/browser/media/media_capture_devices_dispatcher.h" #include "chrome/browser/media/native_desktop_media_list.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/screen_capturer.h" #include "third_party/webrtc/modules/desktop_capture/window_capturer.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" using namespace extensions::nwapi::nw__screen; using namespace content; namespace extensions { class NwDesktopCaptureMonitor : public DesktopMediaListObserver { public: static NwDesktopCaptureMonitor* GetInstance(); NwDesktopCaptureMonitor(); void Start(bool screens, bool windows); void Stop(); bool IsStarted(); private: int GetPrimaryMonitorIndex(); // DesktopMediaListObserver implementation. void OnSourceAdded(int index) override; void OnSourceRemoved(int index) override; void OnSourceMoved(int old_index, int new_index) override; void OnSourceNameChanged(int index) override; void OnSourceThumbnailChanged(int index) override; bool started_; scoped_ptr<DesktopMediaList> media_list_; DISALLOW_COPY_AND_ASSIGN(NwDesktopCaptureMonitor); }; class NwScreenDisplayObserver: public gfx::DisplayObserver { public: static NwScreenDisplayObserver* GetInstance(); NwScreenDisplayObserver(); private: ~NwScreenDisplayObserver() override; // gfx::DisplayObserver implementation. void OnDisplayMetricsChanged(const gfx::Display& display, uint32_t changed_metrics) override; void OnDisplayAdded(const gfx::Display& new_display) override; void OnDisplayRemoved(const gfx::Display& old_display) override; DISALLOW_COPY_AND_ASSIGN(NwScreenDisplayObserver); }; namespace { // Helper function to convert gfx::Display to nwapi::nw__screen::Display scoped_ptr<nwapi::nw__screen::Display> ConvertGfxDisplay(const gfx::Display& gfx_display) { scoped_ptr<nwapi::nw__screen::Display> displayResult(new nwapi::nw__screen::Display); displayResult->id = gfx_display.id(); displayResult->scale_factor = gfx_display.device_scale_factor(); displayResult->is_built_in = gfx_display.IsInternal(); displayResult->rotation = gfx_display.RotationAsDegree(); displayResult->touch_support = gfx_display.touch_support(); gfx::Rect rect = gfx_display.bounds(); DisplayGeometry& bounds = displayResult->bounds; bounds.x = rect.x(); bounds.y = rect.y(); bounds.width = rect.width(); bounds.height = rect.height(); rect = gfx_display.work_area(); DisplayGeometry& work_area = displayResult->work_area; work_area.x = rect.x(); work_area.y = rect.y(); work_area.width = rect.width(); work_area.height = rect.height(); return displayResult; } void DispatchEvent( events::HistogramValue histogram_value, const std::string& event_name, scoped_ptr<base::ListValue> args) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ExtensionsBrowserClient::Get()->BroadcastEventToRenderers( histogram_value, event_name, std::move(args)); } // Lazy initialize screen event listeners until first call base::LazyInstance<NwScreenDisplayObserver>::Leaky g_display_observer = LAZY_INSTANCE_INITIALIZER; base::LazyInstance<NwDesktopCaptureMonitor>::Leaky g_desktop_capture_monitor = LAZY_INSTANCE_INITIALIZER; } // static NwScreenDisplayObserver* NwScreenDisplayObserver::GetInstance() { return g_display_observer.Pointer(); } NwScreenDisplayObserver::NwScreenDisplayObserver() { gfx::Screen* screen = gfx::Screen::GetNativeScreen(); if (screen) { screen->AddObserver(this); } } NwScreenDisplayObserver::~NwScreenDisplayObserver() { gfx::Screen* screen = gfx::Screen::GetNativeScreen(); if (screen) { screen->RemoveObserver(this); } } // Called when the |display|'s bound has changed. void NwScreenDisplayObserver::OnDisplayMetricsChanged(const gfx::Display& display, uint32_t changed_metrics) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayBoundsChanged::Create(*ConvertGfxDisplay(display), changed_metrics); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayBoundsChanged::kEventName, std::move(args)); } // Called when |new_display| has been added. void NwScreenDisplayObserver::OnDisplayAdded(const gfx::Display& new_display) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayAdded::Create(*ConvertGfxDisplay(new_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayAdded::kEventName, std::move(args)); } // Called when |old_display| has been removed. void NwScreenDisplayObserver::OnDisplayRemoved(const gfx::Display& old_display) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayRemoved::Create(*ConvertGfxDisplay(old_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayRemoved::kEventName, std::move(args)); } NwScreenGetScreensFunction::NwScreenGetScreensFunction() {} bool NwScreenGetScreensFunction::RunNWSync(base::ListValue* response, std::string* error) { const std::vector<gfx::Display>& displays = gfx::Screen::GetNativeScreen()->GetAllDisplays(); for (size_t i=0; i<displays.size(); i++) { response->Append(ConvertGfxDisplay(displays[i])->ToValue()); } return true; } NwScreenInitEventListenersFunction::NwScreenInitEventListenersFunction() {} bool NwScreenInitEventListenersFunction::RunNWSync(base::ListValue* response, std::string* error) { NwScreenDisplayObserver::GetInstance(); return true; } NwDesktopCaptureMonitor* NwDesktopCaptureMonitor::GetInstance() { return g_desktop_capture_monitor.Pointer(); } NwDesktopCaptureMonitor::NwDesktopCaptureMonitor() : started_(false) , media_list_(nullptr) { } void NwDesktopCaptureMonitor::Start(bool screens, bool windows) { if (started_) { return; } started_ = true; webrtc::DesktopCaptureOptions options = webrtc::DesktopCaptureOptions::CreateDefault(); options.set_disable_effects(false); scoped_ptr<webrtc::ScreenCapturer> screenCapturer(screens ? webrtc::ScreenCapturer::Create(options) : nullptr); scoped_ptr<webrtc::WindowCapturer> windowCapturer(windows ? webrtc::WindowCapturer::Create(options) : nullptr); media_list_.reset(new NativeDesktopMediaList(std::move(screenCapturer), std::move(windowCapturer))); media_list_->StartUpdating(this); } void NwDesktopCaptureMonitor::Stop() { started_ = false; media_list_.reset(); } bool NwDesktopCaptureMonitor::IsStarted() { return started_; } int NwDesktopCaptureMonitor::GetPrimaryMonitorIndex() { #ifdef _WIN32 int count=0; for (int i = 0;; ++i) { DISPLAY_DEVICE device; device.cb = sizeof(device); BOOL ret = EnumDisplayDevices(NULL, i, &device, 0); if(!ret) break; if (device.StateFlags & DISPLAY_DEVICE_ACTIVE){ if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE){ return count; } count++; } } #endif return -1; } void NwDesktopCaptureMonitor::OnSourceAdded(int index) { DesktopMediaList::Source src = media_list_->GetSource(index); std::string type; switch(src.id.type) { case content::DesktopMediaID::TYPE_WINDOW: type = "window"; break; case content::DesktopMediaID::TYPE_SCREEN: type = "screen"; break; case content::DesktopMediaID::TYPE_NONE: type = "none"; break; default: type = "unknown"; break; } scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceAdded::Create( src.id.ToString(), base::UTF16ToUTF8(src.name), index, type, src.id.type == content::DesktopMediaID::TYPE_SCREEN && GetPrimaryMonitorIndex() == index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceAdded::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceRemoved(int index) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceRemoved::Create(index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceRemoved::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceMoved(int old_index, int new_index) { DesktopMediaList::Source src = media_list_->GetSource(new_index); scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceOrderChanged::Create( src.id.ToString(), new_index, old_index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceOrderChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceNameChanged(int index) { DesktopMediaList::Source src = media_list_->GetSource(index); scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceNameChanged::Create( src.id.ToString(), base::UTF16ToUTF8(src.name)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceNameChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceThumbnailChanged(int index) { std::string base64; DesktopMediaList::Source src = media_list_->GetSource(index); SkBitmap bitmap = src.thumbnail.GetRepresentation(1).sk_bitmap(); SkAutoLockPixels lock_image(bitmap); std::vector<unsigned char> data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data); if (success){ base::StringPiece raw_str(reinterpret_cast<const char*>(&data[0]), data.size()); base::Base64Encode(raw_str, &base64); } scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceThumbnailChanged::Create( src.id.ToString(), base64); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceThumbnailChanged::kEventName, std::move(args)); } NwScreenStartMonitorFunction::NwScreenStartMonitorFunction() {} bool NwScreenStartMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { bool screens, windows; EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &screens)); EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(1, &windows)); NwDesktopCaptureMonitor::GetInstance()->Start(screens, windows); return true; } NwScreenStopMonitorFunction::NwScreenStopMonitorFunction() {} bool NwScreenStopMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { NwDesktopCaptureMonitor::GetInstance()->Stop(); return true; } NwScreenIsMonitorStartedFunction::NwScreenIsMonitorStartedFunction() {} bool NwScreenIsMonitorStartedFunction::RunNWSync(base::ListValue* response, std::string* error) { response->AppendBoolean(NwDesktopCaptureMonitor::GetInstance()->IsStarted()); return true; } NwScreenRegisterStreamFunction::NwScreenRegisterStreamFunction() {} bool NwScreenRegisterStreamFunction::RunNWSync(base::ListValue* response, std::string* error) { std::string id; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &id)); // following code is modified from `DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults` // in chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc content::DesktopMediaID source = content::DesktopMediaID::Parse(id); content::WebContents* web_contents = GetSenderWebContents(); if (!source.is_null() && web_contents) { std::string result; DesktopStreamsRegistry* registry = MediaCaptureDevicesDispatcher::GetInstance()-> GetDesktopStreamsRegistry(); // TODO(miu): Once render_frame_host() is being set, we should register the // exact RenderFrame requesting the stream, not the main RenderFrame. With // that change, also update // MediaCaptureDevicesDispatcher::ProcessDesktopCaptureAccessRequest(). // http://crbug.com/304341 content::RenderFrameHost* const main_frame = web_contents->GetMainFrame(); result = registry->RegisterStream(main_frame->GetProcess()->GetID(), main_frame->GetRoutingID(), extension()->url(), source, extension()->name()); response->AppendString(result); } return true; } } // extensions <commit_msg>Fixed similar issue of #4579 for `nw.Screen.DesktopCaptureMonitor`<commit_after>#include "nw_screen_api.h" #include "base/lazy_instance.h" #include "base/values.h" #include "content/nw/src/api/nw_screen.h" #include "extensions/browser/extensions_browser_client.h" #include "ui/gfx/display_observer.h" #include "ui/gfx/screen.h" // For desktop capture APIs #include "base/base64.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/media/desktop_media_list_observer.h" #include "chrome/browser/media/desktop_streams_registry.h" #include "chrome/browser/media/media_capture_devices_dispatcher.h" #include "chrome/browser/media/native_desktop_media_list.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/screen_capturer.h" #include "third_party/webrtc/modules/desktop_capture/window_capturer.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" using namespace extensions::nwapi::nw__screen; using namespace content; namespace extensions { class NwDesktopCaptureMonitor : public DesktopMediaListObserver { public: static NwDesktopCaptureMonitor* GetInstance(); NwDesktopCaptureMonitor(); void Start(bool screens, bool windows); void Stop(); bool IsStarted(); private: int GetPrimaryMonitorIndex(); // DesktopMediaListObserver implementation. void OnSourceAdded(int index) override; void OnSourceRemoved(int index) override; void OnSourceMoved(int old_index, int new_index) override; void OnSourceNameChanged(int index) override; void OnSourceThumbnailChanged(int index) override; bool started_; scoped_ptr<DesktopMediaList> media_list_; DISALLOW_COPY_AND_ASSIGN(NwDesktopCaptureMonitor); }; class NwScreenDisplayObserver: public gfx::DisplayObserver { public: static NwScreenDisplayObserver* GetInstance(); NwScreenDisplayObserver(); private: ~NwScreenDisplayObserver() override; // gfx::DisplayObserver implementation. void OnDisplayMetricsChanged(const gfx::Display& display, uint32_t changed_metrics) override; void OnDisplayAdded(const gfx::Display& new_display) override; void OnDisplayRemoved(const gfx::Display& old_display) override; DISALLOW_COPY_AND_ASSIGN(NwScreenDisplayObserver); }; namespace { // Helper function to convert gfx::Display to nwapi::nw__screen::Display scoped_ptr<nwapi::nw__screen::Display> ConvertGfxDisplay(const gfx::Display& gfx_display) { scoped_ptr<nwapi::nw__screen::Display> displayResult(new nwapi::nw__screen::Display); displayResult->id = gfx_display.id(); displayResult->scale_factor = gfx_display.device_scale_factor(); displayResult->is_built_in = gfx_display.IsInternal(); displayResult->rotation = gfx_display.RotationAsDegree(); displayResult->touch_support = gfx_display.touch_support(); gfx::Rect rect = gfx_display.bounds(); DisplayGeometry& bounds = displayResult->bounds; bounds.x = rect.x(); bounds.y = rect.y(); bounds.width = rect.width(); bounds.height = rect.height(); rect = gfx_display.work_area(); DisplayGeometry& work_area = displayResult->work_area; work_area.x = rect.x(); work_area.y = rect.y(); work_area.width = rect.width(); work_area.height = rect.height(); return displayResult; } void DispatchEvent( events::HistogramValue histogram_value, const std::string& event_name, scoped_ptr<base::ListValue> args) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ExtensionsBrowserClient::Get()->BroadcastEventToRenderers( histogram_value, event_name, std::move(args)); } // Lazy initialize screen event listeners until first call base::LazyInstance<NwScreenDisplayObserver>::Leaky g_display_observer = LAZY_INSTANCE_INITIALIZER; base::LazyInstance<NwDesktopCaptureMonitor>::Leaky g_desktop_capture_monitor = LAZY_INSTANCE_INITIALIZER; } // static NwScreenDisplayObserver* NwScreenDisplayObserver::GetInstance() { return g_display_observer.Pointer(); } NwScreenDisplayObserver::NwScreenDisplayObserver() { gfx::Screen* screen = gfx::Screen::GetNativeScreen(); if (screen) { screen->AddObserver(this); } } NwScreenDisplayObserver::~NwScreenDisplayObserver() { gfx::Screen* screen = gfx::Screen::GetNativeScreen(); if (screen) { screen->RemoveObserver(this); } } // Called when the |display|'s bound has changed. void NwScreenDisplayObserver::OnDisplayMetricsChanged(const gfx::Display& display, uint32_t changed_metrics) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayBoundsChanged::Create(*ConvertGfxDisplay(display), changed_metrics); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayBoundsChanged::kEventName, std::move(args)); } // Called when |new_display| has been added. void NwScreenDisplayObserver::OnDisplayAdded(const gfx::Display& new_display) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayAdded::Create(*ConvertGfxDisplay(new_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayAdded::kEventName, std::move(args)); } // Called when |old_display| has been removed. void NwScreenDisplayObserver::OnDisplayRemoved(const gfx::Display& old_display) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayRemoved::Create(*ConvertGfxDisplay(old_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayRemoved::kEventName, std::move(args)); } NwScreenGetScreensFunction::NwScreenGetScreensFunction() {} bool NwScreenGetScreensFunction::RunNWSync(base::ListValue* response, std::string* error) { const std::vector<gfx::Display>& displays = gfx::Screen::GetNativeScreen()->GetAllDisplays(); for (size_t i=0; i<displays.size(); i++) { response->Append(ConvertGfxDisplay(displays[i])->ToValue()); } return true; } NwScreenInitEventListenersFunction::NwScreenInitEventListenersFunction() {} bool NwScreenInitEventListenersFunction::RunNWSync(base::ListValue* response, std::string* error) { NwScreenDisplayObserver::GetInstance(); return true; } NwDesktopCaptureMonitor* NwDesktopCaptureMonitor::GetInstance() { return g_desktop_capture_monitor.Pointer(); } NwDesktopCaptureMonitor::NwDesktopCaptureMonitor() : started_(false) , media_list_(nullptr) { } void NwDesktopCaptureMonitor::Start(bool screens, bool windows) { if (started_) { return; } started_ = true; webrtc::DesktopCaptureOptions options = webrtc::DesktopCaptureOptions::CreateDefault(); options.set_disable_effects(false); scoped_ptr<webrtc::ScreenCapturer> screenCapturer(screens ? webrtc::ScreenCapturer::Create(options) : nullptr); scoped_ptr<webrtc::WindowCapturer> windowCapturer(windows ? webrtc::WindowCapturer::Create(options) : nullptr); media_list_.reset(new NativeDesktopMediaList(std::move(screenCapturer), std::move(windowCapturer))); media_list_->StartUpdating(this); } void NwDesktopCaptureMonitor::Stop() { started_ = false; media_list_.reset(); } bool NwDesktopCaptureMonitor::IsStarted() { return started_; } int NwDesktopCaptureMonitor::GetPrimaryMonitorIndex() { #ifdef _WIN32 int count=0; for (int i = 0;; ++i) { DISPLAY_DEVICE device; device.cb = sizeof(device); BOOL ret = EnumDisplayDevices(NULL, i, &device, 0); if(!ret) break; if (device.StateFlags & DISPLAY_DEVICE_ACTIVE){ if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE){ return count; } count++; } } #endif return -1; } void NwDesktopCaptureMonitor::OnSourceAdded(int index) { DesktopMediaList::Source src = media_list_->GetSource(index); std::string type; switch(src.id.type) { case content::DesktopMediaID::TYPE_WINDOW: type = "window"; break; case content::DesktopMediaID::TYPE_SCREEN: type = "screen"; break; case content::DesktopMediaID::TYPE_NONE: type = "none"; break; default: type = "unknown"; break; } scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceAdded::Create( src.id.ToString(), base::UTF16ToUTF8(src.name), index, type, src.id.type == content::DesktopMediaID::TYPE_SCREEN && GetPrimaryMonitorIndex() == index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceAdded::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceRemoved(int index) { scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceRemoved::Create(index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceRemoved::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceMoved(int old_index, int new_index) { DesktopMediaList::Source src = media_list_->GetSource(new_index); scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceOrderChanged::Create( src.id.ToString(), new_index, old_index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceOrderChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceNameChanged(int index) { DesktopMediaList::Source src = media_list_->GetSource(index); scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceNameChanged::Create( src.id.ToString(), base::UTF16ToUTF8(src.name)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceNameChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceThumbnailChanged(int index) { std::string base64; DesktopMediaList::Source src = media_list_->GetSource(index); SkBitmap bitmap = src.thumbnail.GetRepresentation(1).sk_bitmap(); SkAutoLockPixels lock_image(bitmap); std::vector<unsigned char> data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data); if (success){ base::StringPiece raw_str(reinterpret_cast<const char*>(&data[0]), data.size()); base::Base64Encode(raw_str, &base64); } scoped_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceThumbnailChanged::Create( src.id.ToString(), base64); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceThumbnailChanged::kEventName, std::move(args)); } NwScreenStartMonitorFunction::NwScreenStartMonitorFunction() {} bool NwScreenStartMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { bool screens, windows; EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &screens)); EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(1, &windows)); NwDesktopCaptureMonitor::GetInstance()->Start(screens, windows); return true; } NwScreenStopMonitorFunction::NwScreenStopMonitorFunction() {} bool NwScreenStopMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { NwDesktopCaptureMonitor::GetInstance()->Stop(); return true; } NwScreenIsMonitorStartedFunction::NwScreenIsMonitorStartedFunction() {} bool NwScreenIsMonitorStartedFunction::RunNWSync(base::ListValue* response, std::string* error) { response->AppendBoolean(NwDesktopCaptureMonitor::GetInstance()->IsStarted()); return true; } NwScreenRegisterStreamFunction::NwScreenRegisterStreamFunction() {} bool NwScreenRegisterStreamFunction::RunNWSync(base::ListValue* response, std::string* error) { std::string id; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &id)); // following code is modified from `DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults` // in chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc content::DesktopMediaID source = content::DesktopMediaID::Parse(id); content::WebContents* web_contents = GetSenderWebContents(); if (!source.is_null() && web_contents) { std::string result; DesktopStreamsRegistry* registry = MediaCaptureDevicesDispatcher::GetInstance()-> GetDesktopStreamsRegistry(); // TODO(miu): Once render_frame_host() is being set, we should register the // exact RenderFrame requesting the stream, not the main RenderFrame. With // that change, also update // MediaCaptureDevicesDispatcher::ProcessDesktopCaptureAccessRequest(). // http://crbug.com/304341 content::RenderFrameHost* const main_frame = web_contents->GetMainFrame(); result = registry->RegisterStream(main_frame->GetProcess()->GetID(), main_frame->GetRoutingID(), web_contents->GetURL().GetOrigin(), source, extension()->name()); response->AppendString(result); } return true; } } // extensions <|endoftext|>
<commit_before>#pragma once #include <rai/lib/numbers.hpp> #include <deque> #include <mutex> #include <thread> namespace rai { class node; class vote_generator { public: vote_generator (rai::node &, std::chrono::milliseconds); void add (rai::block_hash const &); void stop (); private: void run (); void send (std::unique_lock<std::mutex> &); rai::node & node; std::mutex mutex; std::condition_variable condition; std::deque<rai::block_hash> hashes; std::chrono::milliseconds wait; bool stopped; bool started; std::thread thread; }; } <commit_msg>Directly including condition_variable header.<commit_after>#pragma once #include <rai/lib/numbers.hpp> #include <condition_variable> #include <deque> #include <mutex> #include <thread> namespace rai { class node; class vote_generator { public: vote_generator (rai::node &, std::chrono::milliseconds); void add (rai::block_hash const &); void stop (); private: void run (); void send (std::unique_lock<std::mutex> &); rai::node & node; std::mutex mutex; std::condition_variable condition; std::deque<rai::block_hash> hashes; std::chrono::milliseconds wait; bool stopped; bool started; std::thread thread; }; } <|endoftext|>
<commit_before>/** * @file dropconnect_layer.hpp * @author Palash Ahuja * * Definition of the DropConnectLayer class, which implements a regularizer * that randomly sets connections to zero. Preventing units from co-adapting. */ #ifndef __MLPACK_METHODS_ANN_LAYER_DROPCONNECT_LAYER_HPP #define __MLPACK_METHODS_ANN_LAYER_DROPCONNECT_LAYER_HPP #include <mlpack/core.hpp> #include "empty_layer.hpp" #include <mlpack/methods/ann/network_util.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * The DropConnect layer is a regularizer that randomly with probability * ratio sets the connection values to zero and scales the remaining * elements by factor 1 /(1 - ratio). The output is scaled with 1 / (1 - p) * when deterministic is false. In the deterministic mode(during testing), * the layer just computes the output. The output is computed according * to the input layer. If no input layer is given, it will take a linear layer * as default. * * Note: * During training you should set deterministic to false and during testing * you should set deterministic to true. * * For more information, see the following. * * @code * @inproceedings{WanICML2013, * title={Regularization of Neural Networks using DropConnect}, * booktitle = {Proceedings of the 30th International Conference on Machine * Learning(ICML - 13)}, * author = {Li Wan and Matthew Zeiler and Sixin Zhang and Yann L. Cun and * Rob Fergus}, * year = {2013} * } * @endcode * * @tparam InputLayer Layer used instead of the internel linear layer. * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). */ template< typename InputLayer = EmptyLayer<arma::mat, arma::mat>, typename InputDataType = arma::mat, typename OutputDataType = arma::mat > class DropConnectLayer { public: /** * Creates the DropConnect Layer as a Linear Object that takes input size, * output size and ratio as parameter. * * @param inSize The number of input units. * @param outSize The number of output units. * @param ratio The probability of setting a value to zero. */ DropConnectLayer (const size_t inSize, const size_t outSize, const double ratio = 0.5) : inSize(inSize), outSize(outSize), ratio(ratio), scale(1.0 / (1 - ratio)), uselayer(false) { weights.set_size(outSize, inSize); } /** * Create the DropConnectLayer object using the specified ratio and rescale * parameter. This takes the * * @param ratio The probability of setting a connection to zero. * @param inputLayer the layer object that the dropconnect connection would take. */ template<typename InputLayerType> DropConnectLayer(InputLayerType &&inputLayer, const double ratio = 0.5) : baseLayer(std::forward<InputLayerType>(inputLayer)), ratio(ratio), scale(1.0 / (1 - ratio)), uselayer(true) { static_assert(std::is_same<typename std::decay<InputLayerType>::type, InputLayer>::value, "The type of the inputLayer must be InputLayerType"); } /** * Ordinary feed forward pass of the DropConnect layer. * * @param input Input data used for evaluating the specified function. * @param output Resulting output activation. */ template<typename eT> void Forward(const arma::Mat<eT> &input, arma::Mat<eT> &output) { // The DropConnect mask will not be multiplied in the deterministic mode // (during testing). if (deterministic) { if(uselayer) { baseLayer.Forward(input, output); } else { output = weights * input; } } else { if(uselayer) { // Scale with input / (1 - ratio) and set values to zero with // probability ratio. mask = arma::randu<arma::Mat<eT> >(baseLayer.Weights().n_rows, baseLayer.Weights().n_cols); mask.transform([&](double val) { return (val > ratio); }); // Save weights for denoising. denoise = baseLayer.Weights(); baseLayer.Weights() = baseLayer.Weights() % mask; baseLayer.Forward(input, output); } else { // Scale the input / ( 1 - ratio) and set values to zero with // probability ratio. mask = arma::randu<arma::Mat<eT> >(weights.n_rows, weights.n_cols); mask.transform([&](double val) { return (val > ratio); }); // Save weights for denoising. denoise = weights; weights = weights % mask; output = weights * input; } output = output * scale; } } /** * Ordinary feed backward pass of the DropConnect layer. * * @param input The propagated input activation. * @param gy The backpropagated error. * @param g The calculated gradient. */ template<typename DataType> void Backward(const DataType& input, const DataType& gy, DataType& g) { if(uselayer) { baseLayer.Backward(input, gy, g); } else { g = weights.t() * gy; } } /** * Calculate the gradient using the output delta and the input activation. * * @param d The calculated error. * @param g The calculated gradient. */ template<typename eT, typename GradientDataType> void Gradient(const arma::Mat<eT>& d, GradientDataType& g) { if(uselayer) { baseLayer.Gradient(d, g); // Denoise the weights. baseLayer.Weights() = denoise; } else { g = d * inputParameter.t(); // Denoise the weights. weights = denoise; } } //! Get the weights. OutputDataType const& Weights() const { if(uselayer) return baseLayer.Weights(); return weights; } //! Modify the weights. OutputDataType& Weights() { if(uselayer) return baseLayer.Weights(); return weights; } //! Get the input parameter. InputDataType &InputParameter() const { if(uselayer) return baseLayer.InputParameter(); return inputParameter; } //! Modify the input parameter. InputDataType &InputParameter() { if(uselayer) return baseLayer.InputParameter(); return inputParameter; } //! Get the output parameter. OutputDataType &OutputParameter() const { if(uselayer) return baseLayer.OutputParameter(); return outputParameter; } //! Modify the output parameter. OutputDataType &OutputParameter() { if(uselayer) return baseLayer.OutputParameter(); return outputParameter; } //! Get the delta. OutputDataType const& Delta() const { if(uselayer) return baseLayer.Delta(); return delta; } //! Modify the delta. OutputDataType& Delta() { if(uselayer) return baseLayer.Delta(); return delta; } //! Get the gradient. OutputDataType const& Gradient() const { if(uselayer) return baseLayer.Gradient(); return gradient; } //! Modify the gradient. OutputDataType& Gradient() { if(uselayer) return baseLayer.Gradient(); return gradient; } //! The value of the deterministic parameter. bool Deterministic() const { return deterministic; } //! Modify the value of the deterministic parameter. bool &Deterministic() { return deterministic; } //! The probability of setting a value to zero. double Ratio() const { return ratio; } //! Modify the probability of setting a value to zero. void Ratio(const double r) { ratio = r; scale = 1.0 / (1.0 - ratio); } private: //! Locally stored number of input units. size_t inSize; //! Locally-stored number of output units. size_t outSize; //! The probability of setting a value to zero. double ratio; //! If true the default layer is used otherwise a new layer will be created. bool uselayer; //! Locally-stored weight object. OutputDataType weights; //! Locally-stored delta object. OutputDataType delta; //! Locally-stored layer object. InputLayer baseLayer; //! Locally-stored gradient object. OutputDataType gradient; //! Locally-stored input parameter object. InputDataType inputParameter; //! Locally-stored output parameter object. OutputDataType outputParameter; //! Locally-stored mast object. OutputDataType mask; //! The scale fraction. double scale; //! If true dropout and scaling is disabled, see notes above. bool deterministic; //! Denoise mask for the weights. OutputDataType denoise; }; // class DropConnectLayer. } // namespace ann } // namespace mlpack #endif <commit_msg>Reorder the parameter of the DropConnectLayer to avoid reorder warning.<commit_after>/** * @file dropconnect_layer.hpp * @author Palash Ahuja * * Definition of the DropConnectLayer class, which implements a regularizer * that randomly sets connections to zero. Preventing units from co-adapting. */ #ifndef __MLPACK_METHODS_ANN_LAYER_DROPCONNECT_LAYER_HPP #define __MLPACK_METHODS_ANN_LAYER_DROPCONNECT_LAYER_HPP #include <mlpack/core.hpp> #include "empty_layer.hpp" #include <mlpack/methods/ann/network_util.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * The DropConnect layer is a regularizer that randomly with probability * ratio sets the connection values to zero and scales the remaining * elements by factor 1 /(1 - ratio). The output is scaled with 1 / (1 - p) * when deterministic is false. In the deterministic mode(during testing), * the layer just computes the output. The output is computed according * to the input layer. If no input layer is given, it will take a linear layer * as default. * * Note: * During training you should set deterministic to false and during testing * you should set deterministic to true. * * For more information, see the following. * * @code * @inproceedings{WanICML2013, * title={Regularization of Neural Networks using DropConnect}, * booktitle = {Proceedings of the 30th International Conference on Machine * Learning(ICML - 13)}, * author = {Li Wan and Matthew Zeiler and Sixin Zhang and Yann L. Cun and * Rob Fergus}, * year = {2013} * } * @endcode * * @tparam InputLayer Layer used instead of the internel linear layer. * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). */ template< typename InputLayer = EmptyLayer<arma::mat, arma::mat>, typename InputDataType = arma::mat, typename OutputDataType = arma::mat > class DropConnectLayer { public: /** * Creates the DropConnect Layer as a Linear Object that takes input size, * output size and ratio as parameter. * * @param inSize The number of input units. * @param outSize The number of output units. * @param ratio The probability of setting a value to zero. */ DropConnectLayer (const size_t inSize, const size_t outSize, const double ratio = 0.5) : inSize(inSize), outSize(outSize), ratio(ratio), scale(1.0 / (1 - ratio)), uselayer(false) { weights.set_size(outSize, inSize); } /** * Create the DropConnectLayer object using the specified ratio and rescale * parameter. This takes the * * @param ratio The probability of setting a connection to zero. * @param inputLayer the layer object that the dropconnect connection would take. */ template<typename InputLayerType> DropConnectLayer(InputLayerType &&inputLayer, const double ratio = 0.5) : baseLayer(std::forward<InputLayerType>(inputLayer)), ratio(ratio), scale(1.0 / (1 - ratio)), uselayer(true) { static_assert(std::is_same<typename std::decay<InputLayerType>::type, InputLayer>::value, "The type of the inputLayer must be InputLayerType"); } /** * Ordinary feed forward pass of the DropConnect layer. * * @param input Input data used for evaluating the specified function. * @param output Resulting output activation. */ template<typename eT> void Forward(const arma::Mat<eT> &input, arma::Mat<eT> &output) { // The DropConnect mask will not be multiplied in the deterministic mode // (during testing). if (deterministic) { if(uselayer) { baseLayer.Forward(input, output); } else { output = weights * input; } } else { if(uselayer) { // Scale with input / (1 - ratio) and set values to zero with // probability ratio. mask = arma::randu<arma::Mat<eT> >(baseLayer.Weights().n_rows, baseLayer.Weights().n_cols); mask.transform([&](double val) { return (val > ratio); }); // Save weights for denoising. denoise = baseLayer.Weights(); baseLayer.Weights() = baseLayer.Weights() % mask; baseLayer.Forward(input, output); } else { // Scale the input / ( 1 - ratio) and set values to zero with // probability ratio. mask = arma::randu<arma::Mat<eT> >(weights.n_rows, weights.n_cols); mask.transform([&](double val) { return (val > ratio); }); // Save weights for denoising. denoise = weights; weights = weights % mask; output = weights * input; } output = output * scale; } } /** * Ordinary feed backward pass of the DropConnect layer. * * @param input The propagated input activation. * @param gy The backpropagated error. * @param g The calculated gradient. */ template<typename DataType> void Backward(const DataType& input, const DataType& gy, DataType& g) { if(uselayer) { baseLayer.Backward(input, gy, g); } else { g = weights.t() * gy; } } /** * Calculate the gradient using the output delta and the input activation. * * @param d The calculated error. * @param g The calculated gradient. */ template<typename eT, typename GradientDataType> void Gradient(const arma::Mat<eT>& d, GradientDataType& g) { if(uselayer) { baseLayer.Gradient(d, g); // Denoise the weights. baseLayer.Weights() = denoise; } else { g = d * inputParameter.t(); // Denoise the weights. weights = denoise; } } //! Get the weights. OutputDataType const& Weights() const { if(uselayer) return baseLayer.Weights(); return weights; } //! Modify the weights. OutputDataType& Weights() { if(uselayer) return baseLayer.Weights(); return weights; } //! Get the input parameter. InputDataType &InputParameter() const { if(uselayer) return baseLayer.InputParameter(); return inputParameter; } //! Modify the input parameter. InputDataType &InputParameter() { if(uselayer) return baseLayer.InputParameter(); return inputParameter; } //! Get the output parameter. OutputDataType &OutputParameter() const { if(uselayer) return baseLayer.OutputParameter(); return outputParameter; } //! Modify the output parameter. OutputDataType &OutputParameter() { if(uselayer) return baseLayer.OutputParameter(); return outputParameter; } //! Get the delta. OutputDataType const& Delta() const { if(uselayer) return baseLayer.Delta(); return delta; } //! Modify the delta. OutputDataType& Delta() { if(uselayer) return baseLayer.Delta(); return delta; } //! Get the gradient. OutputDataType const& Gradient() const { if(uselayer) return baseLayer.Gradient(); return gradient; } //! Modify the gradient. OutputDataType& Gradient() { if(uselayer) return baseLayer.Gradient(); return gradient; } //! The value of the deterministic parameter. bool Deterministic() const { return deterministic; } //! Modify the value of the deterministic parameter. bool &Deterministic() { return deterministic; } //! The probability of setting a value to zero. double Ratio() const { return ratio; } //! Modify the probability of setting a value to zero. void Ratio(const double r) { ratio = r; scale = 1.0 / (1.0 - ratio); } private: //! Locally-stored layer object. InputLayer baseLayer; //! Locally stored number of input units. size_t inSize; //! Locally-stored number of output units. size_t outSize; //! The probability of setting a value to zero. double ratio; //! The scale fraction. double scale; //! If true the default layer is used otherwise a new layer will be created. bool uselayer; //! Locally-stored weight object. OutputDataType weights; //! Locally-stored delta object. OutputDataType delta; //! Locally-stored gradient object. OutputDataType gradient; //! Locally-stored input parameter object. InputDataType inputParameter; //! Locally-stored output parameter object. OutputDataType outputParameter; //! Locally-stored mast object. OutputDataType mask; //! If true dropout and scaling is disabled, see notes above. bool deterministic; //! Denoise mask for the weights. OutputDataType denoise; }; // class DropConnectLayer. } // namespace ann } // namespace mlpack #endif <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/Attic/main.cpp,v $ $Revision: 1.4 $ $Name: $ $Author: shoops $ $Date: 2006/04/27 01:34:21 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <iostream> int main (int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; } <commit_msg>Obsolete<commit_after><|endoftext|>
<commit_before> /* * Copyright (c) 2012 Karl N. Redgate * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** \file LinuxNetworkMonitor.cc * \brief * */ #include <asm/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/wait.h> #include <arpa/inet.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <stdlib.h> #include <signal.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <glob.h> #include <errno.h> #include <tcl.h> #include "tcl_util.h" #include "logger.h" #include "util.h" #include "NetLink.h" #include "NetworkMonitor.h" namespace { int debug = 0; } /** */ static int Monitor_obj( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { NetLink::Monitor *monitor = (NetLink::Monitor *)data; if ( objc == 1 ) { Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(monitor)) ); return TCL_OK; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "type") ) { Svc_SetResult( interp, "Network::Monitor", TCL_STATIC ); return TCL_OK; } if ( Tcl_StringMatch(command, "start") ) { // this should have some sort of result so we know it has started correctly monitor->start(); /* if ( result == NULL ) { Tcl_ResetResult( interp ); return TCL_OK; } Svc_SetResult( interp, (char *)result, TCL_STATIC ); return TCL_ERROR; */ Tcl_ResetResult( interp ); return TCL_OK; } /** */ if ( Tcl_StringMatch(command, "stop") ) { /* const char *result = monitor->stop(); if ( result == NULL ) { Tcl_ResetResult( interp ); return TCL_OK; } Svc_SetResult( interp, (char *)result, TCL_STATIC ); return TCL_ERROR; */ Tcl_ResetResult( interp ); return TCL_OK; } /* * I want an 'interfaces' sub command ... */ Svc_SetResult( interp, "Unknown command for Monitor object", TCL_STATIC ); return TCL_ERROR; } /** */ static void Monitor_delete( ClientData data ) { NetLink::Monitor *message = (NetLink::Monitor *)data; delete message; } /** */ static int Monitor_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { if ( objc != 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name factory" ); return TCL_ERROR; } Network::ListenerInterfaceFactory factory; void *p = (void *)&(factory); // avoid strict aliasing errors in the compiler if ( Tcl_GetLongFromObj(interp,objv[2],(long*)p) != TCL_OK ) { Svc_SetResult( interp, "invalid listener object", TCL_STATIC ); return TCL_ERROR; } char *name = Tcl_GetStringFromObj( objv[1], NULL ); NetLink::Monitor *object = new NetLink::Monitor( interp, factory, NULL ); Tcl_CreateObjCommand( interp, name, Monitor_obj, (ClientData)object, Monitor_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } /** * This is a sample command for testing the straight line netlink * probe code. */ static int Probe_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { // Yes, this is intentional, it may get removed later pid_t pid __attribute((unused)) = getpid(); int result; // Discover interfaces and add objects int fd; fd = socket( AF_NETLINK, SOCK_RAW, NETLINK_ROUTE ); if ( socket < 0 ) { log_err( "Probe socket() failed, %s", strerror(errno) ); exit( 1 ); } // setup sndbuf and rcvbuf // bind struct sockaddr_nl address; memset( &address, 0, sizeof(address) ); address.nl_family = AF_NETLINK; address.nl_groups = 0; if ( bind(fd, (struct sockaddr *)&address, sizeof(address)) < 0 ) { log_err( "Probe bind() failed, %s", strerror(errno) ); exit( 1 ); } // send request struct { struct nlmsghdr nlh; struct rtgenmsg g; } nlreq; memset( &nlreq, 0, sizeof(nlreq) ); nlreq.nlh.nlmsg_len = sizeof(nlreq); nlreq.nlh.nlmsg_type = RTM_GETLINK; nlreq.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; nlreq.nlh.nlmsg_pid = 0; nlreq.nlh.nlmsg_seq = 34; nlreq.g.rtgen_family = AF_PACKET; result = sendto( fd, (void*)&nlreq, sizeof(nlreq), 0, (struct sockaddr *)&address, sizeof(address) ); if ( result < 0 ) { log_err( "Probe sendto() failed, %s", strerror(errno) ); exit( 1 ); } // Now I am going to reuse the "address" structure for receiving the responses. memset( &address, 0, sizeof(address) ); char msg_buf[16384]; struct iovec iov; memset( &iov, 0, sizeof(iov) ); iov.iov_base = msg_buf; struct msghdr rsp_msg; rsp_msg.msg_name = &address; rsp_msg.msg_namelen = sizeof(address); rsp_msg.msg_iov = &iov; rsp_msg.msg_iovlen = 1; // loop around waiting for netlink messages // for each response create an interface object for (;;) { unsigned int status; struct nlmsghdr *h; iov.iov_len = sizeof(msg_buf); status = recvmsg( fd, &rsp_msg, 0 ); if ( status < 0 ) { if ( errno == EINTR ) { // normally just continue here printf( "interupted recvmsg\n" ); } else { log_err( "Probe recvmsg() failed, %s", strerror(errno) ); } continue; } if ( status == 0 ) { printf( "finished nlmsgs\n" ); break; } printf( "status=%d\n", status ); h = (struct nlmsghdr *)msg_buf; while ( NLMSG_OK(h, status) ) { if ( h->nlmsg_type == NLMSG_DONE ) { printf( "NLMSG_DONE\n" ); goto finish; } if ( h->nlmsg_type == NLMSG_ERROR ) { printf( "NLMSG_ERROR\n" ); goto finish; } /* if ( h->nlmsg_flags & NLM_F_MULTI ) { printf( "NLM_F_MULTI\n" ); } else { printf( "not:NLM_F_MULTI\n" ); } */ printf( "process nlmsg type=%d flags=0x%08x pid=%d seq=%d\n", h->nlmsg_type, h->nlmsg_flags, h->nlmsg_pid, h->nlmsg_seq ); { // type is in linux/if_arp.h -- flags are in linux/if.h NetLink::NewLink *m = new NetLink::NewLink( h ); Network::Interface *ii = new Network::Interface( interp, m ); if ( ii == NULL ) { // remove -Wall warning by using this } } h = NLMSG_NEXT( h, status ); } printf( "finished with this message (notOK)\n" ); if ( rsp_msg.msg_flags & MSG_TRUNC ) { printf( "msg truncated" ); continue; } if ( status != 0 ) { printf( "remnant\n" ); } } finish: close( fd ); // Discover Bridges // Search for existing bridges and create objects for them // and for each object create a command // the bridge commands should remain in the Network namespace // -- maybe no -- create in whichever namespace you need return TCL_OK; } /** * need some way to find these objects... * use TCL ..hmmm */ bool NetLinkMonitor_Module( Tcl_Interp *interp ) { Tcl_Command command; Tcl_Namespace *ns = Tcl_CreateNamespace(interp, "Network", (ClientData)0, NULL); if ( ns == NULL ) { return false; } if ( Tcl_LinkVar(interp, "Network::debug", (char *)&debug, TCL_LINK_INT) != TCL_OK ) { log_err( "failed to link Network::debug" ); exit( 1 ); } command = Tcl_CreateObjCommand(interp, "Network::Monitor", Monitor_cmd, (ClientData)0, NULL); if ( command == NULL ) { // logger ?? want to report TCL Error return false; } command = Tcl_CreateObjCommand(interp, "Network::Probe", Probe_cmd, (ClientData)0, NULL); if ( command == NULL ) { // logger ?? want to report TCL Error return false; } return true; } /* vim: set autoindent expandtab sw=4 : */ <commit_msg>fix build<commit_after> /* * Copyright (c) 2012 Karl N. Redgate * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** \file LinuxNetworkMonitor.cc * \brief * */ #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/wait.h> #include <arpa/inet.h> #include <stdlib.h> #include <signal.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <glob.h> #include <errno.h> #include <tcl.h> #include "tcl_util.h" #include "logger.h" #include "util.h" #include "NetworkMonitor.h" #include "AppInit.h" namespace { int debug = 0; } /** */ static int Monitor_obj( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { Network::Monitor *monitor = (Network::Monitor *)data; if ( objc == 1 ) { Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(monitor)) ); return TCL_OK; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "type") ) { Svc_SetResult( interp, "Network::Monitor", TCL_STATIC ); return TCL_OK; } if ( Tcl_StringMatch(command, "start") ) { // this should have some sort of result so we know it has started correctly monitor->start(); /* if ( result == NULL ) { Tcl_ResetResult( interp ); return TCL_OK; } Svc_SetResult( interp, (char *)result, TCL_STATIC ); return TCL_ERROR; */ Tcl_ResetResult( interp ); return TCL_OK; } /** */ if ( Tcl_StringMatch(command, "stop") ) { /* const char *result = monitor->stop(); if ( result == NULL ) { Tcl_ResetResult( interp ); return TCL_OK; } Svc_SetResult( interp, (char *)result, TCL_STATIC ); return TCL_ERROR; */ Tcl_ResetResult( interp ); return TCL_OK; } /* * I want an 'interfaces' sub command ... */ Svc_SetResult( interp, "Unknown command for Monitor object", TCL_STATIC ); return TCL_ERROR; } /** */ static void Monitor_delete( ClientData data ) { Network::Monitor *message = (Network::Monitor *)data; delete message; } /** */ static int Monitor_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { if ( objc != 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name factory" ); return TCL_ERROR; } Network::ListenerInterfaceFactory factory; void *p = (void *)&(factory); // avoid strict aliasing errors in the compiler if ( Tcl_GetLongFromObj(interp,objv[2],(long*)p) != TCL_OK ) { Svc_SetResult( interp, "invalid listener object", TCL_STATIC ); return TCL_ERROR; } char *name = Tcl_GetStringFromObj( objv[1], NULL ); Network::Monitor *object = new Network::Monitor( interp, factory ); Tcl_CreateObjCommand( interp, name, Monitor_obj, (ClientData)object, Monitor_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } /** * This is a sample command for testing the straight line netlink * probe code. */ static int Probe_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { #if 0 // Commenting out for now - netlink code should be external to this func // Yes, this is intentional, it may get removed later pid_t pid __attribute((unused)) = getpid(); int result; // Discover interfaces and add objects int fd; fd = socket( AF_NETLINK, SOCK_RAW, NETLINK_ROUTE ); if ( socket < 0 ) { log_err( "Probe socket() failed, %s", strerror(errno) ); exit( 1 ); } // setup sndbuf and rcvbuf // bind struct sockaddr_nl address; memset( &address, 0, sizeof(address) ); address.nl_family = AF_NETLINK; address.nl_groups = 0; if ( bind(fd, (struct sockaddr *)&address, sizeof(address)) < 0 ) { log_err( "Probe bind() failed, %s", strerror(errno) ); exit( 1 ); } // send request struct { struct nlmsghdr nlh; struct rtgenmsg g; } nlreq; memset( &nlreq, 0, sizeof(nlreq) ); nlreq.nlh.nlmsg_len = sizeof(nlreq); nlreq.nlh.nlmsg_type = RTM_GETLINK; nlreq.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; nlreq.nlh.nlmsg_pid = 0; nlreq.nlh.nlmsg_seq = 34; nlreq.g.rtgen_family = AF_PACKET; result = sendto( fd, (void*)&nlreq, sizeof(nlreq), 0, (struct sockaddr *)&address, sizeof(address) ); if ( result < 0 ) { log_err( "Probe sendto() failed, %s", strerror(errno) ); exit( 1 ); } // Now I am going to reuse the "address" structure for receiving the responses. memset( &address, 0, sizeof(address) ); char msg_buf[16384]; struct iovec iov; memset( &iov, 0, sizeof(iov) ); iov.iov_base = msg_buf; struct msghdr rsp_msg; rsp_msg.msg_name = &address; rsp_msg.msg_namelen = sizeof(address); rsp_msg.msg_iov = &iov; rsp_msg.msg_iovlen = 1; // loop around waiting for netlink messages // for each response create an interface object for (;;) { unsigned int status; struct nlmsghdr *h; iov.iov_len = sizeof(msg_buf); status = recvmsg( fd, &rsp_msg, 0 ); if ( status < 0 ) { if ( errno == EINTR ) { // normally just continue here printf( "interupted recvmsg\n" ); } else { log_err( "Probe recvmsg() failed, %s", strerror(errno) ); } continue; } if ( status == 0 ) { printf( "finished nlmsgs\n" ); break; } printf( "status=%d\n", status ); h = (struct nlmsghdr *)msg_buf; while ( NLMSG_OK(h, status) ) { if ( h->nlmsg_type == NLMSG_DONE ) { printf( "NLMSG_DONE\n" ); goto finish; } if ( h->nlmsg_type == NLMSG_ERROR ) { printf( "NLMSG_ERROR\n" ); goto finish; } /* if ( h->nlmsg_flags & NLM_F_MULTI ) { printf( "NLM_F_MULTI\n" ); } else { printf( "not:NLM_F_MULTI\n" ); } */ printf( "process nlmsg type=%d flags=0x%08x pid=%d seq=%d\n", h->nlmsg_type, h->nlmsg_flags, h->nlmsg_pid, h->nlmsg_seq ); { // type is in linux/if_arp.h -- flags are in linux/if.h NetLink::NewLink *m = new NetLink::NewLink( h ); Network::Interface *ii = new Network::Interface( interp, m ); if ( ii == NULL ) { // remove -Wall warning by using this } } h = NLMSG_NEXT( h, status ); } printf( "finished with this message (notOK)\n" ); if ( rsp_msg.msg_flags & MSG_TRUNC ) { printf( "msg truncated" ); continue; } if ( status != 0 ) { printf( "remnant\n" ); } } finish: close( fd ); // Discover Bridges // Search for existing bridges and create objects for them // and for each object create a command // the bridge commands should remain in the Network namespace // -- maybe no -- create in whichever namespace you need #endif return TCL_OK; } /** */ bool NetworkMonitor_Module( Tcl_Interp *interp ) { Tcl_Command command; Tcl_Namespace *ns = Tcl_CreateNamespace(interp, "Network", (ClientData)0, NULL); if ( ns == NULL ) { return false; } if ( Tcl_LinkVar(interp, "Network::debug", (char *)&debug, TCL_LINK_INT) != TCL_OK ) { log_err( "failed to link Network::debug" ); exit( 1 ); } command = Tcl_CreateObjCommand(interp, "Network::Monitor", Monitor_cmd, (ClientData)0, NULL); if ( command == NULL ) { // logger ?? want to report TCL Error return false; } command = Tcl_CreateObjCommand(interp, "Network::Probe", Probe_cmd, (ClientData)0, NULL); if ( command == NULL ) { // logger ?? want to report TCL Error return false; } return true; } app_init( NetworkMonitor_Module ); /* vim: set autoindent expandtab sw=4 : */ <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <entt/core/hashed_string.hpp> #include <entt/meta/context.hpp> #include <entt/meta/factory.hpp> struct base {}; struct clazz: base { clazz() = default; clazz(int) : clazz{} {} clazz(char, int) : clazz{} {} int func(int v) { return (value = v); } int cfunc(int v) const { return v; } static void move_to_bucket(const clazz &instance) { bucket = instance.value; } int value{}; static inline int bucket{}; }; struct local_only {}; struct argument { argument(int val) : value{val} {} int get() const { return value; } int get_mul() const { return value * 2; } private: int value{}; }; class MetaContext: public ::testing::Test { void init_global_context() { using namespace entt::literals; entt::meta<int>() .data<global_marker>("marker"_hs); entt::meta<argument>() .conv<&argument::get>(); entt::meta<clazz>() .type("foo"_hs) .prop("prop"_hs, prop_value) .ctor<int>() .data<&clazz::value>("value"_hs) .data<&clazz::value>("rw"_hs) .func<&clazz::func>("func"_hs); } void init_local_context() { using namespace entt::literals; entt::meta<int>(context) .data<local_marker>("marker"_hs); entt::meta<local_only>(context) .type("quux"_hs); entt::meta<argument>(context) .conv<&argument::get_mul>(); entt::meta<clazz>(context) .type("bar"_hs) .prop("prop"_hs, prop_value) .base<base>() .ctor<char, int>() .dtor<&clazz::move_to_bucket>() .data<nullptr, &clazz::value>("value"_hs) .data<&clazz::value>("rw"_hs) .func<&clazz::cfunc>("func"_hs); } public: void SetUp() override { init_global_context(); init_local_context(); clazz::bucket = bucket_value; } void TearDown() override { entt::meta_reset(context); entt::meta_reset(); } protected: static constexpr int global_marker = 1; static constexpr int local_marker = 42; static constexpr int bucket_value = 99; static constexpr int prop_value = 3; entt::meta_ctx context{}; }; TEST_F(MetaContext, Resolve) { using namespace entt::literals; ASSERT_TRUE(entt::resolve<clazz>()); ASSERT_TRUE(entt::resolve<clazz>(context)); ASSERT_TRUE(entt::resolve<local_only>()); ASSERT_TRUE(entt::resolve<local_only>(context)); ASSERT_TRUE(entt::resolve(entt::type_id<clazz>())); ASSERT_TRUE(entt::resolve(context, entt::type_id<clazz>())); ASSERT_FALSE(entt::resolve(entt::type_id<local_only>())); ASSERT_TRUE(entt::resolve(context, entt::type_id<local_only>())); ASSERT_TRUE(entt::resolve("foo"_hs)); ASSERT_FALSE(entt::resolve(context, "foo"_hs)); ASSERT_FALSE(entt::resolve("bar"_hs)); ASSERT_TRUE(entt::resolve(context, "bar"_hs)); ASSERT_FALSE(entt::resolve("quux"_hs)); ASSERT_TRUE(entt::resolve(context, "quux"_hs)); ASSERT_EQ((std::distance(entt::resolve().cbegin(), entt::resolve().cend())), 3); ASSERT_EQ((std::distance(entt::resolve(context).cbegin(), entt::resolve(context).cend())), 4); } TEST_F(MetaContext, MetaType) { using namespace entt::literals; const auto global = entt::resolve<clazz>(); const auto local = entt::resolve<clazz>(context); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_NE(global, local); ASSERT_EQ(global, entt::resolve("foo"_hs)); ASSERT_EQ(local, entt::resolve(context, "bar"_hs)); ASSERT_EQ(global.id(), "foo"_hs); ASSERT_EQ(local.id(), "bar"_hs); } TEST_F(MetaContext, MetaBase) { const auto global = entt::resolve<clazz>(); const auto local = entt::resolve<clazz>(context); ASSERT_EQ((std::distance(global.base().cbegin(), global.base().cend())), 0); ASSERT_EQ((std::distance(local.base().cbegin(), local.base().cend())), 1); ASSERT_EQ(local.base().cbegin()->second.info(), entt::type_id<base>()); ASSERT_FALSE(entt::resolve(entt::type_id<base>())); ASSERT_FALSE(entt::resolve(context, entt::type_id<base>())); } TEST_F(MetaContext, MetaData) { using namespace entt::literals; const auto global = entt::resolve<clazz>().data("value"_hs); const auto local = entt::resolve<clazz>(context).data("value"_hs); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_FALSE(global.is_const()); ASSERT_TRUE(local.is_const()); ASSERT_EQ(global.type().data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.type().data("marker"_hs).get({}).cast<int>(), local_marker); const auto grw = entt::resolve<clazz>().data("rw"_hs); const auto lrw = entt::resolve<clazz>(context).data("rw"_hs); ASSERT_EQ(grw.arg(0).data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(lrw.arg(0).data("marker"_hs).get({}).cast<int>(), local_marker); clazz instance{}; const argument value{2}; grw.set(instance, value); ASSERT_EQ(instance.value, value.get()); lrw.set(entt::meta_handle{context, instance}, entt::meta_any{context, value}); ASSERT_EQ(instance.value, value.get_mul()); } TEST_F(MetaContext, MetaFunc) { using namespace entt::literals; const auto global = entt::resolve<clazz>().func("func"_hs); const auto local = entt::resolve<clazz>(context).func("func"_hs); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_FALSE(global.is_const()); ASSERT_TRUE(local.is_const()); ASSERT_EQ(global.arg(0).data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.arg(0).data("marker"_hs).get({}).cast<int>(), local_marker); ASSERT_EQ(global.ret().data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.ret().data("marker"_hs).get({}).cast<int>(), local_marker); clazz instance{}; const argument value{2}; ASSERT_NE(instance.value, value.get()); ASSERT_EQ(global.invoke(instance, value).cast<int>(), value.get()); ASSERT_EQ(instance.value, value.get()); ASSERT_NE(instance.value, value.get_mul()); ASSERT_EQ(local.invoke(entt::meta_handle{context, instance}, entt::meta_any{context, value}).cast<int>(), value.get_mul()); ASSERT_NE(instance.value, value.get_mul()); } TEST_F(MetaContext, MetaCtor) { const auto global = entt::resolve<clazz>(); const auto local = entt::resolve<clazz>(context); ASSERT_TRUE(global.construct()); ASSERT_TRUE(local.construct()); ASSERT_TRUE(global.construct(0)); ASSERT_FALSE(local.construct(0)); ASSERT_FALSE(global.construct('c', 0)); ASSERT_TRUE(local.construct('c', 0)); } TEST_F(MetaContext, MetaConv) { argument value{2}; auto global = entt::forward_as_meta(value); auto local = entt::forward_as_meta(context, value); ASSERT_TRUE(global.allow_cast<int>()); ASSERT_TRUE(local.allow_cast<int>()); ASSERT_EQ(global.cast<int>(), value.get()); ASSERT_EQ(local.cast<int>(), value.get_mul()); } TEST_F(MetaContext, MetaDtor) { auto global = entt::resolve<clazz>().construct(); auto local = entt::resolve<clazz>(context).construct(); ASSERT_EQ(clazz::bucket, bucket_value); global.reset(); ASSERT_EQ(clazz::bucket, bucket_value); local.reset(); ASSERT_NE(clazz::bucket, bucket_value); } TEST_F(MetaContext, MetaProp) { using namespace entt::literals; const auto global = entt::resolve<clazz>().prop("prop"_hs); const auto local = entt::resolve<clazz>(context).prop("prop"_hs); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_EQ(global.value().type(), entt::resolve<int>()); ASSERT_EQ(local.value().type(), entt::resolve<int>(context)); ASSERT_EQ(global.value().cast<int>(), prop_value); ASSERT_EQ(local.value().cast<int>(), prop_value); ASSERT_EQ(global.value().type().data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.value().type().data("marker"_hs).get({}).cast<int>(), local_marker); } TEST_F(MetaContext, MetaTemplate) { // TODO } TEST_F(MetaContext, MetaPointer) { // TODO } TEST_F(MetaContext, MetaAssociativeContainer) { // TODO } TEST_F(MetaContext, MetaSequenceContainer) { // TODO } TEST_F(MetaContext, MetaAny) { // TODO } TEST_F(MetaContext, MetaHandle) { // TODO } TEST_F(MetaContext, ForwardAsMeta) { // TODO } TEST_F(MetaContext, ContextMix) { // TODO } <commit_msg>meta: context aware meta template<commit_after>#include <gtest/gtest.h> #include <entt/core/hashed_string.hpp> #include <entt/meta/context.hpp> #include <entt/meta/factory.hpp> #include <entt/meta/template.hpp> struct base {}; struct clazz: base { clazz() = default; clazz(int) : clazz{} {} clazz(char, int) : clazz{} {} int func(int v) { return (value = v); } int cfunc(int v) const { return v; } static void move_to_bucket(const clazz &instance) { bucket = instance.value; } int value{}; static inline int bucket{}; }; struct local_only {}; struct argument { argument(int val) : value{val} {} int get() const { return value; } int get_mul() const { return value * 2; } private: int value{}; }; template<typename...> struct template_clazz {}; class MetaContext: public ::testing::Test { void init_global_context() { using namespace entt::literals; entt::meta<int>() .data<global_marker>("marker"_hs); entt::meta<argument>() .conv<&argument::get>(); entt::meta<clazz>() .type("foo"_hs) .prop("prop"_hs, prop_value) .ctor<int>() .data<&clazz::value>("value"_hs) .data<&clazz::value>("rw"_hs) .func<&clazz::func>("func"_hs); entt::meta<template_clazz<int>>() .type("template"_hs); } void init_local_context() { using namespace entt::literals; entt::meta<int>(context) .data<local_marker>("marker"_hs); entt::meta<local_only>(context) .type("quux"_hs); entt::meta<argument>(context) .conv<&argument::get_mul>(); entt::meta<clazz>(context) .type("bar"_hs) .prop("prop"_hs, prop_value) .base<base>() .ctor<char, int>() .dtor<&clazz::move_to_bucket>() .data<nullptr, &clazz::value>("value"_hs) .data<&clazz::value>("rw"_hs) .func<&clazz::cfunc>("func"_hs); entt::meta<template_clazz<int, char>>(context) .type("template"_hs); } public: void SetUp() override { init_global_context(); init_local_context(); clazz::bucket = bucket_value; } void TearDown() override { entt::meta_reset(context); entt::meta_reset(); } protected: static constexpr int global_marker = 1; static constexpr int local_marker = 42; static constexpr int bucket_value = 99; static constexpr int prop_value = 3; entt::meta_ctx context{}; }; TEST_F(MetaContext, Resolve) { using namespace entt::literals; ASSERT_TRUE(entt::resolve<clazz>()); ASSERT_TRUE(entt::resolve<clazz>(context)); ASSERT_TRUE(entt::resolve<local_only>()); ASSERT_TRUE(entt::resolve<local_only>(context)); ASSERT_TRUE(entt::resolve(entt::type_id<clazz>())); ASSERT_TRUE(entt::resolve(context, entt::type_id<clazz>())); ASSERT_FALSE(entt::resolve(entt::type_id<local_only>())); ASSERT_TRUE(entt::resolve(context, entt::type_id<local_only>())); ASSERT_TRUE(entt::resolve("foo"_hs)); ASSERT_FALSE(entt::resolve(context, "foo"_hs)); ASSERT_FALSE(entt::resolve("bar"_hs)); ASSERT_TRUE(entt::resolve(context, "bar"_hs)); ASSERT_FALSE(entt::resolve("quux"_hs)); ASSERT_TRUE(entt::resolve(context, "quux"_hs)); ASSERT_EQ((std::distance(entt::resolve().cbegin(), entt::resolve().cend())), 4); ASSERT_EQ((std::distance(entt::resolve(context).cbegin(), entt::resolve(context).cend())), 5); } TEST_F(MetaContext, MetaType) { using namespace entt::literals; const auto global = entt::resolve<clazz>(); const auto local = entt::resolve<clazz>(context); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_NE(global, local); ASSERT_EQ(global, entt::resolve("foo"_hs)); ASSERT_EQ(local, entt::resolve(context, "bar"_hs)); ASSERT_EQ(global.id(), "foo"_hs); ASSERT_EQ(local.id(), "bar"_hs); } TEST_F(MetaContext, MetaBase) { const auto global = entt::resolve<clazz>(); const auto local = entt::resolve<clazz>(context); ASSERT_EQ((std::distance(global.base().cbegin(), global.base().cend())), 0); ASSERT_EQ((std::distance(local.base().cbegin(), local.base().cend())), 1); ASSERT_EQ(local.base().cbegin()->second.info(), entt::type_id<base>()); ASSERT_FALSE(entt::resolve(entt::type_id<base>())); ASSERT_FALSE(entt::resolve(context, entt::type_id<base>())); } TEST_F(MetaContext, MetaData) { using namespace entt::literals; const auto global = entt::resolve<clazz>().data("value"_hs); const auto local = entt::resolve<clazz>(context).data("value"_hs); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_FALSE(global.is_const()); ASSERT_TRUE(local.is_const()); ASSERT_EQ(global.type().data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.type().data("marker"_hs).get({}).cast<int>(), local_marker); const auto grw = entt::resolve<clazz>().data("rw"_hs); const auto lrw = entt::resolve<clazz>(context).data("rw"_hs); ASSERT_EQ(grw.arg(0u).data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(lrw.arg(0u).data("marker"_hs).get({}).cast<int>(), local_marker); clazz instance{}; const argument value{2}; grw.set(instance, value); ASSERT_EQ(instance.value, value.get()); lrw.set(entt::meta_handle{context, instance}, entt::meta_any{context, value}); ASSERT_EQ(instance.value, value.get_mul()); } TEST_F(MetaContext, MetaFunc) { using namespace entt::literals; const auto global = entt::resolve<clazz>().func("func"_hs); const auto local = entt::resolve<clazz>(context).func("func"_hs); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_FALSE(global.is_const()); ASSERT_TRUE(local.is_const()); ASSERT_EQ(global.arg(0u).data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.arg(0u).data("marker"_hs).get({}).cast<int>(), local_marker); ASSERT_EQ(global.ret().data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.ret().data("marker"_hs).get({}).cast<int>(), local_marker); clazz instance{}; const argument value{2}; ASSERT_NE(instance.value, value.get()); ASSERT_EQ(global.invoke(instance, value).cast<int>(), value.get()); ASSERT_EQ(instance.value, value.get()); ASSERT_NE(instance.value, value.get_mul()); ASSERT_EQ(local.invoke(entt::meta_handle{context, instance}, entt::meta_any{context, value}).cast<int>(), value.get_mul()); ASSERT_NE(instance.value, value.get_mul()); } TEST_F(MetaContext, MetaCtor) { const auto global = entt::resolve<clazz>(); const auto local = entt::resolve<clazz>(context); ASSERT_TRUE(global.construct()); ASSERT_TRUE(local.construct()); ASSERT_TRUE(global.construct(0)); ASSERT_FALSE(local.construct(0)); ASSERT_FALSE(global.construct('c', 0)); ASSERT_TRUE(local.construct('c', 0)); } TEST_F(MetaContext, MetaConv) { argument value{2}; auto global = entt::forward_as_meta(value); auto local = entt::forward_as_meta(context, value); ASSERT_TRUE(global.allow_cast<int>()); ASSERT_TRUE(local.allow_cast<int>()); ASSERT_EQ(global.cast<int>(), value.get()); ASSERT_EQ(local.cast<int>(), value.get_mul()); } TEST_F(MetaContext, MetaDtor) { auto global = entt::resolve<clazz>().construct(); auto local = entt::resolve<clazz>(context).construct(); ASSERT_EQ(clazz::bucket, bucket_value); global.reset(); ASSERT_EQ(clazz::bucket, bucket_value); local.reset(); ASSERT_NE(clazz::bucket, bucket_value); } TEST_F(MetaContext, MetaProp) { using namespace entt::literals; const auto global = entt::resolve<clazz>().prop("prop"_hs); const auto local = entt::resolve<clazz>(context).prop("prop"_hs); ASSERT_TRUE(global); ASSERT_TRUE(local); ASSERT_EQ(global.value().type(), entt::resolve<int>()); ASSERT_EQ(local.value().type(), entt::resolve<int>(context)); ASSERT_EQ(global.value().cast<int>(), prop_value); ASSERT_EQ(local.value().cast<int>(), prop_value); ASSERT_EQ(global.value().type().data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.value().type().data("marker"_hs).get({}).cast<int>(), local_marker); } TEST_F(MetaContext, MetaTemplate) { using namespace entt::literals; const auto global = entt::resolve("template"_hs); const auto local = entt::resolve(context, "template"_hs); ASSERT_TRUE(global.is_template_specialization()); ASSERT_TRUE(local.is_template_specialization()); ASSERT_EQ(global.template_arity(), 1u); ASSERT_EQ(local.template_arity(), 2u); ASSERT_EQ(global.template_arg(0u), entt::resolve<int>()); ASSERT_EQ(local.template_arg(0u), entt::resolve<int>(context)); ASSERT_EQ(local.template_arg(1u), entt::resolve<char>(context)); ASSERT_EQ(global.template_arg(0u).data("marker"_hs).get({}).cast<int>(), global_marker); ASSERT_EQ(local.template_arg(0u).data("marker"_hs).get({}).cast<int>(), local_marker); } TEST_F(MetaContext, MetaPointer) { // TODO } TEST_F(MetaContext, MetaAssociativeContainer) { // TODO } TEST_F(MetaContext, MetaSequenceContainer) { // TODO } TEST_F(MetaContext, MetaAny) { // TODO } TEST_F(MetaContext, MetaHandle) { // TODO } TEST_F(MetaContext, ForwardAsMeta) { // TODO } TEST_F(MetaContext, ContextMix) { // TODO } <|endoftext|>
<commit_before>/* -*- mode:C++; indent-tabs-mode:nil; -*- */ /* MyThOS: The Many-Threads Operating System * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright 2016 Randolf Rotta, Robert Kuban, and contributors, BTU Cottbus-Senftenberg */ #pragma once #include <cstdint> #include "util/assert.hh" #include "util/LinkedList.hh" #include "async/IResult.hh" #include "async/NestedMonitorDelegating.hh" #include "objects/IKernelObject.hh" #include "objects/CapEntry.hh" #include "objects/DeleteBroadcast.hh" #include "objects/mlog.hh" #include "objects/ops.hh" namespace mythos { class RevokeOperation : public IResult<void> , protected IDeleter { public: typedef IResult<void> result_t; typedef LinkedList<IKernelObject*> queue_t; RevokeOperation(async::NestedMonitorDelegating& m) : monitor(m), _res(nullptr) {} RevokeOperation(const RevokeOperation&) = delete; virtual ~RevokeOperation() {} void deleteObject(LinkedList<IKernelObject*>::Queueable& obj) override { _deleteQueue.push(&obj); } optional<void> deleteEntry(CapEntry& entry) override; // @todo use pointer? void revokeCap(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded) { monitor.request(t, [=, &entry](Tasklet* t) { MLOG_ERROR(mlog::cap, "revoke cap called"); _revoke(t, res, entry, guarded); }); } void deleteCap(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded) { monitor.request(t, [=, &entry](Tasklet* t) { _delete(t, res, entry, guarded); }); } virtual void response(Tasklet* t, optional<void> res) override { ASSERT(res.isSuccess()); monitor.response(t, [=](Tasklet* t) { MLOG_DETAIL(mlog::cap, "received broadcast or delete response"); _deleteObject(t); }); } bool acquire() { auto result = !_lock.test_and_set(); //MLOG_ERROR(mlog::cap, "acquire ops =>", result); return result; } void release() { //MLOG_ERROR(mlog::cap, "release ops"); _lock.clear(); }; private: void _revoke(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded); void _delete(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded); void _deleteObject(Tasklet* t); optional<void> _delete(CapEntry* root, Cap rootCap); bool _startTraversal(CapEntry* root, Cap rootCap); CapEntry* _findLockedLeaf(CapEntry* root); void _startAsyncDelete(Tasklet* t); private: async::NestedMonitorDelegating& monitor; /// FIFO ... this way, every object apears before its parents /// and can be deleted (avoids intraprocess/object snychronization) /// children might be in another list, but these can be waited for /// as another operation objects will delete them. queue_t _deleteQueue; result_t* _res; IKernelObject* _guarded; Error _result; std::atomic_flag _lock; }; } // namespace mythos <commit_msg>Fixed uninitialized flag.<commit_after>/* -*- mode:C++; indent-tabs-mode:nil; -*- */ /* MyThOS: The Many-Threads Operating System * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright 2016 Randolf Rotta, Robert Kuban, and contributors, BTU Cottbus-Senftenberg */ #pragma once #include <cstdint> #include "util/assert.hh" #include "util/LinkedList.hh" #include "async/IResult.hh" #include "async/NestedMonitorDelegating.hh" #include "objects/IKernelObject.hh" #include "objects/CapEntry.hh" #include "objects/DeleteBroadcast.hh" #include "objects/mlog.hh" #include "objects/ops.hh" namespace mythos { class RevokeOperation : public IResult<void> , protected IDeleter { public: typedef IResult<void> result_t; typedef LinkedList<IKernelObject*> queue_t; RevokeOperation(async::NestedMonitorDelegating& m) : monitor(m), _res(nullptr) {} RevokeOperation(const RevokeOperation&) = delete; virtual ~RevokeOperation() {} void deleteObject(LinkedList<IKernelObject*>::Queueable& obj) override { _deleteQueue.push(&obj); } optional<void> deleteEntry(CapEntry& entry) override; // @todo use pointer? void revokeCap(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded) { monitor.request(t, [=, &entry](Tasklet* t) { MLOG_ERROR(mlog::cap, "revoke cap called"); _revoke(t, res, entry, guarded); }); } void deleteCap(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded) { monitor.request(t, [=, &entry](Tasklet* t) { _delete(t, res, entry, guarded); }); } virtual void response(Tasklet* t, optional<void> res) override { ASSERT(res.isSuccess()); monitor.response(t, [=](Tasklet* t) { MLOG_DETAIL(mlog::cap, "received broadcast or delete response"); _deleteObject(t); }); } bool acquire() { auto result = !_lock.test_and_set(); MLOG_ERROR(mlog::cap, DVAR(this), "acquire ops =>", result); return result; } void release() { MLOG_ERROR(mlog::cap, DVAR(this), "release ops"); _lock.clear(); }; private: void _revoke(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded); void _delete(Tasklet* t, result_t* res, CapEntry& entry, IKernelObject* guarded); void _deleteObject(Tasklet* t); optional<void> _delete(CapEntry* root, Cap rootCap); bool _startTraversal(CapEntry* root, Cap rootCap); CapEntry* _findLockedLeaf(CapEntry* root); void _startAsyncDelete(Tasklet* t); private: async::NestedMonitorDelegating& monitor; /// FIFO ... this way, every object apears before its parents /// and can be deleted (avoids intraprocess/object snychronization) /// children might be in another list, but these can be waited for /// as another operation objects will delete them. queue_t _deleteQueue; result_t* _res; IKernelObject* _guarded; Error _result; std::atomic_flag _lock = ATOMIC_FLAG_INIT; }; } // namespace mythos <|endoftext|>
<commit_before>#include "app_fontrenderer.h" #include <stdexcept> #ifndef NDEBUG #include <stdio.h> #endif #include "common.h" #include "snippets.h" FontRenderWorker::Job::Job(size_t index, size_t & count_rendered) : index(index), count_rendered(count_rendered) { } FontRenderWorker::FontRenderWorker(HWND h, std::vector<font::EnumFontInfo> & ff) : hwnd(h), fonts(ff) { InitializeCriticalSection(&mutex); queue_event = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (!queue_event) throw std::runtime_error("FontRenderWorker :" " unable to create queue_event"); } FontRenderWorker::~FontRenderWorker() { CloseHandle(queue_event); DeleteCriticalSection(&mutex); } void FontRenderWorker::task() { static bool needs_flip = true; bool skip = true; size_t index = 0; size_t * count_rendered = nullptr; #ifndef NDEBUG size_t jobs_dropped = 0; #endif #ifdef FR_DEBUG_TICK_DELAY printf(" [ font renderer %08x ] tick\n", (size_t) this); #endif EnterCriticalSection(&mutex); if (!jobs.empty()) { if (!msg || !*msg) msg = "rendering..."; else msg = "still rendering... ( stop scrolling! :)"; #ifdef FR_DEBUG_SLOW_DRAW PostMessage(hwnd, WM_FR_MESSAGE_UPDATE, 0, 0); #endif #ifndef NDEBUG jobs_dropped = jobs.size() - 1; #endif skip = false; index = jobs.back().index; count_rendered = &jobs.back().count_rendered; jobs.clear(); } LeaveCriticalSection(&mutex); if (skip) { msg = ""; if (needs_flip) { offscreen.flip(); needs_flip = false; } #ifdef FR_DEBUG_TICK_DELAY WaitForSingleObject(queue_event, FR_DEBUG_TICK_DELAY); #else WaitForSingleObject(queue_event, INFINITE); #endif return; } #ifndef NDEBUG printf(" [ jobs dropped ] %d\n", jobs_dropped); #endif #ifdef FR_DEBUG_SLOW_DRAW Sleep(FR_DEBUG_SLOW_DRAW); #endif offscreen.clear(COLOR_MENU); draw_fonts(hwnd, offscreen.handle, fonts, index, *count_rendered); // offscreen.flip(); needs_flip = true; } void FontRenderWorker::on_parent_resize() { HDC hdc = GetDC(hwnd); offscreen = window::BackgroundDC(hdc); ReleaseDC(hwnd, hdc); } void FontRenderWorker::queue(size_t index, size_t & count_rendered) { EnterCriticalSection(&mutex); jobs.push_back(Job(index, count_rendered)); LeaveCriticalSection(&mutex); SetEvent(queue_event); } char const * FontRenderWorker::get_msg() const { return msg ? msg : ""; } void draw_frame(HDC dc, RECT & rc, SIZE const & frame_extra, COLORREF color=0, bool rc_adjust=false) { HBRUSH const frame_brush = (HBRUSH) GetStockObject(DC_BRUSH); InflateRect(&rc, frame_extra.cx, frame_extra.cy); SetDCBrushColor(dc, color); FrameRect(dc, &rc, frame_brush); if (!rc_adjust) InflateRect(&rc, -frame_extra.cx, -frame_extra.cy); } void draw_fonts(HWND h, HDC dc, std::vector<font::EnumFontInfo> & ff, size_t skip, size_t & count_rendered) { snippets::RowIndexDrawer rid; SIZE const frame_extra = {3, 2}; SIZE const padding = {8, 8}; SIZE client_size; lib::window::get_inner_size(h, client_size); SIZE const cutoff = { client_size.cx - padding.cx, client_size.cy - padding.cy}; int const gap_row = 0; int const gap_prefix = 16; int const min_step_y = rid.get_height(1.5f); count_rendered = 0; int y = padding.cy; for (size_t i=skip; i<ff.size(); ++i, ++count_rendered) { char const * text = (char const *) ff[i].elfe.elfFullName; size_t const text_len = strlen(text); lib::font::EnumFontInfoLoader efil(dc, ff[i]); RECT rc = {padding.cx, y, 0, 0}; snippets::calc_text_rect_2(rc, dc, text, text_len); int const next_row_height = (rc.bottom - rc.top) + frame_extra.cy * 2; int const step_y = next_row_height - 1; int const step_y_true = step_y > min_step_y ? step_y : min_step_y; int const next_y = y + step_y_true + gap_row; if (next_y > cutoff.cy) break; RECT tr = {padding.cx, y, 0, 0}; rid.draw(dc, tr, i+1, "%4d"); int const offset = tr.right + gap_prefix; OffsetRect(&rc, offset, 0); // SetBkColor(dc, RGB(10,10,10)); // SetTextColor(dc, RGB(200,200,200)); TextOut(dc, rc.left, rc.top, text, text_len); draw_frame(dc, rc, frame_extra, RGB(100,100,100)); y = next_y; } } <commit_msg>v-centered the row index<commit_after>#include "app_fontrenderer.h" #include <stdexcept> #ifndef NDEBUG #include <stdio.h> #endif #include "common.h" #include "snippets.h" FontRenderWorker::Job::Job(size_t index, size_t & count_rendered) : index(index), count_rendered(count_rendered) { } FontRenderWorker::FontRenderWorker(HWND h, std::vector<font::EnumFontInfo> & ff) : hwnd(h), fonts(ff) { InitializeCriticalSection(&mutex); queue_event = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (!queue_event) throw std::runtime_error("FontRenderWorker :" " unable to create queue_event"); } FontRenderWorker::~FontRenderWorker() { CloseHandle(queue_event); DeleteCriticalSection(&mutex); } void FontRenderWorker::task() { static bool needs_flip = true; bool skip = true; size_t index = 0; size_t * count_rendered = nullptr; #ifndef NDEBUG size_t jobs_dropped = 0; #endif #ifdef FR_DEBUG_TICK_DELAY printf(" [ font renderer %08x ] tick\n", (size_t) this); #endif EnterCriticalSection(&mutex); if (!jobs.empty()) { if (!msg || !*msg) msg = "rendering..."; else msg = "still rendering... ( stop scrolling! :)"; #ifdef FR_DEBUG_SLOW_DRAW PostMessage(hwnd, WM_FR_MESSAGE_UPDATE, 0, 0); #endif #ifndef NDEBUG jobs_dropped = jobs.size() - 1; #endif skip = false; index = jobs.back().index; count_rendered = &jobs.back().count_rendered; jobs.clear(); } LeaveCriticalSection(&mutex); if (skip) { msg = ""; if (needs_flip) { offscreen.flip(); needs_flip = false; } #ifdef FR_DEBUG_TICK_DELAY WaitForSingleObject(queue_event, FR_DEBUG_TICK_DELAY); #else WaitForSingleObject(queue_event, INFINITE); #endif return; } #ifndef NDEBUG printf(" [ jobs dropped ] %d\n", jobs_dropped); #endif #ifdef FR_DEBUG_SLOW_DRAW Sleep(FR_DEBUG_SLOW_DRAW); #endif offscreen.clear(COLOR_MENU); draw_fonts(hwnd, offscreen.handle, fonts, index, *count_rendered); // offscreen.flip(); needs_flip = true; } void FontRenderWorker::on_parent_resize() { HDC hdc = GetDC(hwnd); offscreen = window::BackgroundDC(hdc); ReleaseDC(hwnd, hdc); } void FontRenderWorker::queue(size_t index, size_t & count_rendered) { EnterCriticalSection(&mutex); jobs.push_back(Job(index, count_rendered)); LeaveCriticalSection(&mutex); SetEvent(queue_event); } char const * FontRenderWorker::get_msg() const { return msg ? msg : ""; } void draw_frame(HDC dc, RECT & rc, SIZE const & frame_extra, COLORREF color=0, bool rc_adjust=false) { HBRUSH const frame_brush = (HBRUSH) GetStockObject(DC_BRUSH); InflateRect(&rc, frame_extra.cx, frame_extra.cy); SetDCBrushColor(dc, color); FrameRect(dc, &rc, frame_brush); if (!rc_adjust) InflateRect(&rc, -frame_extra.cx, -frame_extra.cy); } void draw_fonts(HWND h, HDC dc, std::vector<font::EnumFontInfo> & ff, size_t skip, size_t & count_rendered) { snippets::RowIndexDrawer rid; SIZE const frame_extra = {3, 2}; SIZE const padding = {8, 8}; SIZE client_size; lib::window::get_inner_size(h, client_size); SIZE const cutoff = { client_size.cx - padding.cx, client_size.cy - padding.cy}; int const gap_row = 0; int const gap_prefix = 16; int const min_step_y = rid.get_height(1.5f); count_rendered = 0; int y = padding.cy; for (size_t i=skip; i<ff.size(); ++i, ++count_rendered) { char const * text = (char const *) ff[i].elfe.elfFullName; size_t const text_len = strlen(text); lib::font::EnumFontInfoLoader efil(dc, ff[i]); RECT rc = {padding.cx, y, 0, 0}; snippets::calc_text_rect_2(rc, dc, text, text_len); int const next_row_height = (rc.bottom - rc.top) + frame_extra.cy * 2; int const step_y = next_row_height - 1; int const step_y_true = step_y > min_step_y ? step_y : min_step_y; int const next_y = y + step_y_true + gap_row; if (next_y > cutoff.cy) break; int const oc = (next_row_height - rid.get_height()) >> 1; RECT tr = {padding.cx, y + oc, 0, 0}; rid.draw(dc, tr, i+1, "%4d"); int const offset = tr.right + gap_prefix; OffsetRect(&rc, offset, 0); // SetBkColor(dc, RGB(10,10,10)); // SetTextColor(dc, RGB(200,200,200)); TextOut(dc, rc.left, rc.top, text, text_len); draw_frame(dc, rc, frame_extra, RGB(100,100,100)); y = next_y; } } <|endoftext|>
<commit_before>/*********************************************************************** filename: SamplesFrameworkBase.cpp created: 24/9/2004 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "SamplesFrameworkBase.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUISamplesConfig.h" // includes for renderer selector classes #if defined( __WIN32__ ) || defined( _WIN32 ) # include "Win32CEGuiRendererSelector.h" #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) # ifdef CEGUI_SAMPLES_USE_GTK2 # include "GTK2CEGuiRendererSelector.h" # else # include "CLICEGuiRendererSelector.h" # endif #elif defined(__APPLE__) # include "MacCEGuiRendererSelector.h" #endif // includes for application types #ifdef CEGUI_SAMPLES_USE_OGRE # include "CEGuiOgreBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_OPENGL # include "CEGuiOpenGLBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_OPENGL3 # include "CEGuiOpenGL3BaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT # include "CEGuiIrrlichtBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_DIRECTFB # include "CEGuiDirectFBBaseApplication.h" #endif #if defined( __WIN32__ ) || defined( _WIN32 ) # ifdef CEGUI_SAMPLES_USE_DIRECT3D8 # include "CEGuiD3D81BaseApplication.h" # endif # ifdef CEGUI_SAMPLES_USE_DIRECT3D9 # include "CEGuiD3D9BaseApplication.h" # endif # ifdef CEGUI_SAMPLES_USE_DIRECT3D10 # include "CEGuiD3D10BaseApplication.h" # endif # ifdef CEGUI_SAMPLES_USE_DIRECT3D11 # include "CEGuiD3D11BaseApplication.h" # endif #endif // now we include the base CEGuiBaseApplication just in case someone has managed to // get this far without any of the renderers. This ensures the framework will build, // although there will be no renderers available for selection in the samples. #include "CEGuiBaseApplication.h" #include "CEGUI/CEGUI.h" // Include iostream if not on windows. #if defined( __WIN32__ ) || defined( _WIN32 ) #else # include <iostream> #endif /************************************************************************* Constructor *************************************************************************/ SamplesFrameworkBase::SamplesFrameworkBase() : d_rendererSelector(0), d_baseApp(0), d_quitting(false), d_appWindowWidth(0), d_appWindowHeight(0) {} /************************************************************************* Destructor *************************************************************************/ SamplesFrameworkBase::~SamplesFrameworkBase() { if (d_baseApp) { d_baseApp->cleanup(); delete d_baseApp; } if (d_rendererSelector) { delete d_rendererSelector; } } /************************************************************************* Application entry point *************************************************************************/ int SamplesFrameworkBase::run() { CEGUI_TRY { if(runApplication()) cleanup(); } CEGUI_CATCH (CEGUI::Exception& exc) { outputExceptionMessage(exc.getMessage().c_str()); } CEGUI_CATCH (std::exception& exc) { outputExceptionMessage(exc.what()); } CEGUI_CATCH (const char* exc) { outputExceptionMessage(exc); } CEGUI_CATCH(...) { outputExceptionMessage("Unknown exception was caught!"); } return 0; } /************************************************************************* Start the SamplesFramework application *************************************************************************/ bool SamplesFrameworkBase::runApplication() { // Setup renderer selection dialog for Win32 #if defined( __WIN32__ ) || defined( _WIN32 ) d_rendererSelector = new Win32CEGuiRendererSelector; // enable renderer types supported for Win32 #ifdef CEGUI_SAMPLES_USE_DIRECT3D8 d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D9 d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D10 d_rendererSelector->setRendererAvailability(Direct3D10GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D11 d_rendererSelector->setRendererAvailability(Direct3D11GuiRendererType); #endif #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) // decide which method to use for renderer selection # ifdef CEGUI_SAMPLES_USE_GTK2 d_rendererSelector = new GTK2CEGuiRendererSelector(); # else d_rendererSelector = new CLICEGuiRendererSelector(); # endif #elif defined(__APPLE__) d_rendererSelector = new MacCEGuiRendererSelector(); #endif // enable available renderer types #ifdef CEGUI_SAMPLES_USE_OGRE d_rendererSelector->setRendererAvailability(OgreGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_OPENGL d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_OPENGL3 d_rendererSelector->setRendererAvailability(OpenGL3GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECTFB d_rendererSelector->setRendererAvailability(DirectFBGuiRendererType); #endif // get selection from user if (d_rendererSelector->invokeDialog()) { // create appropriate application type based upon users selection switch(d_rendererSelector->getSelectedRendererType()) { #ifdef CEGUI_SAMPLES_USE_OGRE case OgreGuiRendererType: { CEGuiOgreBaseApplication* ogreBaseApp = new CEGuiOgreBaseApplication(); if(!ogreBaseApp->isInitialised()) return false; d_baseApp = ogreBaseApp; } break; #endif #if defined( __WIN32__ ) || defined( _WIN32 ) #ifdef CEGUI_SAMPLES_USE_DIRECT3D8 case Direct3D81GuiRendererType: d_baseApp = new CEGuiD3D81BaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D9 case Direct3D9GuiRendererType: d_baseApp = new CEGuiD3D9BaseApplication(); break; #endif // DX9 #ifdef CEGUI_SAMPLES_USE_DIRECT3D10 case Direct3D10GuiRendererType: d_baseApp = new CEGuiD3D10BaseApplication(); break; #endif // DX10 #ifdef CEGUI_SAMPLES_USE_DIRECT3D11 case Direct3D11GuiRendererType: d_baseApp = new CEGuiD3D11BaseApplication(); break; #endif // DX11 #endif // Win32 #ifdef CEGUI_SAMPLES_USE_OPENGL case OpenGLGuiRendererType: d_baseApp = new CEGuiOpenGLBaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_OPENGL3 case OpenGL3GuiRendererType: d_baseApp = new CEGuiOpenGL3BaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT case IrrlichtGuiRendererType: d_baseApp = new CEGuiIrrlichtBaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_DIRECTFB case DirectFBGuiRendererType: d_baseApp = new CEGuiDirectFBBaseApplication(); break; #endif default: CEGUI_THROW(CEGUI::GenericException("No renderer was selected!")); break; } // run the base application (which sets up the demo via 'this' and runs it. if (d_baseApp->execute(this)) { // signal that app initialised and ran return true; } // sample app did not initialise, delete the object. delete d_baseApp; d_baseApp = 0; } // delete renderer selector object delete d_rendererSelector; d_rendererSelector = 0; // signal app did not initialise and run. return false; } /************************************************************************* Cleanup the sample application. *************************************************************************/ void SamplesFrameworkBase::cleanup() { delete d_baseApp; d_baseApp = 0; if (d_rendererSelector) { delete d_rendererSelector; d_rendererSelector = 0; } } /************************************************************************* Output a message to the user in some OS independant way. *************************************************************************/ void SamplesFrameworkBase::outputExceptionMessage(const char* message) { #if defined(__WIN32__) || defined(_WIN32) MessageBoxA(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR); #else std::cout << "An exception was thrown within the sample framework:" << std::endl; std::cout << message << std::endl; #endif } void SamplesFrameworkBase::setQuitting(bool quit) { d_quitting = quit; } bool SamplesFrameworkBase::isQuitting() { return d_quitting; } void SamplesFrameworkBase::setApplicationWindowSize(int width, int height) { d_appWindowWidth = width; d_appWindowHeight = height; }<commit_msg>Fix 'incomplete definition' warning/error on some compilers in Samples Framework<commit_after>/*********************************************************************** filename: SamplesFrameworkBase.cpp created: 24/9/2004 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "SamplesFrameworkBase.h" #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUISamplesConfig.h" // includes for renderer selector classes #if defined( __WIN32__ ) || defined( _WIN32 ) # include "Win32CEGuiRendererSelector.h" #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) # ifdef CEGUI_SAMPLES_USE_GTK2 # include "GTK2CEGuiRendererSelector.h" # else # include "CLICEGuiRendererSelector.h" # endif #elif defined(__APPLE__) # include "MacCEGuiRendererSelector.h" #endif // includes for application types #ifdef CEGUI_SAMPLES_USE_OGRE # include "CEGuiOgreBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_OPENGL # include "CEGuiOpenGLBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_OPENGL3 # include "CEGuiOpenGL3BaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT # include "CEGuiIrrlichtBaseApplication.h" #endif #ifdef CEGUI_SAMPLES_USE_DIRECTFB # include "CEGuiDirectFBBaseApplication.h" #endif #if defined( __WIN32__ ) || defined( _WIN32 ) # ifdef CEGUI_SAMPLES_USE_DIRECT3D8 # include "CEGuiD3D81BaseApplication.h" # endif # ifdef CEGUI_SAMPLES_USE_DIRECT3D9 # include "CEGuiD3D9BaseApplication.h" # endif # ifdef CEGUI_SAMPLES_USE_DIRECT3D10 # include "CEGuiD3D10BaseApplication.h" # endif # ifdef CEGUI_SAMPLES_USE_DIRECT3D11 # include "CEGuiD3D11BaseApplication.h" # endif #endif // now we include the base CEGuiBaseApplication just in case someone has managed to // get this far without any of the renderers. This ensures the framework will build, // although there will be no renderers available for selection in the samples. #include "CEGuiBaseApplication.h" #include "CEGUI/CEGUI.h" #include "CEGuiRendererSelector.h" // Include iostream if not on windows. #if defined( __WIN32__ ) || defined( _WIN32 ) #else # include <iostream> #endif /************************************************************************* Constructor *************************************************************************/ SamplesFrameworkBase::SamplesFrameworkBase() : d_rendererSelector(0), d_baseApp(0), d_quitting(false), d_appWindowWidth(0), d_appWindowHeight(0) {} /************************************************************************* Destructor *************************************************************************/ SamplesFrameworkBase::~SamplesFrameworkBase() { if (d_baseApp) { d_baseApp->cleanup(); delete d_baseApp; } if (d_rendererSelector) { delete d_rendererSelector; } } /************************************************************************* Application entry point *************************************************************************/ int SamplesFrameworkBase::run() { CEGUI_TRY { if(runApplication()) cleanup(); } CEGUI_CATCH (CEGUI::Exception& exc) { outputExceptionMessage(exc.getMessage().c_str()); } CEGUI_CATCH (std::exception& exc) { outputExceptionMessage(exc.what()); } CEGUI_CATCH (const char* exc) { outputExceptionMessage(exc); } CEGUI_CATCH(...) { outputExceptionMessage("Unknown exception was caught!"); } return 0; } /************************************************************************* Start the SamplesFramework application *************************************************************************/ bool SamplesFrameworkBase::runApplication() { // Setup renderer selection dialog for Win32 #if defined( __WIN32__ ) || defined( _WIN32 ) d_rendererSelector = new Win32CEGuiRendererSelector; // enable renderer types supported for Win32 #ifdef CEGUI_SAMPLES_USE_DIRECT3D8 d_rendererSelector->setRendererAvailability(Direct3D81GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D9 d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D10 d_rendererSelector->setRendererAvailability(Direct3D10GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D11 d_rendererSelector->setRendererAvailability(Direct3D11GuiRendererType); #endif #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) // decide which method to use for renderer selection # ifdef CEGUI_SAMPLES_USE_GTK2 d_rendererSelector = new GTK2CEGuiRendererSelector(); # else d_rendererSelector = new CLICEGuiRendererSelector(); # endif #elif defined(__APPLE__) d_rendererSelector = new MacCEGuiRendererSelector(); #endif // enable available renderer types #ifdef CEGUI_SAMPLES_USE_OGRE d_rendererSelector->setRendererAvailability(OgreGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_OPENGL d_rendererSelector->setRendererAvailability(OpenGLGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_OPENGL3 d_rendererSelector->setRendererAvailability(OpenGL3GuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType); #endif #ifdef CEGUI_SAMPLES_USE_DIRECTFB d_rendererSelector->setRendererAvailability(DirectFBGuiRendererType); #endif // get selection from user if (d_rendererSelector->invokeDialog()) { // create appropriate application type based upon users selection switch(d_rendererSelector->getSelectedRendererType()) { #ifdef CEGUI_SAMPLES_USE_OGRE case OgreGuiRendererType: { CEGuiOgreBaseApplication* ogreBaseApp = new CEGuiOgreBaseApplication(); if(!ogreBaseApp->isInitialised()) return false; d_baseApp = ogreBaseApp; } break; #endif #if defined( __WIN32__ ) || defined( _WIN32 ) #ifdef CEGUI_SAMPLES_USE_DIRECT3D8 case Direct3D81GuiRendererType: d_baseApp = new CEGuiD3D81BaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_DIRECT3D9 case Direct3D9GuiRendererType: d_baseApp = new CEGuiD3D9BaseApplication(); break; #endif // DX9 #ifdef CEGUI_SAMPLES_USE_DIRECT3D10 case Direct3D10GuiRendererType: d_baseApp = new CEGuiD3D10BaseApplication(); break; #endif // DX10 #ifdef CEGUI_SAMPLES_USE_DIRECT3D11 case Direct3D11GuiRendererType: d_baseApp = new CEGuiD3D11BaseApplication(); break; #endif // DX11 #endif // Win32 #ifdef CEGUI_SAMPLES_USE_OPENGL case OpenGLGuiRendererType: d_baseApp = new CEGuiOpenGLBaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_OPENGL3 case OpenGL3GuiRendererType: d_baseApp = new CEGuiOpenGL3BaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_IRRLICHT case IrrlichtGuiRendererType: d_baseApp = new CEGuiIrrlichtBaseApplication(); break; #endif #ifdef CEGUI_SAMPLES_USE_DIRECTFB case DirectFBGuiRendererType: d_baseApp = new CEGuiDirectFBBaseApplication(); break; #endif default: CEGUI_THROW(CEGUI::GenericException("No renderer was selected!")); break; } // run the base application (which sets up the demo via 'this' and runs it. if (d_baseApp->execute(this)) { // signal that app initialised and ran return true; } // sample app did not initialise, delete the object. delete d_baseApp; d_baseApp = 0; } // delete renderer selector object delete d_rendererSelector; d_rendererSelector = 0; // signal app did not initialise and run. return false; } /************************************************************************* Cleanup the sample application. *************************************************************************/ void SamplesFrameworkBase::cleanup() { delete d_baseApp; d_baseApp = 0; if (d_rendererSelector) { delete d_rendererSelector; d_rendererSelector = 0; } } /************************************************************************* Output a message to the user in some OS independant way. *************************************************************************/ void SamplesFrameworkBase::outputExceptionMessage(const char* message) { #if defined(__WIN32__) || defined(_WIN32) MessageBoxA(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR); #else std::cout << "An exception was thrown within the sample framework:" << std::endl; std::cout << message << std::endl; #endif } void SamplesFrameworkBase::setQuitting(bool quit) { d_quitting = quit; } bool SamplesFrameworkBase::isQuitting() { return d_quitting; } void SamplesFrameworkBase::setApplicationWindowSize(int width, int height) { d_appWindowWidth = width; d_appWindowHeight = height; }<|endoftext|>
<commit_before>/* docker-script: run script files inside Docker containers Copyright (c) 2017, Adam Rehn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "NvidiaDockerImages.h" #include "Utility.h" #include <stdexcept> #include <iostream> #include <fstream> #include <cstdlib> #include <vector> using std::ifstream; using std::vector; using std::clog; using std::endl; int main (int argc, char* argv[]) { //Check that a script file was specified if (argc > 1) { try { //Parse CLI arguments, keeping docker-script options separate from script options bool interactive = true; bool verboseOutput = false; bool enableDebugging = false; string trailingArgs = ""; for (int i = 2; i < argc; ++i) { string currArg = string(argv[i]); if (currArg == "---verbose") { verboseOutput = true; } else if (currArg == "---debug") { enableDebugging = true; } else if (currArg == "---non-interactive") { interactive = false; } else { trailingArgs += "\"" + currArg + "\" "; } } //Attempt to open the script file string scriptPath = argv[1]; ifstream script(scriptPath.c_str()); if (script.is_open() == false) { throw std::runtime_error("failed to open script file \"" + scriptPath + "\""); } //Attempt to read the second shebang line in the script file string shebang = ""; std::getline(script, shebang); std::getline(script, shebang); if (script.fail()) { throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\""); } //Verify that the shebang line is well-formed size_t spacePos = shebang.find(" "); if (shebang.substr(0,2) != "#!" || spacePos == string::npos) { throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\""); } //Parse the shebang line string dockerImage = shebang.substr(2, spacePos - 2); string interpreter = shebang.substr(spacePos + 1); //Determine the full path to the script file scriptPath = Utility::realPath(scriptPath); //Extract the directory and filename components of the script's path, as well as our current working directory string scriptFile = Utility::baseName(scriptPath); string scriptDir = Utility::dirName(scriptPath); string workingDir = Utility::cwd(); //Extract the docker image name, without trailing tag name string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":")); //If the specified docker image (or the specific image and tag combination) requires //nvidia-docker, we invoke nvidia-docker instead of regular docker string docker = "docker"; auto nvDockerImages = NvidiaDockerImages::getList(); if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) { docker = "nvidia-docker"; } //If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker` if (string(argv[0]) == "nvidia-docker-script") { docker = "nvidia-docker"; } //Build the `docker run` command string command = docker + " run " + string("\"-v") + scriptDir + ":/scriptdir\" " + string("\"-v") + workingDir + ":/workingdir\" " + string((enableDebugging == true) ? "--privileged=true " : "") + string("--workdir=/workingdir ") + string("-e \"HOST_CWD=") + workingDir + "\" " + string((interactive == true) ? "-ti" : "") + string("--rm --entrypoint=\"\" ") + string("\"") + dockerImage + "\" " + string("\"") + interpreter + "\" " + string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs; //If verbose output was requested, display diagnostic information if (verboseOutput == true) { clog << "Docker image: " << dockerImage << endl; clog << "Interpreter: " << interpreter << endl; clog << "Script path: " << scriptPath << endl; clog << "Script basename: " << scriptFile << endl; clog << "Script dirname: " << scriptDir << endl; clog << "Working directory: " << workingDir << endl; clog << "Trailing arguments: " << trailingArgs << endl; clog << endl << "Docker command:" << endl << command << endl << endl; } //Invoke docker return system(command.c_str()); } catch (std::runtime_error& e) { clog << "Error: " << e.what() << endl << endl; return 1; } } else { clog << "Usage:" << endl << argv[0] << " <SCRIPT> [---verbose] [---debug] [args for script]" << endl << endl; clog << "The first line of the script file should be a normal Unix shebang line." << endl; clog << "The second line of the script file should be:" << endl; clog << "#!<IMAGE> <INTERPRETER>" << endl << endl; } return 0; } <commit_msg>Fix missing whitespace in interactive mode arguments<commit_after>/* docker-script: run script files inside Docker containers Copyright (c) 2017, Adam Rehn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "NvidiaDockerImages.h" #include "Utility.h" #include <stdexcept> #include <iostream> #include <fstream> #include <cstdlib> #include <vector> using std::ifstream; using std::vector; using std::clog; using std::endl; int main (int argc, char* argv[]) { //Check that a script file was specified if (argc > 1) { try { //Parse CLI arguments, keeping docker-script options separate from script options bool interactive = true; bool verboseOutput = false; bool enableDebugging = false; string trailingArgs = ""; for (int i = 2; i < argc; ++i) { string currArg = string(argv[i]); if (currArg == "---verbose") { verboseOutput = true; } else if (currArg == "---debug") { enableDebugging = true; } else if (currArg == "---non-interactive") { interactive = false; } else { trailingArgs += "\"" + currArg + "\" "; } } //Attempt to open the script file string scriptPath = argv[1]; ifstream script(scriptPath.c_str()); if (script.is_open() == false) { throw std::runtime_error("failed to open script file \"" + scriptPath + "\""); } //Attempt to read the second shebang line in the script file string shebang = ""; std::getline(script, shebang); std::getline(script, shebang); if (script.fail()) { throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\""); } //Verify that the shebang line is well-formed size_t spacePos = shebang.find(" "); if (shebang.substr(0,2) != "#!" || spacePos == string::npos) { throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\""); } //Parse the shebang line string dockerImage = shebang.substr(2, spacePos - 2); string interpreter = shebang.substr(spacePos + 1); //Determine the full path to the script file scriptPath = Utility::realPath(scriptPath); //Extract the directory and filename components of the script's path, as well as our current working directory string scriptFile = Utility::baseName(scriptPath); string scriptDir = Utility::dirName(scriptPath); string workingDir = Utility::cwd(); //Extract the docker image name, without trailing tag name string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":")); //If the specified docker image (or the specific image and tag combination) requires //nvidia-docker, we invoke nvidia-docker instead of regular docker string docker = "docker"; auto nvDockerImages = NvidiaDockerImages::getList(); if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) { docker = "nvidia-docker"; } //If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker` if (string(argv[0]) == "nvidia-docker-script") { docker = "nvidia-docker"; } //Build the `docker run` command string command = docker + " run " + string("\"-v") + scriptDir + ":/scriptdir\" " + string("\"-v") + workingDir + ":/workingdir\" " + string((enableDebugging == true) ? "--privileged=true " : "") + string("--workdir=/workingdir ") + string("-e \"HOST_CWD=") + workingDir + "\" " + string((interactive == true) ? "-ti " : "") + string("--rm --entrypoint=\"\" ") + string("\"") + dockerImage + "\" " + string("\"") + interpreter + "\" " + string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs; //If verbose output was requested, display diagnostic information if (verboseOutput == true) { clog << "Docker image: " << dockerImage << endl; clog << "Interpreter: " << interpreter << endl; clog << "Script path: " << scriptPath << endl; clog << "Script basename: " << scriptFile << endl; clog << "Script dirname: " << scriptDir << endl; clog << "Working directory: " << workingDir << endl; clog << "Trailing arguments: " << trailingArgs << endl; clog << endl << "Docker command:" << endl << command << endl << endl; } //Invoke docker return system(command.c_str()); } catch (std::runtime_error& e) { clog << "Error: " << e.what() << endl << endl; return 1; } } else { clog << "Usage:" << endl << argv[0] << " <SCRIPT> [---verbose] [---debug] [args for script]" << endl << endl; clog << "The first line of the script file should be a normal Unix shebang line." << endl; clog << "The second line of the script file should be:" << endl; clog << "#!<IMAGE> <INTERPRETER>" << endl << endl; } return 0; } <|endoftext|>
<commit_before>#ifndef __PROCESS_PROTOBUF_HPP__ #define __PROCESS_PROTOBUF_HPP__ #include <glog/logging.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <vector> #include <tr1/unordered_map> #include <process/process.hpp> // Provides a "protocol buffer process", which is to say a subclass of // Process that allows you to install protocol buffer handlers in // addition to normal message and HTTP handlers. Then you can simply // send around protocol buffer objects which will get passed to the // appropriate handlers. namespace google { namespace protobuf { // Type conversions helpful for changing between protocol buffer types // and standard C++ types (for parameters). template <typename T> const T& convert(const T& t) { return t; } template <typename T> std::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items) { std::vector<T> result; for (int i = 0; i < items.size(); i++) { result.push_back(items.Get(i)); } return result; } }} // namespace google { namespace protobuf { template <typename T> class ProtobufProcess : public process::Process<T> { public: ProtobufProcess(const std::string& id = "") : process::Process<T>(id) {} virtual ~ProtobufProcess() {} protected: virtual void operator () () { // TODO(benh): Shouldn't we just make Process::serve be a virtual // function, and then the one we get from process::Process will be // sufficient? do { if (serve() == process::TERMINATE) break; } while (true); } void send(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); process::Process<T>::send(to, message.GetTypeName(), data.data(), data.size()); } using process::Process<T>::send; const std::string& serve(double secs = 0, bool once = false) { do { const std::string& name = process::Process<T>::serve(secs, once); if (protobufHandlers.count(name) > 0) { protobufHandlers[name](process::Process<T>::body()); } else { return name; } } while (!once); } template <typename M> void installProtobufHandler(void (T::*method)()) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&ProtobufProcess<T>::handler0, t, method, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C> void installProtobufHandler(void (T::*method)(P1C), P1 (M::*param1)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler1<M, P1, P1C>, t, method, param1, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C> void installProtobufHandler(void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler2<M, P1, P1C, P2, P2C>, t, method, p1, p2, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler3<M, P1, P1C, P2, P2C, P3, P3C>, t, method, p1, p2, p3, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler4<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C>, t, method, p1, p2, p3, p4, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler5<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C, P5, P5C>, t, method, p1, p2, p3, p4, p5, std::tr1::placeholders::_1); delete m; } private: static void handler0(T* t, void (T::*method)(), const std::string& data) { (t->*method)(); } template <typename M, typename P1, typename P1C> static void handler1(T* t, void (T::*method)(P1C), P1 (M::*p1)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C> static void handler2(T* t, void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> static void handler3(T* t, void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> static void handler4(T* t, void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> static void handler5(T* t, void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)()), google::protobuf::convert((&m->*p5)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } typedef std::tr1::function<void(const std::string&)> handler; std::tr1::unordered_map<std::string, handler> protobufHandlers; }; namespace process { inline void post(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); post(to, message.GetTypeName(), data.data(), data.size()); } template <typename Request, typename Response> class RequestResponseProcess : public ProtobufProcess<RequestResponseProcess<Request, Response> > { public: RequestResponseProcess( const UPID& _pid, const Request& _request, const Promise<Response>& _promise) : pid(_pid), request(_request), promise(_promise) {} protected: virtual void operator () () { send(pid, request); ProcessBase::receive(); Response response; CHECK(ProcessBase::name() == response.GetTypeName()); response.ParseFromString(ProcessBase::body()); promise.set(response); } private: const UPID pid; const Request request; Promise<Response> promise; }; template <typename Request, typename Response> struct Protocol { Future<Response> operator () (const UPID& pid, const Request& request) { Future<Response> future; Promise<Response> promise; promise.associate(future); RequestResponseProcess<Request, Response>* process = new RequestResponseProcess<Request, Response>(pid, request, promise); spawn(process, true); return future; } }; } // namespace process { #endif // __PROCESS_PROTOBUF_HPP__ <commit_msg>Removed Protocol and RequestResultProcess for now.<commit_after>#ifndef __PROCESS_PROTOBUF_HPP__ #define __PROCESS_PROTOBUF_HPP__ #include <glog/logging.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <vector> #include <tr1/unordered_map> #include <process/process.hpp> // Provides a "protocol buffer process", which is to say a subclass of // Process that allows you to install protocol buffer handlers in // addition to normal message and HTTP handlers. Then you can simply // send around protocol buffer objects which will get passed to the // appropriate handlers. namespace google { namespace protobuf { // Type conversions helpful for changing between protocol buffer types // and standard C++ types (for parameters). template <typename T> const T& convert(const T& t) { return t; } template <typename T> std::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items) { std::vector<T> result; for (int i = 0; i < items.size(); i++) { result.push_back(items.Get(i)); } return result; } }} // namespace google { namespace protobuf { template <typename T> class ProtobufProcess : public process::Process<T> { public: ProtobufProcess(const std::string& id = "") : process::Process<T>(id) {} virtual ~ProtobufProcess() {} protected: virtual void operator () () { // TODO(benh): Shouldn't we just make Process::serve be a virtual // function, and then the one we get from process::Process will be // sufficient? do { if (serve() == process::TERMINATE) break; } while (true); } void send(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); process::Process<T>::send(to, message.GetTypeName(), data.data(), data.size()); } using process::Process<T>::send; const std::string& serve(double secs = 0, bool once = false) { do { const std::string& name = process::Process<T>::serve(secs, once); if (protobufHandlers.count(name) > 0) { protobufHandlers[name](process::Process<T>::body()); } else { return name; } } while (!once); } template <typename M> void installProtobufHandler(void (T::*method)()) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&ProtobufProcess<T>::handler0, t, method, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C> void installProtobufHandler(void (T::*method)(P1C), P1 (M::*param1)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler1<M, P1, P1C>, t, method, param1, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C> void installProtobufHandler(void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler2<M, P1, P1C, P2, P2C>, t, method, p1, p2, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler3<M, P1, P1C, P2, P2C, P3, P3C>, t, method, p1, p2, p3, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler4<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C>, t, method, p1, p2, p3, p4, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler5<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C, P5, P5C>, t, method, p1, p2, p3, p4, p5, std::tr1::placeholders::_1); delete m; } private: static void handler0(T* t, void (T::*method)(), const std::string& data) { (t->*method)(); } template <typename M, typename P1, typename P1C> static void handler1(T* t, void (T::*method)(P1C), P1 (M::*p1)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C> static void handler2(T* t, void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> static void handler3(T* t, void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> static void handler4(T* t, void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> static void handler5(T* t, void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)()), google::protobuf::convert((&m->*p5)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } typedef std::tr1::function<void(const std::string&)> handler; std::tr1::unordered_map<std::string, handler> protobufHandlers; }; namespace process { inline void post(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); post(to, message.GetTypeName(), data.data(), data.size()); } // template <typename Request, typename Response> // class RequestResponseProcess // : public ProtobufProcess<RequestResponseProcess<Request, Response> > // { // public: // RequestResponseProcess( // const UPID& _pid, // const Request& _request, // const Promise<Response>& _promise) // : pid(_pid), request(_request), promise(_promise) {} // protected: // virtual void operator () () // { // send(pid, request); // ProcessBase::receive(); // Response response; // CHECK(ProcessBase::name() == response.GetTypeName()); // response.ParseFromString(ProcessBase::body()); // promise.set(response); // } // private: // const UPID pid; // const Request request; // Promise<Response> promise; // }; // template <typename Request, typename Response> // struct Protocol // { // Future<Response> operator () (const UPID& pid, const Request& request) // { // Future<Response> future; // Promise<Response> promise; // promise.associate(future); // RequestResponseProcess<Request, Response>* process = // new RequestResponseProcess<Request, Response>(pid, request, promise); // spawn(process, true); // return future; // } // }; } // namespace process { #endif // __PROCESS_PROTOBUF_HPP__ <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/scoped_ptr.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "views/controls/textfield/textfield_views_model.h" #include "views/test/test_views_delegate.h" #include "views/views_delegate.h" namespace views { #define EXPECT_STR_EQ(ascii, utf16) \ EXPECT_EQ(ASCIIToWide(ascii), UTF16ToWide(utf16)) TEST(TextfieldViewsModelTest, EditString) { TextfieldViewsModel model; // append two strings model.Append(ASCIIToUTF16("HILL")); EXPECT_STR_EQ("HILL", model.text()); model.Append(ASCIIToUTF16("WORLD")); EXPECT_STR_EQ("HILLWORLD", model.text()); // Insert "E" to make hello model.MoveCursorRight(false); model.Insert('E'); EXPECT_STR_EQ("HEILLWORLD", model.text()); // Replace "I" with "L" model.Replace('L'); EXPECT_STR_EQ("HELLLWORLD", model.text()); model.Replace('L'); model.Replace('O'); EXPECT_STR_EQ("HELLOWORLD", model.text()); // Delete 6th char "W", then delete 5th char O" EXPECT_EQ(5U, model.cursor_pos()); EXPECT_TRUE(model.Delete()); EXPECT_STR_EQ("HELLOORLD", model.text()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(4U, model.cursor_pos()); EXPECT_STR_EQ("HELLORLD", model.text()); // Move the cursor to start. backspace should fail. model.MoveCursorToStart(false); EXPECT_FALSE(model.Backspace()); EXPECT_STR_EQ("HELLORLD", model.text()); // Move the cursor to the end. delete should fail. model.MoveCursorToEnd(false); EXPECT_FALSE(model.Delete()); EXPECT_STR_EQ("HELLORLD", model.text()); // but backspace should work. EXPECT_TRUE(model.Backspace()); EXPECT_STR_EQ("HELLORL", model.text()); } TEST(TextfieldViewsModelTest, EmptyString) { TextfieldViewsModel model; EXPECT_EQ(string16(), model.text()); EXPECT_EQ(string16(), model.GetSelectedText()); EXPECT_EQ(string16(), model.GetVisibleText()); model.MoveCursorLeft(true); EXPECT_EQ(0U, model.cursor_pos()); model.MoveCursorRight(true); EXPECT_EQ(0U, model.cursor_pos()); EXPECT_EQ(string16(), model.GetSelectedText()); EXPECT_FALSE(model.Delete()); EXPECT_FALSE(model.Backspace()); } TEST(TextfieldViewsModelTest, Selection) { TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO")); model.MoveCursorRight(false); model.MoveCursorRight(true); EXPECT_STR_EQ("E", model.GetSelectedText()); model.MoveCursorRight(true); EXPECT_STR_EQ("EL", model.GetSelectedText()); model.MoveCursorToStart(true); EXPECT_STR_EQ("H", model.GetSelectedText()); model.MoveCursorToEnd(true); EXPECT_STR_EQ("ELLO", model.GetSelectedText()); model.ClearSelection(); EXPECT_EQ(string16(), model.GetSelectedText()); model.SelectAll(); EXPECT_STR_EQ("HELLO", model.GetSelectedText()); // Select and move cursor model.MoveCursorTo(1U, false); model.MoveCursorTo(3U, true); EXPECT_STR_EQ("EL", model.GetSelectedText()); model.MoveCursorLeft(false); EXPECT_EQ(1U, model.cursor_pos()); model.MoveCursorTo(1U, false); model.MoveCursorTo(3U, true); model.MoveCursorRight(false); EXPECT_EQ(3U, model.cursor_pos()); // Select all and move cursor model.SelectAll(); model.MoveCursorLeft(false); EXPECT_EQ(0U, model.cursor_pos()); model.SelectAll(); model.MoveCursorRight(false); EXPECT_EQ(5U, model.cursor_pos()); } TEST(TextfieldViewsModelTest, SelectionAndEdit) { TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO")); model.MoveCursorRight(false); model.MoveCursorRight(true); model.MoveCursorRight(true); // select "EL" EXPECT_TRUE(model.Backspace()); EXPECT_STR_EQ("HLO", model.text()); model.Append(ASCIIToUTF16("ILL")); model.MoveCursorRight(true); model.MoveCursorRight(true); // select "LO" EXPECT_TRUE(model.Delete()); EXPECT_STR_EQ("HILL", model.text()); EXPECT_EQ(1U, model.cursor_pos()); model.MoveCursorRight(true); // select "I" model.Insert('E'); EXPECT_STR_EQ("HELL", model.text()); model.MoveCursorToStart(false); model.MoveCursorRight(true); // select "H" model.Replace('B'); EXPECT_STR_EQ("BELL", model.text()); model.MoveCursorToEnd(false); model.MoveCursorLeft(true); model.MoveCursorLeft(true); // select ">LL" model.Replace('E'); EXPECT_STR_EQ("BEE", model.text()); } TEST(TextfieldViewsModelTest, Password) { TextfieldViewsModel model; model.set_is_password(true); model.Append(ASCIIToUTF16("HELLO")); EXPECT_STR_EQ("*****", model.GetVisibleText()); EXPECT_STR_EQ("HELLO", model.text()); EXPECT_TRUE(model.Delete()); EXPECT_STR_EQ("****", model.GetVisibleText()); EXPECT_STR_EQ("ELLO", model.text()); EXPECT_EQ(0U, model.cursor_pos()); model.SelectAll(); EXPECT_STR_EQ("ELLO", model.GetSelectedText()); EXPECT_EQ(0U, model.cursor_pos()); model.Insert('X'); EXPECT_STR_EQ("*", model.GetVisibleText()); EXPECT_STR_EQ("X", model.text()); } TEST(TextfieldViewsModelTest, Word) { TextfieldViewsModel model; model.Append( ASCIIToUTF16("The answer to Life, the Universe, and Everything")); model.MoveCursorToNextWord(false); EXPECT_EQ(3U, model.cursor_pos()); model.MoveCursorToNextWord(false); EXPECT_EQ(10U, model.cursor_pos()); model.MoveCursorToNextWord(false); model.MoveCursorToNextWord(false); EXPECT_EQ(18U, model.cursor_pos()); // Should passes the non word char ',' model.MoveCursorToNextWord(true); EXPECT_EQ(23U, model.cursor_pos()); EXPECT_STR_EQ(", the", model.GetSelectedText()); // Move to the end. model.MoveCursorToNextWord(true); model.MoveCursorToNextWord(true); model.MoveCursorToNextWord(true); EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText()); // Should be safe to go next word at the end. model.MoveCursorToNextWord(true); EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText()); model.Insert('2'); EXPECT_EQ(19U, model.cursor_pos()); // Now backwards. model.MoveCursorLeft(false); // leave 2. model.MoveCursorToPreviousWord(true); EXPECT_EQ(14U, model.cursor_pos()); EXPECT_STR_EQ("Life", model.GetSelectedText()); model.MoveCursorToPreviousWord(true); EXPECT_STR_EQ("to Life", model.GetSelectedText()); model.MoveCursorToPreviousWord(true); model.MoveCursorToPreviousWord(true); model.MoveCursorToPreviousWord(true); // Select to the begining. EXPECT_STR_EQ("The answer to Life", model.GetSelectedText()); // Should be safe to go pervious word at the begining. model.MoveCursorToPreviousWord(true); EXPECT_STR_EQ("The answer to Life", model.GetSelectedText()); model.Replace('4'); EXPECT_EQ(string16(), model.GetSelectedText()); EXPECT_STR_EQ("42", model.GetVisibleText()); } TEST(TextfieldViewsModelTest, TextFragment) { TextfieldViewsModel model; TextfieldViewsModel::TextFragments fragments; // Empty string model.GetFragments(&fragments); EXPECT_EQ(1U, fragments.size()); fragments.clear(); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(0U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); // Some string model.Append(ASCIIToUTF16("Hello world")); model.GetFragments(&fragments); EXPECT_EQ(1U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(11U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); // Select 1st word model.MoveCursorToNextWord(true); model.GetFragments(&fragments); EXPECT_EQ(2U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(5U, fragments[0].end); EXPECT_TRUE(fragments[0].selected); EXPECT_EQ(5U, fragments[1].begin); EXPECT_EQ(11U, fragments[1].end); EXPECT_FALSE(fragments[1].selected); // Select empty string model.ClearSelection(); model.MoveCursorRight(true); model.GetFragments(&fragments); EXPECT_EQ(3U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(5U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); EXPECT_EQ(5U, fragments[1].begin); EXPECT_EQ(6U, fragments[1].end); EXPECT_TRUE(fragments[1].selected); EXPECT_EQ(6U, fragments[2].begin); EXPECT_EQ(11U, fragments[2].end); EXPECT_FALSE(fragments[2].selected); // Select to the end. model.MoveCursorToEnd(true); model.GetFragments(&fragments); EXPECT_EQ(2U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(5U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); EXPECT_EQ(5U, fragments[1].begin); EXPECT_EQ(11U, fragments[1].end); EXPECT_TRUE(fragments[1].selected); } TEST(TextfieldViewsModelTest, SetText) { TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO")); model.MoveCursorToEnd(false); model.SetText(ASCIIToUTF16("GOODBYE")); EXPECT_STR_EQ("GOODBYE", model.text()); EXPECT_EQ(5U, model.cursor_pos()); model.SelectAll(); EXPECT_STR_EQ("GOODBYE", model.GetSelectedText()); // Selection move the current pos to the begining. EXPECT_EQ(0U, model.cursor_pos()); model.MoveCursorToEnd(false); EXPECT_EQ(7U, model.cursor_pos()); model.SetText(ASCIIToUTF16("BYE")); EXPECT_EQ(3U, model.cursor_pos()); EXPECT_EQ(string16(), model.GetSelectedText()); model.SetText(ASCIIToUTF16("")); EXPECT_EQ(0U, model.cursor_pos()); } TEST(TextfieldViewsModelTest, Clipboard) { scoped_ptr<TestViewsDelegate> test_views_delegate(new TestViewsDelegate()); views::ViewsDelegate::views_delegate = test_views_delegate.get(); ui::Clipboard* clipboard = views::ViewsDelegate::views_delegate->GetClipboard(); string16 initial_clipboard_text; clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &initial_clipboard_text); string16 clipboard_text; TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO WORLD")); model.MoveCursorToEnd(false); // Test for cut: Empty selection. EXPECT_FALSE(model.Cut()); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ(UTF16ToUTF8(initial_clipboard_text), clipboard_text); EXPECT_STR_EQ("HELLO WORLD", model.text()); EXPECT_EQ(11U, model.cursor_pos()); // Test for cut: Non-empty selection. model.MoveCursorToPreviousWord(true); EXPECT_TRUE(model.Cut()); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("WORLD", clipboard_text); EXPECT_STR_EQ("HELLO ", model.text()); EXPECT_EQ(6U, model.cursor_pos()); // Test for copy: Empty selection. model.Copy(); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("WORLD", clipboard_text); EXPECT_STR_EQ("HELLO ", model.text()); EXPECT_EQ(6U, model.cursor_pos()); // Test for copy: Non-empty selection. model.Append(ASCIIToUTF16("HELLO WORLD")); model.SelectAll(); model.Copy(); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text); EXPECT_STR_EQ("HELLO HELLO WORLD", model.text()); EXPECT_EQ(0U, model.cursor_pos()); // Test for paste. model.ClearSelection(); model.MoveCursorToEnd(false); model.MoveCursorToPreviousWord(true); EXPECT_TRUE(model.Paste()); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text); EXPECT_STR_EQ("HELLO HELLO HELLO HELLO WORLD", model.text()); EXPECT_EQ(29U, model.cursor_pos()); } } // namespace views <commit_msg>Revert 71170 - Delete test view delegate at end of test<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/scoped_ptr.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "views/controls/textfield/textfield_views_model.h" #include "views/test/test_views_delegate.h" #include "views/views_delegate.h" namespace views { #define EXPECT_STR_EQ(ascii, utf16) \ EXPECT_EQ(ASCIIToWide(ascii), UTF16ToWide(utf16)) TEST(TextfieldViewsModelTest, EditString) { TextfieldViewsModel model; // append two strings model.Append(ASCIIToUTF16("HILL")); EXPECT_STR_EQ("HILL", model.text()); model.Append(ASCIIToUTF16("WORLD")); EXPECT_STR_EQ("HILLWORLD", model.text()); // Insert "E" to make hello model.MoveCursorRight(false); model.Insert('E'); EXPECT_STR_EQ("HEILLWORLD", model.text()); // Replace "I" with "L" model.Replace('L'); EXPECT_STR_EQ("HELLLWORLD", model.text()); model.Replace('L'); model.Replace('O'); EXPECT_STR_EQ("HELLOWORLD", model.text()); // Delete 6th char "W", then delete 5th char O" EXPECT_EQ(5U, model.cursor_pos()); EXPECT_TRUE(model.Delete()); EXPECT_STR_EQ("HELLOORLD", model.text()); EXPECT_TRUE(model.Backspace()); EXPECT_EQ(4U, model.cursor_pos()); EXPECT_STR_EQ("HELLORLD", model.text()); // Move the cursor to start. backspace should fail. model.MoveCursorToStart(false); EXPECT_FALSE(model.Backspace()); EXPECT_STR_EQ("HELLORLD", model.text()); // Move the cursor to the end. delete should fail. model.MoveCursorToEnd(false); EXPECT_FALSE(model.Delete()); EXPECT_STR_EQ("HELLORLD", model.text()); // but backspace should work. EXPECT_TRUE(model.Backspace()); EXPECT_STR_EQ("HELLORL", model.text()); } TEST(TextfieldViewsModelTest, EmptyString) { TextfieldViewsModel model; EXPECT_EQ(string16(), model.text()); EXPECT_EQ(string16(), model.GetSelectedText()); EXPECT_EQ(string16(), model.GetVisibleText()); model.MoveCursorLeft(true); EXPECT_EQ(0U, model.cursor_pos()); model.MoveCursorRight(true); EXPECT_EQ(0U, model.cursor_pos()); EXPECT_EQ(string16(), model.GetSelectedText()); EXPECT_FALSE(model.Delete()); EXPECT_FALSE(model.Backspace()); } TEST(TextfieldViewsModelTest, Selection) { TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO")); model.MoveCursorRight(false); model.MoveCursorRight(true); EXPECT_STR_EQ("E", model.GetSelectedText()); model.MoveCursorRight(true); EXPECT_STR_EQ("EL", model.GetSelectedText()); model.MoveCursorToStart(true); EXPECT_STR_EQ("H", model.GetSelectedText()); model.MoveCursorToEnd(true); EXPECT_STR_EQ("ELLO", model.GetSelectedText()); model.ClearSelection(); EXPECT_EQ(string16(), model.GetSelectedText()); model.SelectAll(); EXPECT_STR_EQ("HELLO", model.GetSelectedText()); // Select and move cursor model.MoveCursorTo(1U, false); model.MoveCursorTo(3U, true); EXPECT_STR_EQ("EL", model.GetSelectedText()); model.MoveCursorLeft(false); EXPECT_EQ(1U, model.cursor_pos()); model.MoveCursorTo(1U, false); model.MoveCursorTo(3U, true); model.MoveCursorRight(false); EXPECT_EQ(3U, model.cursor_pos()); // Select all and move cursor model.SelectAll(); model.MoveCursorLeft(false); EXPECT_EQ(0U, model.cursor_pos()); model.SelectAll(); model.MoveCursorRight(false); EXPECT_EQ(5U, model.cursor_pos()); } TEST(TextfieldViewsModelTest, SelectionAndEdit) { TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO")); model.MoveCursorRight(false); model.MoveCursorRight(true); model.MoveCursorRight(true); // select "EL" EXPECT_TRUE(model.Backspace()); EXPECT_STR_EQ("HLO", model.text()); model.Append(ASCIIToUTF16("ILL")); model.MoveCursorRight(true); model.MoveCursorRight(true); // select "LO" EXPECT_TRUE(model.Delete()); EXPECT_STR_EQ("HILL", model.text()); EXPECT_EQ(1U, model.cursor_pos()); model.MoveCursorRight(true); // select "I" model.Insert('E'); EXPECT_STR_EQ("HELL", model.text()); model.MoveCursorToStart(false); model.MoveCursorRight(true); // select "H" model.Replace('B'); EXPECT_STR_EQ("BELL", model.text()); model.MoveCursorToEnd(false); model.MoveCursorLeft(true); model.MoveCursorLeft(true); // select ">LL" model.Replace('E'); EXPECT_STR_EQ("BEE", model.text()); } TEST(TextfieldViewsModelTest, Password) { TextfieldViewsModel model; model.set_is_password(true); model.Append(ASCIIToUTF16("HELLO")); EXPECT_STR_EQ("*****", model.GetVisibleText()); EXPECT_STR_EQ("HELLO", model.text()); EXPECT_TRUE(model.Delete()); EXPECT_STR_EQ("****", model.GetVisibleText()); EXPECT_STR_EQ("ELLO", model.text()); EXPECT_EQ(0U, model.cursor_pos()); model.SelectAll(); EXPECT_STR_EQ("ELLO", model.GetSelectedText()); EXPECT_EQ(0U, model.cursor_pos()); model.Insert('X'); EXPECT_STR_EQ("*", model.GetVisibleText()); EXPECT_STR_EQ("X", model.text()); } TEST(TextfieldViewsModelTest, Word) { TextfieldViewsModel model; model.Append( ASCIIToUTF16("The answer to Life, the Universe, and Everything")); model.MoveCursorToNextWord(false); EXPECT_EQ(3U, model.cursor_pos()); model.MoveCursorToNextWord(false); EXPECT_EQ(10U, model.cursor_pos()); model.MoveCursorToNextWord(false); model.MoveCursorToNextWord(false); EXPECT_EQ(18U, model.cursor_pos()); // Should passes the non word char ',' model.MoveCursorToNextWord(true); EXPECT_EQ(23U, model.cursor_pos()); EXPECT_STR_EQ(", the", model.GetSelectedText()); // Move to the end. model.MoveCursorToNextWord(true); model.MoveCursorToNextWord(true); model.MoveCursorToNextWord(true); EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText()); // Should be safe to go next word at the end. model.MoveCursorToNextWord(true); EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText()); model.Insert('2'); EXPECT_EQ(19U, model.cursor_pos()); // Now backwards. model.MoveCursorLeft(false); // leave 2. model.MoveCursorToPreviousWord(true); EXPECT_EQ(14U, model.cursor_pos()); EXPECT_STR_EQ("Life", model.GetSelectedText()); model.MoveCursorToPreviousWord(true); EXPECT_STR_EQ("to Life", model.GetSelectedText()); model.MoveCursorToPreviousWord(true); model.MoveCursorToPreviousWord(true); model.MoveCursorToPreviousWord(true); // Select to the begining. EXPECT_STR_EQ("The answer to Life", model.GetSelectedText()); // Should be safe to go pervious word at the begining. model.MoveCursorToPreviousWord(true); EXPECT_STR_EQ("The answer to Life", model.GetSelectedText()); model.Replace('4'); EXPECT_EQ(string16(), model.GetSelectedText()); EXPECT_STR_EQ("42", model.GetVisibleText()); } TEST(TextfieldViewsModelTest, TextFragment) { TextfieldViewsModel model; TextfieldViewsModel::TextFragments fragments; // Empty string model.GetFragments(&fragments); EXPECT_EQ(1U, fragments.size()); fragments.clear(); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(0U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); // Some string model.Append(ASCIIToUTF16("Hello world")); model.GetFragments(&fragments); EXPECT_EQ(1U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(11U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); // Select 1st word model.MoveCursorToNextWord(true); model.GetFragments(&fragments); EXPECT_EQ(2U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(5U, fragments[0].end); EXPECT_TRUE(fragments[0].selected); EXPECT_EQ(5U, fragments[1].begin); EXPECT_EQ(11U, fragments[1].end); EXPECT_FALSE(fragments[1].selected); // Select empty string model.ClearSelection(); model.MoveCursorRight(true); model.GetFragments(&fragments); EXPECT_EQ(3U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(5U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); EXPECT_EQ(5U, fragments[1].begin); EXPECT_EQ(6U, fragments[1].end); EXPECT_TRUE(fragments[1].selected); EXPECT_EQ(6U, fragments[2].begin); EXPECT_EQ(11U, fragments[2].end); EXPECT_FALSE(fragments[2].selected); // Select to the end. model.MoveCursorToEnd(true); model.GetFragments(&fragments); EXPECT_EQ(2U, fragments.size()); EXPECT_EQ(0U, fragments[0].begin); EXPECT_EQ(5U, fragments[0].end); EXPECT_FALSE(fragments[0].selected); EXPECT_EQ(5U, fragments[1].begin); EXPECT_EQ(11U, fragments[1].end); EXPECT_TRUE(fragments[1].selected); } TEST(TextfieldViewsModelTest, SetText) { TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO")); model.MoveCursorToEnd(false); model.SetText(ASCIIToUTF16("GOODBYE")); EXPECT_STR_EQ("GOODBYE", model.text()); EXPECT_EQ(5U, model.cursor_pos()); model.SelectAll(); EXPECT_STR_EQ("GOODBYE", model.GetSelectedText()); // Selection move the current pos to the begining. EXPECT_EQ(0U, model.cursor_pos()); model.MoveCursorToEnd(false); EXPECT_EQ(7U, model.cursor_pos()); model.SetText(ASCIIToUTF16("BYE")); EXPECT_EQ(3U, model.cursor_pos()); EXPECT_EQ(string16(), model.GetSelectedText()); model.SetText(ASCIIToUTF16("")); EXPECT_EQ(0U, model.cursor_pos()); } TEST(TextfieldViewsModelTest, Clipboard) { views::ViewsDelegate::views_delegate = new TestViewsDelegate(); ui::Clipboard* clipboard = views::ViewsDelegate::views_delegate->GetClipboard(); string16 initial_clipboard_text; clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &initial_clipboard_text); string16 clipboard_text; TextfieldViewsModel model; model.Append(ASCIIToUTF16("HELLO WORLD")); model.MoveCursorToEnd(false); // Test for cut: Empty selection. EXPECT_FALSE(model.Cut()); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ(UTF16ToUTF8(initial_clipboard_text), clipboard_text); EXPECT_STR_EQ("HELLO WORLD", model.text()); EXPECT_EQ(11U, model.cursor_pos()); // Test for cut: Non-empty selection. model.MoveCursorToPreviousWord(true); EXPECT_TRUE(model.Cut()); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("WORLD", clipboard_text); EXPECT_STR_EQ("HELLO ", model.text()); EXPECT_EQ(6U, model.cursor_pos()); // Test for copy: Empty selection. model.Copy(); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("WORLD", clipboard_text); EXPECT_STR_EQ("HELLO ", model.text()); EXPECT_EQ(6U, model.cursor_pos()); // Test for copy: Non-empty selection. model.Append(ASCIIToUTF16("HELLO WORLD")); model.SelectAll(); model.Copy(); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text); EXPECT_STR_EQ("HELLO HELLO WORLD", model.text()); EXPECT_EQ(0U, model.cursor_pos()); // Test for paste. model.ClearSelection(); model.MoveCursorToEnd(false); model.MoveCursorToPreviousWord(true); EXPECT_TRUE(model.Paste()); clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text); EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text); EXPECT_STR_EQ("HELLO HELLO HELLO HELLO WORLD", model.text()); EXPECT_EQ(29U, model.cursor_pos()); } } // namespace views <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2021 ZNC, see the NOTICE file for details. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gmock/gmock.h> #include "znctest.h" using testing::HasSubstr; namespace znc_inttest { namespace { TEST(Config, AlreadyExists) { QTemporaryDir dir; WriteConfig(dir.path()); Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug" << "--datadir" << dir.path() << "--makeconf"); p.ReadUntil("already exists"); p.CanDie(); } TEST_F(ZNCTest, Connect) { auto znc = Run(); auto ircd = ConnectIRCd(); ircd.ReadUntil("CAP LS"); auto client = ConnectClient(); client.Write("PASS :hunter2"); client.Write("NICK nick"); client.Write("USER user/test x x :x"); client.ReadUntil("Welcome"); client.Close(); client = ConnectClient(); client.Write("PASS :user:hunter2"); client.Write("NICK nick"); client.Write("USER u x x x"); client.ReadUntil("Welcome"); client.Close(); client = ConnectClient(); client.Write("NICK nick"); client.Write("USER user x x x"); client.ReadUntil("Configure your client to send a server password"); client.Close(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("WHO"); } TEST_F(ZNCTest, Channel) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); client.ReadUntil("Welcome"); client.Write("JOIN #znc"); client.Close(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("JOIN #znc"); ircd.Write(":nick JOIN :#znc"); ircd.Write(":server 353 nick #znc :nick"); ircd.Write(":server 366 nick #znc :End of /NAMES list"); ircd.Write(":server PING :1"); ircd.ReadUntil("PONG 1"); client = LoginClient(); client.ReadUntil(":nick JOIN :#znc"); } TEST_F(ZNCTest, HTTP) { auto znc = Run(); auto ircd = ConnectIRCd(); auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/"))); EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC")); } TEST_F(ZNCTest, FixCVE20149403) { auto znc = Run(); auto ircd = ConnectIRCd(); ircd.Write(":server 001 nick :Hello"); ircd.Write(":server 005 nick CHANTYPES=# :supports"); ircd.Write(":server PING :1"); ircd.ReadUntil("PONG 1"); QNetworkRequest request; request.setRawHeader("Authorization", "Basic " + QByteArray("user:hunter2").toBase64()); request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan")); HttpPost(request, { {"user", "user"}, {"network", "test"}, {"submitted", "1"}, {"name", "znc"}, {"enabled", "1"}, }); EXPECT_THAT(HttpPost(request, { {"user", "user"}, {"network", "test"}, {"submitted", "1"}, {"name", "znc"}, {"enabled", "1"}, }) ->readAll() .toStdString(), HasSubstr("Channel [#znc] already exists")); } TEST_F(ZNCTest, FixFixOfCVE20149403) { auto znc = Run(); auto ircd = ConnectIRCd(); ircd.Write(":server 001 nick :Hello"); ircd.Write(":nick JOIN @#znc"); ircd.ReadUntil("MODE @#znc"); ircd.Write(":server 005 nick STATUSMSG=@ :supports"); ircd.Write(":server PING :12345"); ircd.ReadUntil("PONG 12345"); QNetworkRequest request; request.setRawHeader("Authorization", "Basic " + QByteArray("user:hunter2").toBase64()); request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan")); auto reply = HttpPost(request, { {"user", "user"}, {"network", "test"}, {"submitted", "1"}, {"name", "@#znc"}, {"enabled", "1"}, }); EXPECT_THAT(reply->readAll().toStdString(), HasSubstr("Could not add channel [@#znc]")); } TEST_F(ZNCTest, InvalidConfigInChan) { QFile conf(m_dir.path() + "/configs/znc.conf"); ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text)); QTextStream out(&conf); out << R"( <User foo> <Network bar> <Chan #baz> Invalid = Line </Chan> </Network> </User> )"; out.flush(); auto znc = Run(); znc->ShouldFinishItself(1); } TEST_F(ZNCTest, Encoding) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); ircd.Write(":server 001 nick :hello"); // legacy ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world"); client.ReadUntil("Hello\xE6world"); client.Write("PRIVMSG *controlpanel :SetNetwork Encoding $me $net UTF-8"); client.ReadUntil("Encoding = UTF-8"); ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world"); client.ReadUntil("Hello\xEF\xBF\xBDworld"); client.Write( "PRIVMSG *controlpanel :SetNetwork Encoding $me $net ^CP-1251"); client.ReadUntil("Encoding = ^CP-1251"); ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world"); client.ReadUntil("Hello\xD0\xB6world"); ircd.Write(":n!u@h PRIVMSG nick :Hello\xD0\xB6world"); client.ReadUntil("Hello\xD0\xB6world"); } TEST_F(ZNCTest, BuildMod) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); QTemporaryDir srcd; QDir srcdir(srcd.path()); QFile file(srcdir.filePath("testmod.cpp")); ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text)); QTextStream out(&file); out << R"( #include <znc/Modules.h> class TestModule : public CModule { public: MODCONSTRUCTOR(TestModule) {} void OnModCommand(const CString& sLine) override { PutModule("Lorem ipsum"); } }; MODULEDEFS(TestModule, "Test") )"; file.close(); QDir dir(m_dir.path()); EXPECT_TRUE(dir.mkdir("modules")); EXPECT_TRUE(dir.cd("modules")); { Process p(ZNC_BIN_DIR "/znc-buildmod", QStringList() << srcdir.filePath("file-not-found.cpp"), [&](QProcess* proc) { proc->setWorkingDirectory(dir.absolutePath()); proc->setProcessChannelMode(QProcess::ForwardedChannels); }); p.ShouldFinishItself(1); p.ShouldFinishInSec(300); } { Process p(ZNC_BIN_DIR "/znc-buildmod", QStringList() << srcdir.filePath("testmod.cpp"), [&](QProcess* proc) { proc->setWorkingDirectory(dir.absolutePath()); proc->setProcessChannelMode(QProcess::ForwardedChannels); }); p.ShouldFinishItself(); p.ShouldFinishInSec(300); } client.Write("znc loadmod testmod"); client.Write("PRIVMSG *testmod :hi"); client.ReadUntil("Lorem ipsum"); } TEST_F(ZNCTest, AwayNotify) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = ConnectClient(); client.Write("CAP LS"); client.Write("PASS :hunter2"); client.Write("NICK nick"); client.Write("USER user/test x x :x"); QByteArray cap_ls; client.ReadUntilAndGet(" LS :", cap_ls); ASSERT_THAT(cap_ls.toStdString(), AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify")))); client.Write("CAP REQ :cap-notify"); client.ReadUntil("ACK :cap-notify"); client.Write("CAP END"); client.ReadUntil(" 001 "); ircd.ReadUntil("USER"); ircd.Write("CAP user LS :away-notify"); ircd.ReadUntil("CAP REQ :away-notify"); ircd.Write("CAP user ACK :away-notify"); ircd.ReadUntil("CAP END"); ircd.Write(":server 001 user :welcome"); client.ReadUntil("CAP user NEW :away-notify"); client.Write("CAP REQ :away-notify"); client.ReadUntil("ACK :away-notify"); ircd.Write(":x!y@z AWAY :reason"); client.ReadUntil(":x!y@z AWAY :reason"); ircd.Close(); client.ReadUntil("DEL :away-notify"); // This test often fails on macos due to ZNC process not finishing. // No idea why. Let's try to shutdown it more explicitly... client.Write("znc shutdown"); } TEST_F(ZNCTest, JoinKey) { QFile conf(m_dir.path() + "/configs/znc.conf"); ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text)); QTextStream(&conf) << "ServerThrottle = 1\n"; auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); ircd.Write(":server 001 nick :Hello"); client.Write("JOIN #znc secret"); ircd.ReadUntil("JOIN #znc secret"); ircd.Write(":nick JOIN :#znc"); client.ReadUntil("JOIN :#znc"); ircd.Close(); ircd = ConnectIRCd(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("JOIN #znc secret"); } TEST_F(ZNCTest, StatusEchoMessage) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); client.Write("CAP REQ :echo-message"); client.Write("PRIVMSG *status :blah"); client.ReadUntil(":nick!user@irc.znc.in PRIVMSG *status :blah"); client.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command"); client.Write("znc delnetwork test"); client.ReadUntil("Network deleted"); auto client2 = LoginClient(); client2.Write("PRIVMSG *status :blah2"); client2.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command"); auto client3 = LoginClient(); client3.Write("PRIVMSG *status :blah3"); client3.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command"); } TEST_F(ZNCTest, MoveChannels) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); client.Write("JOIN #foo,#bar"); client.Close(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("JOIN #foo,#bar"); ircd.Write(":nick JOIN :#foo"); ircd.Write(":server 353 nick #foo :nick"); ircd.Write(":server 366 nick #foo :End of /NAMES list"); ircd.Write(":nick JOIN :#bar"); ircd.Write(":server 353 nick #bar :nick"); ircd.Write(":server 366 nick #bar :End of /NAMES list"); client = LoginClient(); client.ReadUntil(":nick JOIN :#foo"); client.ReadUntil(":nick JOIN :#bar"); client.Write("znc movechan #foo 2"); client.ReadUntil("Moved channel #foo to index 2"); client.Close(); client = LoginClient(); client.ReadUntil(":nick JOIN :#bar"); client.ReadUntil(":nick JOIN :#foo"); client.Write("znc swapchans #foo #bar"); client.ReadUntil("Swapped channels #foo and #bar"); client.Close(); client = LoginClient(); client.ReadUntil(":nick JOIN :#foo"); client.ReadUntil(":nick JOIN :#bar"); } } // namespace } // namespace znc_inttest <commit_msg>Add tests for deny options<commit_after>/* * Copyright (C) 2004-2021 ZNC, see the NOTICE file for details. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gmock/gmock.h> #include "znctest.h" using testing::HasSubstr; namespace znc_inttest { namespace { TEST(Config, AlreadyExists) { QTemporaryDir dir; WriteConfig(dir.path()); Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug" << "--datadir" << dir.path() << "--makeconf"); p.ReadUntil("already exists"); p.CanDie(); } TEST_F(ZNCTest, Connect) { auto znc = Run(); auto ircd = ConnectIRCd(); ircd.ReadUntil("CAP LS"); auto client = ConnectClient(); client.Write("PASS :hunter2"); client.Write("NICK nick"); client.Write("USER user/test x x :x"); client.ReadUntil("Welcome"); client.Close(); client = ConnectClient(); client.Write("PASS :user:hunter2"); client.Write("NICK nick"); client.Write("USER u x x x"); client.ReadUntil("Welcome"); client.Close(); client = ConnectClient(); client.Write("NICK nick"); client.Write("USER user x x x"); client.ReadUntil("Configure your client to send a server password"); client.Close(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("WHO"); } TEST_F(ZNCTest, Channel) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); client.ReadUntil("Welcome"); client.Write("JOIN #znc"); client.Close(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("JOIN #znc"); ircd.Write(":nick JOIN :#znc"); ircd.Write(":server 353 nick #znc :nick"); ircd.Write(":server 366 nick #znc :End of /NAMES list"); ircd.Write(":server PING :1"); ircd.ReadUntil("PONG 1"); client = LoginClient(); client.ReadUntil(":nick JOIN :#znc"); } TEST_F(ZNCTest, HTTP) { auto znc = Run(); auto ircd = ConnectIRCd(); auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/"))); EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC")); } TEST_F(ZNCTest, FixCVE20149403) { auto znc = Run(); auto ircd = ConnectIRCd(); ircd.Write(":server 001 nick :Hello"); ircd.Write(":server 005 nick CHANTYPES=# :supports"); ircd.Write(":server PING :1"); ircd.ReadUntil("PONG 1"); QNetworkRequest request; request.setRawHeader("Authorization", "Basic " + QByteArray("user:hunter2").toBase64()); request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan")); HttpPost(request, { {"user", "user"}, {"network", "test"}, {"submitted", "1"}, {"name", "znc"}, {"enabled", "1"}, }); EXPECT_THAT(HttpPost(request, { {"user", "user"}, {"network", "test"}, {"submitted", "1"}, {"name", "znc"}, {"enabled", "1"}, }) ->readAll() .toStdString(), HasSubstr("Channel [#znc] already exists")); } TEST_F(ZNCTest, FixFixOfCVE20149403) { auto znc = Run(); auto ircd = ConnectIRCd(); ircd.Write(":server 001 nick :Hello"); ircd.Write(":nick JOIN @#znc"); ircd.ReadUntil("MODE @#znc"); ircd.Write(":server 005 nick STATUSMSG=@ :supports"); ircd.Write(":server PING :12345"); ircd.ReadUntil("PONG 12345"); QNetworkRequest request; request.setRawHeader("Authorization", "Basic " + QByteArray("user:hunter2").toBase64()); request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan")); auto reply = HttpPost(request, { {"user", "user"}, {"network", "test"}, {"submitted", "1"}, {"name", "@#znc"}, {"enabled", "1"}, }); EXPECT_THAT(reply->readAll().toStdString(), HasSubstr("Could not add channel [@#znc]")); } TEST_F(ZNCTest, InvalidConfigInChan) { QFile conf(m_dir.path() + "/configs/znc.conf"); ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text)); QTextStream out(&conf); out << R"( <User foo> <Network bar> <Chan #baz> Invalid = Line </Chan> </Network> </User> )"; out.flush(); auto znc = Run(); znc->ShouldFinishItself(1); } TEST_F(ZNCTest, Encoding) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); ircd.Write(":server 001 nick :hello"); // legacy ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world"); client.ReadUntil("Hello\xE6world"); client.Write("PRIVMSG *controlpanel :SetNetwork Encoding $me $net UTF-8"); client.ReadUntil("Encoding = UTF-8"); ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world"); client.ReadUntil("Hello\xEF\xBF\xBDworld"); client.Write( "PRIVMSG *controlpanel :SetNetwork Encoding $me $net ^CP-1251"); client.ReadUntil("Encoding = ^CP-1251"); ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world"); client.ReadUntil("Hello\xD0\xB6world"); ircd.Write(":n!u@h PRIVMSG nick :Hello\xD0\xB6world"); client.ReadUntil("Hello\xD0\xB6world"); } TEST_F(ZNCTest, BuildMod) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); QTemporaryDir srcd; QDir srcdir(srcd.path()); QFile file(srcdir.filePath("testmod.cpp")); ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text)); QTextStream out(&file); out << R"( #include <znc/Modules.h> class TestModule : public CModule { public: MODCONSTRUCTOR(TestModule) {} void OnModCommand(const CString& sLine) override { PutModule("Lorem ipsum"); } }; MODULEDEFS(TestModule, "Test") )"; file.close(); QDir dir(m_dir.path()); EXPECT_TRUE(dir.mkdir("modules")); EXPECT_TRUE(dir.cd("modules")); { Process p(ZNC_BIN_DIR "/znc-buildmod", QStringList() << srcdir.filePath("file-not-found.cpp"), [&](QProcess* proc) { proc->setWorkingDirectory(dir.absolutePath()); proc->setProcessChannelMode(QProcess::ForwardedChannels); }); p.ShouldFinishItself(1); p.ShouldFinishInSec(300); } { Process p(ZNC_BIN_DIR "/znc-buildmod", QStringList() << srcdir.filePath("testmod.cpp"), [&](QProcess* proc) { proc->setWorkingDirectory(dir.absolutePath()); proc->setProcessChannelMode(QProcess::ForwardedChannels); }); p.ShouldFinishItself(); p.ShouldFinishInSec(300); } client.Write("znc loadmod testmod"); client.Write("PRIVMSG *testmod :hi"); client.ReadUntil("Lorem ipsum"); } TEST_F(ZNCTest, AwayNotify) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = ConnectClient(); client.Write("CAP LS"); client.Write("PASS :hunter2"); client.Write("NICK nick"); client.Write("USER user/test x x :x"); QByteArray cap_ls; client.ReadUntilAndGet(" LS :", cap_ls); ASSERT_THAT(cap_ls.toStdString(), AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify")))); client.Write("CAP REQ :cap-notify"); client.ReadUntil("ACK :cap-notify"); client.Write("CAP END"); client.ReadUntil(" 001 "); ircd.ReadUntil("USER"); ircd.Write("CAP user LS :away-notify"); ircd.ReadUntil("CAP REQ :away-notify"); ircd.Write("CAP user ACK :away-notify"); ircd.ReadUntil("CAP END"); ircd.Write(":server 001 user :welcome"); client.ReadUntil("CAP user NEW :away-notify"); client.Write("CAP REQ :away-notify"); client.ReadUntil("ACK :away-notify"); ircd.Write(":x!y@z AWAY :reason"); client.ReadUntil(":x!y@z AWAY :reason"); ircd.Close(); client.ReadUntil("DEL :away-notify"); // This test often fails on macos due to ZNC process not finishing. // No idea why. Let's try to shutdown it more explicitly... client.Write("znc shutdown"); } TEST_F(ZNCTest, JoinKey) { QFile conf(m_dir.path() + "/configs/znc.conf"); ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text)); QTextStream(&conf) << "ServerThrottle = 1\n"; auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); ircd.Write(":server 001 nick :Hello"); client.Write("JOIN #znc secret"); ircd.ReadUntil("JOIN #znc secret"); ircd.Write(":nick JOIN :#znc"); client.ReadUntil("JOIN :#znc"); ircd.Close(); ircd = ConnectIRCd(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("JOIN #znc secret"); } TEST_F(ZNCTest, StatusEchoMessage) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); client.Write("CAP REQ :echo-message"); client.Write("PRIVMSG *status :blah"); client.ReadUntil(":nick!user@irc.znc.in PRIVMSG *status :blah"); client.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command"); client.Write("znc delnetwork test"); client.ReadUntil("Network deleted"); auto client2 = LoginClient(); client2.Write("PRIVMSG *status :blah2"); client2.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command"); auto client3 = LoginClient(); client3.Write("PRIVMSG *status :blah3"); client3.ReadUntil(":*status!znc@znc.in PRIVMSG nick :Unknown command"); } TEST_F(ZNCTest, MoveChannels) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); client.Write("JOIN #foo,#bar"); client.Close(); ircd.Write(":server 001 nick :Hello"); ircd.ReadUntil("JOIN #foo,#bar"); ircd.Write(":nick JOIN :#foo"); ircd.Write(":server 353 nick #foo :nick"); ircd.Write(":server 366 nick #foo :End of /NAMES list"); ircd.Write(":nick JOIN :#bar"); ircd.Write(":server 353 nick #bar :nick"); ircd.Write(":server 366 nick #bar :End of /NAMES list"); client = LoginClient(); client.ReadUntil(":nick JOIN :#foo"); client.ReadUntil(":nick JOIN :#bar"); client.Write("znc movechan #foo 2"); client.ReadUntil("Moved channel #foo to index 2"); client.Close(); client = LoginClient(); client.ReadUntil(":nick JOIN :#bar"); client.ReadUntil(":nick JOIN :#foo"); client.Write("znc swapchans #foo #bar"); client.ReadUntil("Swapped channels #foo and #bar"); client.Close(); client = LoginClient(); client.ReadUntil(":nick JOIN :#foo"); client.ReadUntil(":nick JOIN :#bar"); } TEST_F(ZNCTest, DenyOptions) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client1 = LoginClient(); client1.Write("PRIVMSG *controlpanel :CloneUser user user2"); client1.ReadUntil("User user2 added!"); client1.Write("PRIVMSG *controlpanel :Set Admin user2 false"); client1.ReadUntil("Admin = false"); client1.Write("PRIVMSG *controlpanel :Set MaxNetworks user2 5"); client1.ReadUntil("MaxNetworks = 5"); auto client2 = ConnectClient(); client2.Write("PASS :hunter2"); client2.Write("NICK nick2"); client2.Write("USER user2/test x x :x"); // DenySetNetwork // This is false by default so we should be able to add/delete networks/servers client2.Write("PRIVMSG *controlpanel :AddNetwork user2 test2"); client2.ReadUntil("Network test2 added to user user2."); client2.Write("PRIVMSG *controlpanel :AddServer user2 test2 127.0.0.1"); client2.ReadUntil("Added IRC Server 127.0.0.1 to network test2 for user user2."); client2.Write("PRIVMSG *controlpanel :DelServer user2 test2 127.0.0.1"); client2.ReadUntil("Deleted IRC Server 127.0.0.1 from network test2 for user user2."); client2.Write("PRIVMSG *controlpanel :DelNetwork user2 test2"); client2.ReadUntil("Network test2 deleted for user user2."); // Set it to true client1.Write("PRIVMSG *controlpanel :Set DenySetNetwork user2 true"); client1.ReadUntil("DenySetNetwork = true"); // Now we should be denied client2.Write("PRIVMSG *controlpanel :AddNetwork user2 test2"); client2.ReadUntil("Access denied!"); client2.Write("PRIVMSG *controlpanel :AddServer user2 test 127.0.0.2"); client2.ReadUntil("Access denied!"); client2.Write("PRIVMSG *controlpanel :DelServer user2 test 127.0.0.1"); client2.ReadUntil("Access denied!"); client2.Write("PRIVMSG *controlpanel :DelNetwork user2 test"); client2.ReadUntil("Access denied!"); // DenySetBindHost client2.Write("PRIVMSG *controlpanel :Set BindHost user2 127.0.0.1"); client2.ReadUntil("BindHost = 127.0.0.1"); client1.Write("PRIVMSG *controlpanel :Set DenySetBindHost user2 true"); client1.ReadUntil("DenySetBindHost = true"); client2.Write("PRIVMSG *controlpanel :Set BindHost user2 127.0.0.2"); client2.ReadUntil("Access denied!"); // DenySetIdent client2.Write("PRIVMSG *controlpanel :Set Ident user2 test"); client2.ReadUntil("Ident = test"); client1.Write("PRIVMSG *controlpanel :Set DenySetIdent user2 true"); client1.ReadUntil("DenySetIdent = true"); client2.Write("PRIVMSG *controlpanel :Set Ident user2 test2"); client2.ReadUntil("Access denied!"); // DenySetRealName client2.Write("PRIVMSG *controlpanel :Set RealName user2 test"); client2.ReadUntil("RealName = test"); client1.Write("PRIVMSG *controlpanel :Set DenySetRealName user2 true"); client1.ReadUntil("DenySetRealName = true"); client2.Write("PRIVMSG *controlpanel :Set RealName user2 test2"); client2.ReadUntil("Access denied!"); // DenySetQuitMsg client2.Write("PRIVMSG *controlpanel :Set QuitMsg user2 test"); client2.ReadUntil("QuitMsg = test"); client1.Write("PRIVMSG *controlpanel :Set DenySetQuitMsg user2 true"); client1.ReadUntil("DenySetQuitMsg = true"); client2.Write("PRIVMSG *controlpanel :Set QuitMsg user2 test2"); client2.ReadUntil("Access denied!"); // DenySetCTCPReplies client2.Write("PRIVMSG *controlpanel :AddCTCP user2 FOO BAR"); client2.ReadUntil("CTCP requests FOO to user user2 will now get reply: BAR"); client2.Write("PRIVMSG *controlpanel :DelCTCP user2 FOO"); client2.ReadUntil("CTCP requests FOO to user user2 will now be sent to IRC clients"); client1.Write("PRIVMSG *controlpanel :Set DenySetCTCPReplies user2 true"); client1.ReadUntil("DenySetCTCPReplies = true"); client2.Write("PRIVMSG *controlpanel :AddCTCP user2 FOO BAR"); client2.ReadUntil("Access denied!"); client2.Write("PRIVMSG *controlpanel :DelCTCP user2 FOO"); client2.ReadUntil("Access denied!"); } } // namespace } // namespace znc_inttest <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: TaskPaneTreeNode.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kz $ $Date: 2005-03-18 16:49:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_TASKPANE_TREE_NODE_HXX #define SD_TASKPANE_TREE_NODE_HXX #include "ILayoutableWindow.hxx" #include <memory> namespace sd { class ObjectBarManager; }; namespace sd { namespace toolpanel { class ControlContainer; class TaskPaneShellManager; /** Base class for all members of the object hierarchy that makes up the tool panel. There are usually at least three levels. At the top level is the ToolPanel with one instance: the root of the tree. At the middle level there are SubToolPanels and Window/Control objects. At the lowest level there are only Window or Control objects. This class provides the means of communication between objects on different levels. */ class TreeNode : public ILayoutableWindow, public ILayouter { public: TreeNode (TreeNode* pParent); virtual ~TreeNode (void); /** Returns <TRUE/> if the node has no children, i.e. is a leaf of a tree. In this case mpControlContainer is NULL. */ bool IsLeaf (void); /** Returns true if the node has no parent, i.e. is the root of a tree. */ bool IsRoot (void); void SetParentNode (TreeNode* pNewParent); TreeNode* GetParentNode (void); /** Return the Window pointer of a tree node. */ virtual ::Window* GetWindow (void); /** Return a const pointer to the window of a tree node. */ virtual const ::Window* GetConstWindow (void) const; /** Return the joined minimum width of all children, i.e. the largest of the minimum widths. */ virtual sal_Int32 GetMinimumWidth (void); /** Give each node access to the object bar manager of the tool panel. At least the root node has to overwrite this method since the default implementation simply returns the object bar manager of the parent. */ virtual ObjectBarManager* GetObjectBarManager (void); /** The default implementaion always returns <FALSE/> */ virtual bool IsResizable (void); /** Call this method whenever the size of one of the children of the called node has to be changed, e.g. when the layout menu shows more or less items than before. As a typical result the node will layout and resize its children according to their size requirements. Please remember that the size of the children can be changed in the first place because scroll bars can give a node the space it needs. The default implementation passes this call to its parent. */ virtual void RequestResize (void); /** The default implementation shows the window (when it exists) when bExpansionState is <TRUE/>. It hides the window otherwise. */ virtual void Expand (bool bExpansionState); /** The default implementation returns whether the window is showing. When there is no window then it returns <FALSE/>. */ virtual bool IsExpanded (void) const; /** Return whether the node can be expanded or collapsed. The default implementation always returns <TRUE/> when there is window and <FALSE/> otherwise. If <FALSE/> is returned then Expand() may be called but it will not change the expansion state. */ virtual bool IsExpandable (void) const; /** The default implementation calls GetWindow()->Show(). */ virtual void Show (bool bVisibilityState); /** The default implementation returns GetWindow()->IsVisible(). */ virtual bool IsShowing (void) const; ControlContainer& GetControlContainer (void); /** Give each node access to a shell manage. This usually is the shell manager of the TaskPaneViewShell. At least the root node has to overwrite this method since the default implementation simply returns the shell manager of its parent. */ virtual TaskPaneShellManager* GetShellManager (void); protected: ::std::auto_ptr<ControlContainer> mpControlContainer; private: TreeNode* mpParent; }; } } // end of namespace ::sd::toolpanel #endif <commit_msg>#100000# resolve inconsistency caused by impress39<commit_after>/************************************************************************* * * $RCSfile: TaskPaneTreeNode.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-03-23 14:22:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_TASKPANE_TREE_NODE_HXX #define SD_TASKPANE_TREE_NODE_HXX #include "ILayoutableWindow.hxx" #include <memory> namespace sd { class ObjectBarManager; }; namespace sd { namespace toolpanel { class ControlContainer; class TaskPaneShellManager; /** Base class for all members of the object hierarchy that makes up the tool panel. There are usually at least three levels. At the top level is the ToolPanel with one instance: the root of the tree. At the middle level there are SubToolPanels and Window/Control objects. At the lowest level there are only Window or Control objects. This class provides the means of communication between objects on different levels. */ class TreeNode : public ILayoutableWindow, public ILayouter { public: TreeNode (TreeNode* pParent); virtual ~TreeNode (void); /** Returns <TRUE/> if the node has no children, i.e. is a leaf of a tree. In this case mpControlContainer is NULL. */ bool IsLeaf (void); /** Returns true if the node has no parent, i.e. is the root of a tree. */ bool IsRoot (void); void SetParentNode (TreeNode* pNewParent); TreeNode* GetParentNode (void); /** Return the Window pointer of a tree node. */ virtual ::Window* GetWindow (void); /** Return a const pointer to the window of a tree node. */ virtual const ::Window* GetConstWindow (void) const; /** Return the joined minimum width of all children, i.e. the largest of the minimum widths. */ virtual sal_Int32 GetMinimumWidth (void); /** Give each node access to the object bar manager of the tool panel. At least the root node has to overwrite this method since the default implementation simply returns the object bar manager of the parent. */ virtual ObjectBarManager* GetObjectBarManager (void); /** The default implementaion always returns <FALSE/> */ virtual bool IsResizable (void); /** Call this method whenever the size of one of the children of the called node has to be changed, e.g. when the layout menu shows more or less items than before. As a typical result the node will layout and resize its children according to their size requirements. Please remember that the size of the children can be changed in the first place because scroll bars can give a node the space it needs. The default implementation passes this call to its parent. */ virtual void RequestResize (void); /** The default implementation shows the window (when it exists) when bExpansionState is <TRUE/>. It hides the window otherwise. @return Returns <TRUE/> when the expansion state changes. When an expansion state is requested that is already in place then <FALSE/> is returned. */ virtual bool Expand (bool bExpansionState); /** The default implementation returns whether the window is showing. When there is no window then it returns <FALSE/>. */ virtual bool IsExpanded (void) const; /** Return whether the node can be expanded or collapsed. The default implementation always returns <TRUE/> when there is window and <FALSE/> otherwise. If <FALSE/> is returned then Expand() may be called but it will not change the expansion state. */ virtual bool IsExpandable (void) const; /** The default implementation calls GetWindow()->Show(). */ virtual void Show (bool bVisibilityState); /** The default implementation returns GetWindow()->IsVisible(). */ virtual bool IsShowing (void) const; ControlContainer& GetControlContainer (void); /** Give each node access to a shell manage. This usually is the shell manager of the TaskPaneViewShell. At least the root node has to overwrite this method since the default implementation simply returns the shell manager of its parent. */ virtual TaskPaneShellManager* GetShellManager (void); protected: ::std::auto_ptr<ControlContainer> mpControlContainer; private: TreeNode* mpParent; }; } } // end of namespace ::sd::toolpanel #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Soar Qin<soarchin@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ struct SSUParseStruct; void realParse(const char * filename, SSUParseStruct * ssus); #include "LexUtil.h" #include "SsuLex.h" #include "SsuLex.c" struct TokenAssign { const char * token; int id; } tokenAssigns[] = { {"struct", TK_STRUCT}, {"message", TK_STRUCT}, {"class", TK_STRUCT}, {"enum", TK_ENUM}, {"option", TK_OPTION}, {"package", TK_PACKAGE}, {"import", TK_IMPORT}, {"{", TK_LBRACE}, {"}", TK_RBRACE}, {"[", TK_LSBRACKET}, {"]", TK_RSBRACKET}, {",", TK_COMMA}, {"=", TK_ASSIGN}, {";", TK_DELIM}, {"required", TK_REQUIRED}, {"optional", TK_OPTIONAL}, {"repeated", TK_REPEATED}, {"ordermap", TK_ORDERMAP}, {"int", TK_INTEGER}, {"sint", TK_SINTEGER}, {"uint", TK_UINTEGER}, {"int32", TK_INTEGER}, {"sint32", TK_SINTEGER}, {"uint32", TK_UINTEGER}, {"int64", TK_INTEGER64}, {"sint64", TK_SINTEGER64}, {"uint64", TK_UINTEGER64}, {"float", TK_FLOAT}, {"double", TK_DOUBLE}, {"fixed32", TK_FIXED32}, {"sfixed32", TK_FIXED32}, {"fixed64", TK_FIXED64}, {"sfixed64", TK_FIXED64}, {"string", TK_STRING}, {"bool", TK_BOOL}, {"default", TK_DEFAULT}, {"packed", TK_PACKED}, {NULL, TK_CUSTOM}, }; inline void push(void * parser, SSUParseStruct * ssus) { TokenAssign * assign; for(assign = tokenAssigns; assign->token != NULL; ++ assign) { if(strcmp(assign->token, ssus->ssh.word.c_str()) == 0) { printf_debug("%s %d\n", ssus->ssh.word.c_str(), assign->id); ssuParser(parser, assign->id, strdup(ssus->ssh.word.c_str()), ssus); return; } } printf_debug("%s\n", ssus->ssh.word.c_str()); ssuParser(parser, TK_CUSTOM, strdup(ssus->ssh.word.c_str()), ssus); } inline int typeFromChar(uint8_t v) { const int cTable[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 9, 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 9, 0, 0, // 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 8, 0, 7, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 3 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 5 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // 7 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F }; return cTable[v]; } static char * extractComment(char * s, int& err) { err = 0; char *p = s; while(*p != 0) { if(*p == '\'' || *p == '"') { p = strchr(p + 1, *p); if(p == NULL) { err = 1; return NULL; } } else if(*p == '/' && *(p + 1) == '/') { *p = 0; return p + 2; } ++ p; } return NULL; } #define PUSH_LASTTOKEN \ if((currentCharId == 0 || currentCharId == 1) && sstart != scurrent) { \ ssus->ssh.col.back() = sstart - s + 1; \ ssus->ssh.word.assign(sstart, scurrent); \ push(parser, ssus); \ } void realParse(const char * filename, SSUParseStruct * ssus) { void * parser = ssuParserAlloc(malloc); FILE * f = fopen(filename, "rt"); ssus->ssh.fileName.push_back(filename); ssus->ssh.row.push_back(0); ssus->ssh.col.push_back(0); int lineNo = 0; while(!feof(f)) { char s[4096]; ++ lineNo; if(fgets(s, 4096, f) == NULL) continue; ++ ssus->ssh.row.back(); size_t len = strlen(s); if(len == 0) continue; int i = (int)len - 1; while(i >= 0 && typeFromChar(s[i]) == 9) -- i; if(i < 0) continue; s[i + 1] = 0; int err = 0; char * cmt = extractComment(s, err); if(err) { fprintf(stderr, "[%s] %d:1 Unpaired quotes!", filename, lineNo); exit(0); } if(cmt != NULL) ssuParser(parser, TK_COMMENT, strdup(cmt), ssus); char * sstart = s; char * scurrent = s; bool nextLine = false; int currentCharId = -1; while(!nextLine) { int charId = typeFromChar(*scurrent); switch(charId) { case 9: if(scurrent != sstart) { PUSH_LASTTOKEN; } nextLine = true; break; case 8: { PUSH_LASTTOKEN; do { ++ scurrent; } while(typeFromChar(*scurrent) == 8); sstart = scurrent; currentCharId = -1; continue; } case 7: { PUSH_LASTTOKEN; sstart = scurrent + 1; scurrent = strchr(sstart, *scurrent); std::string tmpStr2(sstart, scurrent); ssuParser(parser, TK_CUSTOM, strdup(tmpStr2.c_str()), ssus); sstart = scurrent + 1; } break; case 1: case 0: if(charId != currentCharId) { PUSH_LASTTOKEN currentCharId = charId; sstart = scurrent; } if(charId == 0) { ssus->ssh.col.back() = scurrent - s + 1; ssus->ssh.word = *scurrent; push(parser, ssus); sstart = scurrent + 1; } break; } if(nextLine) break; ++ scurrent; } } fclose(f); ssuParser(parser, 0, NULL, ssus); ssuParserFree(parser, free); ssus->ssh.fileName.erase(ssus->ssh.fileName.end() - 1); ssus->ssh.row.erase(ssus->ssh.row.end() - 1); ssus->ssh.col.erase(ssus->ssh.col.end() - 1); } DLLSPEC void * parse(const char * filename) { SSUParseStruct * ssus = new SSUParseStruct; realParse(filename, ssus); return ssus; } DLLSPEC SSUStruct * parseGetStruct( void * ssus ) { return &((SSUParseStruct *)ssus)->ss; } DLLSPEC void parseFree( void * ssus ) { delete (SSUParseStruct *)ssus; } <commit_msg>added bytes support<commit_after>/* * Copyright (c) 2011, Soar Qin<soarchin@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ struct SSUParseStruct; void realParse(const char * filename, SSUParseStruct * ssus); #include "LexUtil.h" #include "SsuLex.h" #include "SsuLex.c" struct TokenAssign { const char * token; int id; } tokenAssigns[] = { {"struct", TK_STRUCT}, {"message", TK_STRUCT}, {"class", TK_STRUCT}, {"enum", TK_ENUM}, {"option", TK_OPTION}, {"package", TK_PACKAGE}, {"import", TK_IMPORT}, {"{", TK_LBRACE}, {"}", TK_RBRACE}, {"[", TK_LSBRACKET}, {"]", TK_RSBRACKET}, {",", TK_COMMA}, {"=", TK_ASSIGN}, {";", TK_DELIM}, {"required", TK_REQUIRED}, {"optional", TK_OPTIONAL}, {"repeated", TK_REPEATED}, {"ordermap", TK_ORDERMAP}, {"int", TK_INTEGER}, {"sint", TK_SINTEGER}, {"uint", TK_UINTEGER}, {"int32", TK_INTEGER}, {"sint32", TK_SINTEGER}, {"uint32", TK_UINTEGER}, {"int64", TK_INTEGER64}, {"sint64", TK_SINTEGER64}, {"uint64", TK_UINTEGER64}, {"float", TK_FLOAT}, {"double", TK_DOUBLE}, {"fixed32", TK_FIXED32}, {"sfixed32", TK_FIXED32}, {"fixed64", TK_FIXED64}, {"sfixed64", TK_FIXED64}, {"string", TK_STRING}, {"bytes", TK_STRING}, {"bool", TK_BOOL}, {"default", TK_DEFAULT}, {"packed", TK_PACKED}, {NULL, TK_CUSTOM}, }; inline void push(void * parser, SSUParseStruct * ssus) { TokenAssign * assign; for(assign = tokenAssigns; assign->token != NULL; ++ assign) { if(strcmp(assign->token, ssus->ssh.word.c_str()) == 0) { printf_debug("%s %d\n", ssus->ssh.word.c_str(), assign->id); ssuParser(parser, assign->id, strdup(ssus->ssh.word.c_str()), ssus); return; } } printf_debug("%s\n", ssus->ssh.word.c_str()); ssuParser(parser, TK_CUSTOM, strdup(ssus->ssh.word.c_str()), ssus); } inline int typeFromChar(uint8_t v) { const int cTable[256] = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 9, 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 9, 0, 0, // 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 8, 0, 7, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 1, 1, 0, // 2 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 3 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 5 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // 7 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F }; return cTable[v]; } static char * extractComment(char * s, int& err) { err = 0; char *p = s; while(*p != 0) { if(*p == '\'' || *p == '"') { p = strchr(p + 1, *p); if(p == NULL) { err = 1; return NULL; } } else if(*p == '/' && *(p + 1) == '/') { *p = 0; return p + 2; } ++ p; } return NULL; } #define PUSH_LASTTOKEN \ if((currentCharId == 0 || currentCharId == 1) && sstart != scurrent) { \ ssus->ssh.col.back() = sstart - s + 1; \ ssus->ssh.word.assign(sstart, scurrent); \ push(parser, ssus); \ } void realParse(const char * filename, SSUParseStruct * ssus) { void * parser = ssuParserAlloc(malloc); FILE * f = fopen(filename, "rt"); ssus->ssh.fileName.push_back(filename); ssus->ssh.row.push_back(0); ssus->ssh.col.push_back(0); int lineNo = 0; while(!feof(f)) { char s[4096]; ++ lineNo; if(fgets(s, 4096, f) == NULL) continue; ++ ssus->ssh.row.back(); size_t len = strlen(s); if(len == 0) continue; int i = (int)len - 1; while(i >= 0 && typeFromChar(s[i]) == 9) -- i; if(i < 0) continue; s[i + 1] = 0; int err = 0; char * cmt = extractComment(s, err); if(err) { fprintf(stderr, "[%s] %d:1 Unpaired quotes!", filename, lineNo); exit(0); } if(cmt != NULL) ssuParser(parser, TK_COMMENT, strdup(cmt), ssus); char * sstart = s; char * scurrent = s; bool nextLine = false; int currentCharId = -1; while(!nextLine) { int charId = typeFromChar(*scurrent); switch(charId) { case 9: if(scurrent != sstart) { PUSH_LASTTOKEN; } nextLine = true; break; case 8: { PUSH_LASTTOKEN; do { ++ scurrent; } while(typeFromChar(*scurrent) == 8); sstart = scurrent; currentCharId = -1; continue; } case 7: { PUSH_LASTTOKEN; sstart = scurrent + 1; scurrent = strchr(sstart, *scurrent); std::string tmpStr2(sstart, scurrent); ssuParser(parser, TK_CUSTOM, strdup(tmpStr2.c_str()), ssus); sstart = scurrent + 1; } break; case 1: case 0: if(charId != currentCharId) { PUSH_LASTTOKEN currentCharId = charId; sstart = scurrent; } if(charId == 0) { ssus->ssh.col.back() = scurrent - s + 1; ssus->ssh.word = *scurrent; push(parser, ssus); sstart = scurrent + 1; } break; } if(nextLine) break; ++ scurrent; } } fclose(f); ssuParser(parser, 0, NULL, ssus); ssuParserFree(parser, free); ssus->ssh.fileName.erase(ssus->ssh.fileName.end() - 1); ssus->ssh.row.erase(ssus->ssh.row.end() - 1); ssus->ssh.col.erase(ssus->ssh.col.end() - 1); } DLLSPEC void * parse(const char * filename) { SSUParseStruct * ssus = new SSUParseStruct; realParse(filename, ssus); return ssus; } DLLSPEC SSUStruct * parseGetStruct( void * ssus ) { return &((SSUParseStruct *)ssus)->ss; } DLLSPEC void parseFree( void * ssus ) { delete (SSUParseStruct *)ssus; } <|endoftext|>
<commit_before>// // MIT License // // Copyright (c) 2017-2018 Thibault Martinez and Simon Ninon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // #include <algorithm> #include <array> #include <cstdlib> #include <functional> #include <iota/constants.hpp> #include <iota/types/trinary.hpp> namespace IOTA { namespace Types { static constexpr std::array<std::array<int8_t, 3>, TryteAlphabetLength> trytesTrits{ { { { 0, 0, 0 } }, { { 1, 0, 0 } }, { { -1, 1, 0 } }, { { 0, 1, 0 } }, { { 1, 1, 0 } }, { { -1, -1, 1 } }, { { 0, -1, 1 } }, { { 1, -1, 1 } }, { { -1, 0, 1 } }, { { 0, 0, 1 } }, { { 1, 0, 1 } }, { { -1, 1, 1 } }, { { 0, 1, 1 } }, { { 1, 1, 1 } }, { { -1, -1, -1 } }, { { 0, -1, -1 } }, { { 1, -1, -1 } }, { { -1, 0, -1 } }, { { 0, 0, -1 } }, { { 1, 0, -1 } }, { { -1, 1, -1 } }, { { 0, 1, -1 } }, { { 1, 1, -1 } }, { { -1, -1, 0 } }, { { 0, -1, 0 } }, { { 1, -1, 0 } }, { { -1, 0, 0 } } } }; int8_t tryteIndex(const char& tryte) { if (tryte == '9') { return 0; } if ('A' <= tryte && tryte <= 'Z') { return tryte - 'A' + 1; } return -1; } bool isValidTryte(const char& tryte) { return tryteIndex(tryte) >= 0; } bool isValidTrytes(const Trytes& trytes) { return std::find_if_not(trytes.begin(), trytes.end(), &isValidTryte) == trytes.end(); } bool isArrayOfHashes(const std::vector<Trytes>& hashes) { for (const auto& hash : hashes) { if (hash.length() != SeedLength && hash.length() != SeedLengthWithChecksum) { return false; } if (!isValidTrytes(hash)) { return false; } } return true; } bool isValidHash(const Trytes& s) { return s.length() == HashLength && isValidTrytes(s); } std::vector<int8_t> tritsToBytes(const Trits& trits) { size_t i = trits.size(); // strip leading zeroes; while (i && !trits[i - 1]) { i--; } if (i == 0) { return std::vector<int8_t>(ByteHashLength, 0); } std::vector<uint32_t> data(1, 0); int8_t sign = trits[i - 1]; for (; i > 0; --i) { // multiply by 3 uint64_t sum = 0; for (size_t j = 0; j < data.size(); ++j) { sum += data[j] + (static_cast<uint64_t>(data[j]) << 1); data[j] = static_cast<uint32_t>(sum & 0xffffffff); sum >>= 32; } if (sum != 0) { data.push_back(static_cast<uint32_t>(sum & 0xffffffff)); } switch (sign * trits[i - 1]) { case 1: // increment by 1 for (size_t j = 0; j < data.size(); ++j) { data[j] = data[j] + 1; if (data[j]) { break; } } if (!data.back()) { data.push_back(1); } break; case -1: // decrement by 1 uint8_t carry = 0; for (size_t j = 0; j < data.size(); ++j) { data[j] = data[j] + 0xffffffff + carry; carry = data[j] != 0xffffffff; } if (!data.back()) { data.pop_back(); } break; } } uint32_t msdw = data.back(); size_t j = 32; for (; j > 0 && !(msdw & (0x1 << (j - 1))); --j) ; size_t nr_bytes = ((data.size() - 1) << 2) + ((j + 7) >> 3); // negate two's complement if sign is negative if (sign == -1) { size_t i = 0; for (; i < data.size(); ++i) { data[i] = ~data[i] + 1; if (data[i]) { ++i; break; } } for (; i < data.size(); ++i) { data[i] = ~data[i]; } } // read out the bytes std::vector<int8_t> bytes(nr_bytes); uint32_t dw = 0; for (size_t i = 0; i < nr_bytes; ++i) { if (!(i & 0x3)) { dw = data[i >> 2]; } bytes[nr_bytes - i - 1] = static_cast<int8_t>(dw & 0xff); dw >>= 8; } std::vector<int8_t> res(48, sign == 1 ? 0 : -1); std::copy(bytes.begin(), bytes.end(), res.begin() + ByteHashLength - nr_bytes); return res; } Trits bytesToTrits(const std::vector<int8_t>& bytes) { int8_t sign = bytes.empty() || bytes[0] >= 0 ? 1 : -1; size_t nr_bytes = bytes.size(); size_t j = (nr_bytes + 3) >> 2; std::vector<uint32_t> div(j, 0); uint32_t dw = sign == 1 ? 0 : (0xffffffff << 8); for (size_t i = 0; i < nr_bytes; ++i) { dw |= static_cast<uint8_t>(bytes[i]); if (!((nr_bytes - i - 1) & 0x3)) { div[(nr_bytes - i - 1) >> 2] = dw; dw = 0; } dw <<= 8; } // negate two's complement if sign is negative if (sign == -1) { size_t i = 0; for (; i < div.size(); ++i) { div[i] = ~div[i] + 1; if (div[i]) { ++i; break; } } for (; i < div.size(); ++i) { div[i] = ~div[i]; } } std::vector<int8_t> trits; // strip leading zeros while (j && !div[j - 1]) { --j; } while (j) { // divide by 3 uint64_t rem = 0; for (size_t k = j; k > 0; --k) { rem <<= 32; rem += div[k - 1]; div[k - 1] = static_cast<uint32_t>(rem / 3); rem %= 3; } if (!div[j - 1]) { j--; } if (rem > 1) { // increment by 1 for (size_t k = 0; k < j; ++k) { div[k] = div[k] + 1; if (div[k]) { break; } } if (!j || !div[j - 1]) { div[j] = 1; j++; } rem -= 3; } trits.push_back(sign * static_cast<int8_t>(rem)); } trits.resize(TritHashLength, 0); return trits; } Trits trytesToTrits(const Trytes& trytes) { Trits trits; trits.reserve(trytes.size() * 3); for (std::size_t i = 0; i < trytes.size(); i++) { std::size_t index = tryteIndex(trytes[i]); trits.insert(std::end(trits), std::begin(trytesTrits[index]), std::end(trytesTrits[index])); } return trits; } Trytes tritsToTrytes(const Trits& trits) { return tritsToTrytes(trits, trits.size()); } Trytes tritsToTrytes(const Trits& trits, std::size_t length) { Trytes trytes; for (std::size_t i = 0; i < length; i += 3) { int8_t idx = trits[i] + trits[i + 1] * 3 + trits[i + 2] * 9; if (idx < 0) { idx += TryteAlphabetLength; } trytes += TryteAlphabet[idx]; } return trytes; } Types::Trits intToTrits(const int64_t& value) { Types::Trits trits; uint64_t absoluteValue = std::abs(value); while (absoluteValue > 0) { int8_t remainder = absoluteValue % 3; absoluteValue = absoluteValue / 3; if (remainder > 1) { remainder = -1; absoluteValue++; } trits.push_back(remainder); } if (value < 0) { std::transform(std::begin(trits), std::end(trits), std::begin(trits), std::negate<int>()); } return trits; } Types::Trits intToTrits(const int64_t& value, std::size_t length) { auto res = intToTrits(value); res.resize(length, 0); return res; } } // namespace Types } // namespace IOTA <commit_msg>Int to trits optimization (#237)<commit_after>// // MIT License // // Copyright (c) 2017-2018 Thibault Martinez and Simon Ninon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // #include <algorithm> #include <array> #include <cmath> #include <cstdlib> #include <functional> #include <iota/constants.hpp> #include <iota/types/trinary.hpp> namespace IOTA { namespace Types { static constexpr std::array<std::array<int8_t, 3>, TryteAlphabetLength> trytesTrits{ { { { 0, 0, 0 } }, { { 1, 0, 0 } }, { { -1, 1, 0 } }, { { 0, 1, 0 } }, { { 1, 1, 0 } }, { { -1, -1, 1 } }, { { 0, -1, 1 } }, { { 1, -1, 1 } }, { { -1, 0, 1 } }, { { 0, 0, 1 } }, { { 1, 0, 1 } }, { { -1, 1, 1 } }, { { 0, 1, 1 } }, { { 1, 1, 1 } }, { { -1, -1, -1 } }, { { 0, -1, -1 } }, { { 1, -1, -1 } }, { { -1, 0, -1 } }, { { 0, 0, -1 } }, { { 1, 0, -1 } }, { { -1, 1, -1 } }, { { 0, 1, -1 } }, { { 1, 1, -1 } }, { { -1, -1, 0 } }, { { 0, -1, 0 } }, { { 1, -1, 0 } }, { { -1, 0, 0 } } } }; int8_t tryteIndex(const char& tryte) { if (tryte == '9') { return 0; } if ('A' <= tryte && tryte <= 'Z') { return tryte - 'A' + 1; } return -1; } bool isValidTryte(const char& tryte) { return tryteIndex(tryte) >= 0; } bool isValidTrytes(const Trytes& trytes) { return std::find_if_not(trytes.begin(), trytes.end(), &isValidTryte) == trytes.end(); } bool isArrayOfHashes(const std::vector<Trytes>& hashes) { for (const auto& hash : hashes) { if (hash.length() != SeedLength && hash.length() != SeedLengthWithChecksum) { return false; } if (!isValidTrytes(hash)) { return false; } } return true; } bool isValidHash(const Trytes& s) { return s.length() == HashLength && isValidTrytes(s); } std::vector<int8_t> tritsToBytes(const Trits& trits) { size_t i = trits.size(); // strip leading zeroes; while (i && !trits[i - 1]) { i--; } if (i == 0) { return std::vector<int8_t>(ByteHashLength, 0); } std::vector<uint32_t> data(1, 0); int8_t sign = trits[i - 1]; for (; i > 0; --i) { // multiply by 3 uint64_t sum = 0; for (size_t j = 0; j < data.size(); ++j) { sum += data[j] + (static_cast<uint64_t>(data[j]) << 1); data[j] = static_cast<uint32_t>(sum & 0xffffffff); sum >>= 32; } if (sum != 0) { data.push_back(static_cast<uint32_t>(sum & 0xffffffff)); } switch (sign * trits[i - 1]) { case 1: // increment by 1 for (size_t j = 0; j < data.size(); ++j) { data[j] = data[j] + 1; if (data[j]) { break; } } if (!data.back()) { data.push_back(1); } break; case -1: // decrement by 1 uint8_t carry = 0; for (size_t j = 0; j < data.size(); ++j) { data[j] = data[j] + 0xffffffff + carry; carry = data[j] != 0xffffffff; } if (!data.back()) { data.pop_back(); } break; } } uint32_t msdw = data.back(); size_t j = 32; for (; j > 0 && !(msdw & (0x1 << (j - 1))); --j) ; size_t nr_bytes = ((data.size() - 1) << 2) + ((j + 7) >> 3); // negate two's complement if sign is negative if (sign == -1) { size_t i = 0; for (; i < data.size(); ++i) { data[i] = ~data[i] + 1; if (data[i]) { ++i; break; } } for (; i < data.size(); ++i) { data[i] = ~data[i]; } } // read out the bytes std::vector<int8_t> bytes(nr_bytes); uint32_t dw = 0; for (size_t i = 0; i < nr_bytes; ++i) { if (!(i & 0x3)) { dw = data[i >> 2]; } bytes[nr_bytes - i - 1] = static_cast<int8_t>(dw & 0xff); dw >>= 8; } std::vector<int8_t> res(48, sign == 1 ? 0 : -1); std::copy(bytes.begin(), bytes.end(), res.begin() + ByteHashLength - nr_bytes); return res; } Trits bytesToTrits(const std::vector<int8_t>& bytes) { int8_t sign = bytes.empty() || bytes[0] >= 0 ? 1 : -1; size_t nr_bytes = bytes.size(); size_t j = (nr_bytes + 3) >> 2; std::vector<uint32_t> div(j, 0); uint32_t dw = sign == 1 ? 0 : (0xffffffff << 8); for (size_t i = 0; i < nr_bytes; ++i) { dw |= static_cast<uint8_t>(bytes[i]); if (!((nr_bytes - i - 1) & 0x3)) { div[(nr_bytes - i - 1) >> 2] = dw; dw = 0; } dw <<= 8; } // negate two's complement if sign is negative if (sign == -1) { size_t i = 0; for (; i < div.size(); ++i) { div[i] = ~div[i] + 1; if (div[i]) { ++i; break; } } for (; i < div.size(); ++i) { div[i] = ~div[i]; } } std::vector<int8_t> trits; // strip leading zeros while (j && !div[j - 1]) { --j; } while (j) { // divide by 3 uint64_t rem = 0; for (size_t k = j; k > 0; --k) { rem <<= 32; rem += div[k - 1]; div[k - 1] = static_cast<uint32_t>(rem / 3); rem %= 3; } if (!div[j - 1]) { j--; } if (rem > 1) { // increment by 1 for (size_t k = 0; k < j; ++k) { div[k] = div[k] + 1; if (div[k]) { break; } } if (!j || !div[j - 1]) { div[j] = 1; j++; } rem -= 3; } trits.push_back(sign * static_cast<int8_t>(rem)); } trits.resize(TritHashLength, 0); return trits; } Trits trytesToTrits(const Trytes& trytes) { Trits trits; trits.reserve(trytes.size() * 3); for (std::size_t i = 0; i < trytes.size(); i++) { std::size_t index = tryteIndex(trytes[i]); trits.insert(std::end(trits), std::begin(trytesTrits[index]), std::end(trytesTrits[index])); } return trits; } Trytes tritsToTrytes(const Trits& trits) { return tritsToTrytes(trits, trits.size()); } Trytes tritsToTrytes(const Trits& trits, std::size_t length) { Trytes trytes; for (std::size_t i = 0; i < length; i += 3) { int8_t idx = trits[i] + trits[i + 1] * 3 + trits[i + 2] * 9; if (idx < 0) { idx += TryteAlphabetLength; } trytes += TryteAlphabet[idx]; } return trytes; } Types::Trits intToTrits(const int64_t& value) { if (value == 0) return {}; Types::Trits trits; int sign = (value > 0) - (value < 0); uint64_t absoluteValue = value * sign; // pre-computed log3(e) static const double log3e = 0.91023922662683739361; // predict number of digits of value in base 3 with basic logarithms const int size = std::ceil(std::log(absoluteValue) * log3e) + 1; // reserving the right size will avoid reallocating in the loop, saving up time trits.reserve(size); while (absoluteValue > 0) { int8_t remainder = absoluteValue % 3; absoluteValue = absoluteValue / 3; if (remainder > 1) { remainder = -1; absoluteValue++; } trits.push_back(remainder * sign); } return trits; } Types::Trits intToTrits(const int64_t& value, std::size_t length) { auto res = intToTrits(value); res.resize(length, 0); return res; } } // namespace Types } // namespace IOTA <|endoftext|>
<commit_before>/******************************************************************************* Copyright The University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // File manager //============================================================================== #include "corecliutils.h" #include "filemanager.h" //============================================================================== #include <QApplication> #include <QFile> #include <QTimer> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== FileManager::FileManager() : mFiles(QMap<QString, File *>()), mFilesReadable(QMap<QString, bool>()), mFilesWritable(QMap<QString, bool>()) { // Create our timer mTimer = new QTimer(this); // A connection to handle the timing out of our timer connect(mTimer, SIGNAL(timeout()), this, SLOT(checkFiles())); } //============================================================================== FileManager::~FileManager() { // Delete some internal objects delete mTimer; // Remove all the managed files foreach (File *file, mFiles) delete file; } //============================================================================== FileManager * FileManager::instance() { // Return the 'global' instance of our file manager class static FileManager instance; return static_cast<FileManager *>(globalInstance("OpenCOR::Core::FileManager::instance()", &instance)); } //============================================================================== FileManager::Status FileManager::manage(const QString &pFileName, const File::Type &pType, const QString &pUrl) { // Manage the given file, should it not be already managed QString nativeFileName = nativeCanonicalFileName(pFileName); if (QFile::exists(nativeFileName)) { if (file(nativeFileName)) { return AlreadyManaged; } else { // The file isn't already managed, so add it to our list of managed // files and let people know about it being now managed mFiles.insert(nativeFileName, new File(nativeFileName, pType, pUrl)); if (!mTimer->isActive()) mTimer->start(1000); emit fileManaged(nativeFileName); return Added; } } else { return DoesNotExist; } } //============================================================================== FileManager::Status FileManager::unmanage(const QString &pFileName) { // Unmanage the given file, should it be managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { // The file is managed, so we can remove it mFiles.remove(nativeFileName); delete nativeFile; if (mFiles.isEmpty()) mTimer->stop(); emit fileUnmanaged(nativeFileName); return Removed; } else { return NotManaged; } } //============================================================================== File * FileManager::file(const QString &pFileName) const { // Return the File object, if any, associated with the given file return mFiles.value(nativeCanonicalFileName(pFileName), 0); } //============================================================================== QString FileManager::sha1(const QString &pFileName) const { // Return the SHA-1 value of the given file, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->sha1(); else return QString(); } //============================================================================== void FileManager::reset(const QString &pFileName) { // Reset the given file, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) nativeFile->reset(); } //============================================================================== int FileManager::newIndex(const QString &pFileName) const { // Return the given file's new index, if it is being managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->newIndex(); else return 0; } //============================================================================== QString FileManager::url(const QString &pFileName) const { // Return the given file's URL, if it is being managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->url(); else return QString(); } //============================================================================== bool FileManager::isDifferent(const QString &pFileName) const { // Return whether the given file, if it is being managed, is different from // its corresponding physical version File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isDifferent(); else return false; } //============================================================================== bool FileManager::isDifferent(const QString &pFileName, const QByteArray &pFileContents) const { // Return whether the given file, if it is being managed, has the same // contents has the given one File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isDifferent(pFileContents); else return false; } //============================================================================== bool FileManager::isNew(const QString &pFileName) const { // Return whether the given file, if it is being managed, is new File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isNew(); else return false; } //============================================================================== bool FileManager::isRemote(const QString &pFileName) const { // Return whether the given file, if it is being managed, is a remote one File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isRemote(); else return false; } //============================================================================== bool FileManager::isModified(const QString &pFileName) const { // Return whether the given file, if it is being managed, has been modified File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isModified(); else return false; } //============================================================================== bool FileManager::isLocalNewOrModified(const QString &pFileName) const { // Return whether the given file is a local one, as well as is new or // modified return !isRemote(pFileName) && (isNew(pFileName) || isModified(pFileName)); } //============================================================================== void FileManager::makeNew(const QString &pFileName) { // Make the given file new, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) { QString fileName; if (newFile(fileName)) nativeFile->makeNew(fileName); } } //============================================================================== void FileManager::setModified(const QString &pFileName, const bool &pModified) { // Set the modified state of the given file, should it be managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile && nativeFile->setModified(pModified)) emit fileModified(nativeFileName); } //============================================================================== void FileManager::setDependenciesModified(const QString &pFileName, const bool &pModified) { // Set the dependencies modified state of the given file, should it be // managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) nativeFile->setDependenciesModified(pModified); } //============================================================================== bool FileManager::isReadable(const QString &pFileName) const { // Return whether the given file, if it is being managed, is readable File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isReadable(); else return false; } //============================================================================== bool FileManager::isWritable(const QString &pFileName) const { // Return whether the given file, if it is being managed, is writable File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isWritable(); else return false; } //============================================================================== bool FileManager::isReadableAndWritable(const QString &pFileName) const { // Return whether the given file, if it is being managed, is readable and // writable return isReadable(pFileName) && isWritable(pFileName); } //============================================================================== bool FileManager::isLocked(const QString &pFileName) const { // Return whether the given file, if it is being managed, is locked File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isLocked(); else return false; } //============================================================================== FileManager::Status FileManager::setLocked(const QString &pFileName, const bool &pLocked) { // Set the locked status of the given file, should it be managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { File::Status status = nativeFile->setLocked(pLocked); if (status == File::LockedSet) emitFilePermissionsChanged(nativeFileName); if (status == File::LockedNotNeeded) return LockedNotNeeded; else if (status == File::LockedSet) return LockedSet; else return LockedNotSet; } else { return NotManaged; } } //============================================================================== QStringList FileManager::dependencies(const QString &pFileName) const { // Return the given file's dependencies, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->dependencies(); else return QStringList(); } //============================================================================== void FileManager::setDependencies(const QString &pFileName, const QStringList &pDependencies) { // Set the dependencies of the given file, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) nativeFile->setDependencies(pDependencies); } //============================================================================== void FileManager::reload(const QString &pFileName, const bool &pForceFileChanged) { // Make sure that the given file is managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { // The file is managed, so determine whether the file itself has been // modified, reset its settings and let people know that it should be // reloaded File::Status nativeFileStatus = nativeFile->check(); nativeFile->reset(); emit fileReloaded(nativeFileName, pForceFileChanged || (nativeFileStatus == File::Changed) || (nativeFileStatus == File::AllChanged)); } } //============================================================================== bool FileManager::newFile(QString &pFileName, const QByteArray &pContents) { // Retrieve a temporary file name for our new file QString fileName = temporaryFileName(); // Create a new file with the given contents if (writeFileContentsToFile(fileName, pContents)) { pFileName = fileName; return true; } else { pFileName = QString(); return false; } } //============================================================================== FileManager::Status FileManager::create(const QString &pUrl, const QByteArray &pContents) { // Create a new file QString fileName; if (newFile(fileName, pContents)) { // Let people know that we have created a file emit fileCreated(fileName, pUrl); return Created; } else { return NotCreated; } } //============================================================================== FileManager::Status FileManager::rename(const QString &pOldFileName, const QString &pNewFileName) { // Make sure that the given 'old' file is managed QString oldNativeFileName = nativeCanonicalFileName(pOldFileName); File *nativeFile = file(oldNativeFileName); if (nativeFile) { // The 'old' file is managed, so rename it and let people know about it QString newNativeFileName = nativeCanonicalFileName(pNewFileName); if (nativeFile->setFileName(newNativeFileName)) { mFiles.insert(newNativeFileName, mFiles.value(oldNativeFileName)); mFiles.remove(oldNativeFileName); emit fileRenamed(oldNativeFileName, newNativeFileName); return Renamed; } else { return RenamingNotNeeded; } } else { return NotManaged; } } //============================================================================== FileManager::Status FileManager::duplicate(const QString &pFileName) { // Make sure that the given file is managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) { // The file is managed, so retrieve its contents QByteArray fileContents; if (readFileContentsFromFile(pFileName, fileContents)) { // Now, we can create a new file, which contents will be that of our // given file QString fileName; if (newFile(fileName, fileContents)) { // Let people know that we have duplicated a file emit fileDuplicated(fileName); return Duplicated; } else { return NotDuplicated; } } else { return NotDuplicated; } } else { return NotManaged; } } //============================================================================== void FileManager::save(const QString &pFileName) { // Make sure that the given file is managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { // The file is managed, so reset its settings and let people know that // it has been saved nativeFile->reset(false); emit fileSaved(nativeFileName); } } //============================================================================== int FileManager::count() const { // Return the number of files currently being managed return mFiles.count(); } //============================================================================== void FileManager::emitFilePermissionsChanged(const QString &pFileName) { // Update our internals and let people know that the given file has had its // permissions changed mFilesReadable.insert(pFileName, isReadable(pFileName)); mFilesWritable.insert(pFileName, isWritable(pFileName)); emit filePermissionsChanged(pFileName); } //============================================================================== void FileManager::checkFiles() { // Check our various files, as well as their locked status, but only if they // are not being ignored foreach (File *file, mFiles) { QString fileName = file->fileName(); File::Status fileStatus = file->check(); switch (fileStatus) { case File::Changed: case File::DependenciesChanged: case File::AllChanged: // The file and/or one or several of its dependencies has changed, // so let people know about it emit fileChanged(fileName, (fileStatus == File::Changed) || (fileStatus == File::AllChanged), (fileStatus == File::DependenciesChanged) || (fileStatus == File::AllChanged)); break; case File::Unchanged: // The file has neither changed nor been deleted, so check whether // its permissions have changed if ( (mFilesReadable.value(fileName, false) != isReadable(fileName)) || (mFilesWritable.value(fileName, false) != isWritable(fileName)) || !( mFilesReadable.contains(fileName) && mFilesWritable.contains(fileName))) { emitFilePermissionsChanged(fileName); } break; case File::Deleted: // The file has been deleted, so let people know about it emit fileDeleted(fileName); break; default: // Not a relevant status, so do nothing ; } } } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Copyright The University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // File manager //============================================================================== #include "corecliutils.h" #include "filemanager.h" //============================================================================== #include <QApplication> #include <QFile> #include <QTimer> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== FileManager::FileManager() : mFiles(QMap<QString, File *>()), mFilesReadable(QMap<QString, bool>()), mFilesWritable(QMap<QString, bool>()) { // Create our timer mTimer = new QTimer(this); // A connection to handle the timing out of our timer connect(mTimer, SIGNAL(timeout()), this, SLOT(checkFiles())); } //============================================================================== FileManager::~FileManager() { // Delete some internal objects delete mTimer; // Remove all the managed files foreach (File *file, mFiles) delete file; } //============================================================================== FileManager * FileManager::instance() { // Return the 'global' instance of our file manager class static FileManager instance; return static_cast<FileManager *>(globalInstance("OpenCOR::Core::FileManager::instance()", &instance)); } //============================================================================== FileManager::Status FileManager::manage(const QString &pFileName, const File::Type &pType, const QString &pUrl) { // Manage the given file, should it not be already managed QString nativeFileName = nativeCanonicalFileName(pFileName); if (QFile::exists(nativeFileName)) { if (file(nativeFileName)) { return AlreadyManaged; } else { // The file isn't already managed, so add it to our list of managed // files and let people know about it being now managed mFiles.insert(nativeFileName, new File(nativeFileName, pType, pUrl)); if (!mTimer->isActive()) mTimer->start(1000); emit fileManaged(nativeFileName); return Added; } } else { return DoesNotExist; } } //============================================================================== FileManager::Status FileManager::unmanage(const QString &pFileName) { // Unmanage the given file, should it be managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { // The file is managed, so we can remove it mFiles.remove(nativeFileName); delete nativeFile; if (mFiles.isEmpty()) mTimer->stop(); emit fileUnmanaged(nativeFileName); return Removed; } else { return NotManaged; } } //============================================================================== File * FileManager::file(const QString &pFileName) const { // Return the File object, if any, associated with the given file return mFiles.value(nativeCanonicalFileName(pFileName), 0); } //============================================================================== QString FileManager::sha1(const QString &pFileName) const { // Return the SHA-1 value of the given file, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->sha1(); else return QString(); } //============================================================================== void FileManager::reset(const QString &pFileName) { // Reset the given file, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) nativeFile->reset(); } //============================================================================== int FileManager::newIndex(const QString &pFileName) const { // Return the given file's new index, if it is being managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->newIndex(); else return 0; } //============================================================================== QString FileManager::url(const QString &pFileName) const { // Return the given file's URL, if it is being managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->url(); else return QString(); } //============================================================================== bool FileManager::isDifferent(const QString &pFileName) const { // Return whether the given file, if it is being managed, is different from // its corresponding physical version File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isDifferent(); else return false; } //============================================================================== bool FileManager::isDifferent(const QString &pFileName, const QByteArray &pFileContents) const { // Return whether the given file, if it is being managed, has the same // contents has the given one File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isDifferent(pFileContents); else return false; } //============================================================================== bool FileManager::isNew(const QString &pFileName) const { // Return whether the given file, if it is being managed, is new File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isNew(); else return false; } //============================================================================== bool FileManager::isRemote(const QString &pFileName) const { // Return whether the given file, if it is being managed, is a remote one File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isRemote(); else return false; } //============================================================================== bool FileManager::isModified(const QString &pFileName) const { // Return whether the given file, if it is being managed, has been modified File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isModified(); else return false; } //============================================================================== bool FileManager::isLocalNewOrModified(const QString &pFileName) const { // Return whether the given file is a local one, as well as is new or // modified return !isRemote(pFileName) && (isNew(pFileName) || isModified(pFileName)); } //============================================================================== void FileManager::makeNew(const QString &pFileName) { // Make the given file new, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) { QString fileName; if (newFile(fileName)) nativeFile->makeNew(fileName); } } //============================================================================== void FileManager::setModified(const QString &pFileName, const bool &pModified) { // Set the modified state of the given file, should it be managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile && nativeFile->setModified(pModified)) emit fileModified(nativeFileName); } //============================================================================== void FileManager::setDependenciesModified(const QString &pFileName, const bool &pModified) { // Set the dependencies modified state of the given file, should it be // managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) nativeFile->setDependenciesModified(pModified); } //============================================================================== bool FileManager::isReadable(const QString &pFileName) const { // Return whether the given file, if it is being managed, is readable File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isReadable(); else return false; } //============================================================================== bool FileManager::isWritable(const QString &pFileName) const { // Return whether the given file, if it is being managed, is writable File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isWritable(); else return false; } //============================================================================== bool FileManager::isReadableAndWritable(const QString &pFileName) const { // Return whether the given file, if it is being managed, is readable and // writable return isReadable(pFileName) && isWritable(pFileName); } //============================================================================== bool FileManager::isLocked(const QString &pFileName) const { // Return whether the given file, if it is being managed, is locked File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->isLocked(); else return false; } //============================================================================== FileManager::Status FileManager::setLocked(const QString &pFileName, const bool &pLocked) { // Set the locked status of the given file, should it be managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { File::Status status = nativeFile->setLocked(pLocked); if (status == File::LockedSet) emitFilePermissionsChanged(nativeFileName); if (status == File::LockedNotNeeded) return LockedNotNeeded; else if (status == File::LockedSet) return LockedSet; else return LockedNotSet; } else { return NotManaged; } } //============================================================================== QStringList FileManager::dependencies(const QString &pFileName) const { // Return the given file's dependencies, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) return nativeFile->dependencies(); else return QStringList(); } //============================================================================== void FileManager::setDependencies(const QString &pFileName, const QStringList &pDependencies) { // Set the dependencies of the given file, should it be managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) nativeFile->setDependencies(pDependencies); } //============================================================================== void FileManager::reload(const QString &pFileName, const bool &pForceFileChanged) { // Make sure that the given file is managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { // The file is managed, so determine whether the file itself has been // modified, reset its settings and let people know that it should be // reloaded File::Status nativeFileStatus = nativeFile->check(); nativeFile->reset(); emit fileReloaded(nativeFileName, pForceFileChanged || (nativeFileStatus == File::Changed) || (nativeFileStatus == File::AllChanged)); } } //============================================================================== bool FileManager::newFile(QString &pFileName, const QByteArray &pContents) { // Retrieve a temporary file name for our new file QString fileName = temporaryFileName(); // Create a new file with the given contents if (writeFileContentsToFile(fileName, pContents)) { pFileName = fileName; return true; } else { pFileName = QString(); return false; } } //============================================================================== FileManager::Status FileManager::create(const QString &pUrl, const QByteArray &pContents) { // Create a new file QString fileName; if (newFile(fileName, pContents)) { // Let people know that we have created a new file emit fileCreated(fileName, pUrl); return Created; } else { return NotCreated; } } //============================================================================== FileManager::Status FileManager::rename(const QString &pOldFileName, const QString &pNewFileName) { // Make sure that the given 'old' file is managed QString oldNativeFileName = nativeCanonicalFileName(pOldFileName); File *nativeFile = file(oldNativeFileName); if (nativeFile) { // The 'old' file is managed, so rename it and let people know about it QString newNativeFileName = nativeCanonicalFileName(pNewFileName); if (nativeFile->setFileName(newNativeFileName)) { mFiles.insert(newNativeFileName, mFiles.value(oldNativeFileName)); mFiles.remove(oldNativeFileName); emit fileRenamed(oldNativeFileName, newNativeFileName); return Renamed; } else { return RenamingNotNeeded; } } else { return NotManaged; } } //============================================================================== FileManager::Status FileManager::duplicate(const QString &pFileName) { // Make sure that the given file is managed File *nativeFile = file(nativeCanonicalFileName(pFileName)); if (nativeFile) { // The file is managed, so retrieve its contents QByteArray fileContents; if (readFileContentsFromFile(pFileName, fileContents)) { // Now, we can create a new file, which contents will be that of our // given file QString fileName; if (newFile(fileName, fileContents)) { // Let people know that we have duplicated a file emit fileDuplicated(fileName); return Duplicated; } else { return NotDuplicated; } } else { return NotDuplicated; } } else { return NotManaged; } } //============================================================================== void FileManager::save(const QString &pFileName) { // Make sure that the given file is managed QString nativeFileName = nativeCanonicalFileName(pFileName); File *nativeFile = file(nativeFileName); if (nativeFile) { // The file is managed, so reset its settings and let people know that // it has been saved nativeFile->reset(false); emit fileSaved(nativeFileName); } } //============================================================================== int FileManager::count() const { // Return the number of files currently being managed return mFiles.count(); } //============================================================================== void FileManager::emitFilePermissionsChanged(const QString &pFileName) { // Update our internals and let people know that the given file has had its // permissions changed mFilesReadable.insert(pFileName, isReadable(pFileName)); mFilesWritable.insert(pFileName, isWritable(pFileName)); emit filePermissionsChanged(pFileName); } //============================================================================== void FileManager::checkFiles() { // Check our various files, as well as their locked status, but only if they // are not being ignored foreach (File *file, mFiles) { QString fileName = file->fileName(); File::Status fileStatus = file->check(); switch (fileStatus) { case File::Changed: case File::DependenciesChanged: case File::AllChanged: // The file and/or one or several of its dependencies has changed, // so let people know about it emit fileChanged(fileName, (fileStatus == File::Changed) || (fileStatus == File::AllChanged), (fileStatus == File::DependenciesChanged) || (fileStatus == File::AllChanged)); break; case File::Unchanged: // The file has neither changed nor been deleted, so check whether // its permissions have changed if ( (mFilesReadable.value(fileName, false) != isReadable(fileName)) || (mFilesWritable.value(fileName, false) != isWritable(fileName)) || !( mFilesReadable.contains(fileName) && mFilesWritable.contains(fileName))) { emitFilePermissionsChanged(fileName); } break; case File::Deleted: // The file has been deleted, so let people know about it emit fileDeleted(fileName); break; default: // Not a relevant status, so do nothing ; } } } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include <RcppArmadillo.h> #include "bootstrappers.h" #include "inference.h" #include "gmwm_logic.h" // Used for scales_cpp #include "wave_variance.h" #include "analytical_matrix_derivatives.h" #include "model_selection.h" #include "ts_model_cpp.h" //#include "automatic_models.h" using namespace Rcpp; // ---- START helper functions //' @title Build List of Unique Models //' @description Creates a set containing unique strings. //' @param combs A \code{mat} that is a binary matrix (0,1) containing the combinations of different variables. //' @param x A \code{vec<string>} that contains a list of model descriptors. //' @return A \code{set<string>} that contains the list of unique models. // [[Rcpp::export]] std::set<std::vector<std::string > > build_model_set(const arma::mat& combs, std::vector <std::string> x) { std::set<std::vector<std::string > > models; for(unsigned int i = 0; i < combs.n_rows; i++) { std::vector< std::string > tmp; for(unsigned int j = 0; j < combs.n_cols; j++){ if(combs(i,j) == 1){ tmp.push_back( x[j] ); } } models.insert(tmp); } return models; } //' @title Conversion function of Vector to Set //' @description Converts a vector into a set //' @param x A \code{vec<vec<string>>} that contains a list of model descriptors. //' @return A \code{set<vector<string>>} that contains the list of unique models. // [[Rcpp::export]] std::set<std::vector<std::string> > vector_to_set(std::vector<std::vector<std::string > > model_str){ // Number of columns to process // Create a set of unique models. std::set<std::vector<std::string > > models; for(std::vector<std::vector<std::string> >::const_iterator it = model_str.begin(); it != model_str.end(); ++it) { models.insert(*it); } return models; } //' @title Find the Common Denominator of the Models //' @description Determines the common denominator among models //' @param x A \code{vector< vector<string> >} that contains all possible models under consideration //' @return A \code{vector<string>} that contains the terms of the common denominator of all models // [[Rcpp::export]] std::vector<std::string> find_full_model(std::vector<std::vector<std::string> > x ){ // Set up iterators to go over the sets std::vector<std::vector<std::string> >::const_iterator it; std::vector<std::string>::const_iterator it2; // Figure out all common terms // AR1s can have an infinite amount of combinations unsigned int maxAR1s = 0; // In the mean time, WN, RW, QN, and DR, can only appear once in a model. bool WN = false; bool RW = false; bool QN = false; bool DR = false; // Begin iterating through the set. for(it = x.begin(); it != x.end(); ++it) { // Create an internal counter of AR1s for a given vector unsigned int num_AR1s = 0; // Iterate through the vector for (it2 = (*it).begin(); it2 != (*it).end(); ++it2){ if(*it2 == "AR1"){ num_AR1s++; // For each AR1 detected, increment by 1. }else if(*it2 == "WN"){ if(!WN){ WN = true; // If WN has yet to be set, set it here. } }else if(*it2 == "RW"){ if(!RW){ RW = true; } }else if(*it2 == "QN"){ if(!QN){ QN = true; } }else if(*it2 == "DR"){ if(!DR){ DR = true; } } // end if block // Does this model have more AR1s than previous models? Y/N? if(num_AR1s > maxAR1s){ maxAR1s = num_AR1s; } } // end inner for } // end outer for // Create a vector holding all the model terms std::vector<std::string> out(maxAR1s+WN+RW+QN+DR); // Begin assigning the terms unsigned int i; for(i = 0; i < maxAR1s; i++){ out[i] = "AR1"; } if(WN){ out[i] = "WN"; i++; } if(RW){ out[i] = "RW"; i++; } if(QN){ out[i] = "QN"; i++; } if(DR){ out[i] = "DR"; i++; } return out; } arma::rowvec bs_optim_calc(const arma::vec& theta, const std::vector<std::string>& desc, const arma::field<arma::vec>& objdesc, std::string model_type, const arma::vec& scales, const arma::mat& omega, unsigned int N, double obj_value, double alpha, std::string compute_v, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff){ arma::field<arma::mat> bso = opt_n_gof_bootstrapper(theta, desc, objdesc, scales, model_type, N, robust, eff, alpha, H); arma::mat cov_nu_nu_theta = bso(0); arma::mat bs_obj_values = bso(1); double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega)); arma::rowvec temp(4); temp(0) = obj_value; temp(1) = optimism; temp(2) = obj_value + optimism; temp(3) = arma::as_scalar(bootstrap_gof_test(obj_value, bs_obj_values, alpha, false).row(0)); return temp; } arma::rowvec asympt_calc(const arma::vec& theta, const std::vector<std::string>& desc, const arma::field<arma::vec>& objdesc, std::string model_type, const arma::vec& scales, const arma::mat& V, const arma::mat& omega, const arma::vec& wv_empir, const arma::vec& theo, double obj_value){ // Take derivatives arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales); /* A note to someone in the future... * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix * and the model_score diff (theo-wv_empir). */ // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file) arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(theo - wv_empir)); arma::rowvec temp(4); arma::vec result = model_score(A, D, omega, V, obj_value); temp(0) = obj_value; temp(1) = arma::as_scalar(result.row(1)); temp(2) = arma::as_scalar(result.row(0)); temp(3) = arma::as_scalar( gof_test(theta, desc, objdesc, model_type, scales, V, wv_empir).row(1) ); // GoF return temp; } // ---- End helper functions arma::field<arma::field<arma::mat> > model_select(const arma::mat& data, const std::set<std::vector<std::string > >& models, const std::vector< std::string >& full_model, std::string model_type, bool bs_optimism, double alpha, std::string compute_v, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff){ // Number of data points unsigned int N = data.n_rows; // Number of models unsigned int num_models = models.size(); // Make an iterator to iterator through it std::set<std::vector<std::string > > ::const_iterator iter; iter = models.begin(); // Get the first model std::vector<std::string> desc = full_model; // Find where the results should be input. (No protection needed, we know it is in the matrix) unsigned int full_model_index = std::distance(models.begin(),models.find(full_model)); // Build the fields off of the first model's description arma::vec theta = model_theta(desc); arma::field<arma::vec> objdesc = model_objdesc(desc); // Build matrix to store results arma::mat results(num_models, 4); std::cout << "Processing model 1 out of " << num_models << std::endl; // Obtain the largest models information arma::field<arma::mat> master = gmwm_master_cpp(data, theta, desc, objdesc, model_type, true, //starting alpha, "fast", // compute V K, H, G, robust, eff); // Theta update theta = master(0); // Define WV Empirical arma::vec wv_empir = master(2); // Get the original "FAST" matrix arma::mat orgV = master(6); // Original V // Take the inverse arma::mat omega = inv(orgV); // Original V => Omega // Get expect_diff for guesses with DR double expect_diff = arma::as_scalar(master(7)); // Obtain the theoretical WV arma::vec theo = master(8); // Obtain the obj_value of the function double obj_value = arma::as_scalar(master(10)); // Calculate the values of the Scales arma::vec scales = scales_cpp(floor(log2(N))); // ------------------------------------ // Here we set up specifics that are used not in a specific mode. // Asymptotic ---- // Get bootstrapped V arma::mat V; // Bootstrap ---- // Hold optimism result arma::mat cov_nu_nu_theta; // Hold the bootstrapped obj values arma::vec bs_obj_values; if(bs_optimism){ results.row(full_model_index) = bs_optim_calc(theta, desc, objdesc, model_type, scales, omega, N, obj_value, alpha, compute_v, K, H, G, robust, eff); }else{ std::cout << "One time computation of the V matrix via bootstrap... Please stand by." << std::endl; V = cov_bootstrapper(theta, desc, objdesc, N, robust, eff, H, false); // Bootstrapped V (largest model) // Calculate the model score according to model selection criteria paper results.row(full_model_index) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value); } // Initialize counter to keep track of values unsigned int count = 0; unsigned int countModels = 1; while(iter != models.end()){ if(full_model_index != count){ countModels++; std::cout << "Processing model " << countModels << " out of " << num_models << std::endl; // Get the first model desc = *iter; // Build the fields off of the first model's description theta = model_theta(desc); objdesc = model_objdesc(desc); // Run the update version of the GMWM arma::field<arma::mat> update = gmwm_update_cpp(theta, desc, objdesc, model_type, N, expect_diff, orgV, scales, wv_empir, true, //starting "fast", K,H,G, robust,eff); // Theta update theta = update(0); // Update theo theo = update(3); // Update objective function obj_value = arma::as_scalar(update(5)); if(bs_optimism){ results.row(count) = bs_optim_calc(theta, desc, objdesc, model_type, scales, omega, N, obj_value, alpha, compute_v, K, H, G, robust, eff); }else{ // Calculate the model score according to model selection criteria paper results.row(count) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value); } } // end if // Increment iterator iter++; // Increase count count++; } arma::field< arma::field<arma::mat> > out(1); arma::field<arma::mat> ms(1); ms(0) = results; out(0) = ms; return out; } // [[Rcpp::export]] arma::field< arma::field<arma::field<arma::mat> > > rank_models(const arma::vec& data, const std::vector<std::vector < std::string > >& model_str, const std::vector< std::string >& full_model, double alpha, std::string compute_v, std::string model_type, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff, bool bs_optimism){ std::set<std::vector < std::string > > models = vector_to_set(model_str); arma::field< arma::field<arma::field<arma::mat> > > h(1); h(0) = model_select(data, models, full_model, model_type, bs_optimism, alpha, compute_v, K, H, G, robust, eff); return h; } // [[Rcpp::export]] arma::field< arma::field<arma::field<arma::mat> > > auto_imu(const arma::mat& data, const arma::mat& combs, const std::vector< std::string >& full_model, double alpha, std::string compute_v, std::string model_type, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff, bool bs_optimism){ // Number of columns to process unsigned int V = data.n_cols; // Create a set of unique models. std::set<std::vector<std::string > > models = build_model_set(combs, full_model); arma::field< arma::field<arma::field<arma::mat> > > h(V); for(unsigned int i = 0; i < V; i++){ h(i) = model_select(data.col(i), models, full_model, model_type, bs_optimism, alpha, compute_v, K, H, G, robust, eff); } return h; } <commit_msg>Added in steph's hack...<commit_after>#include <RcppArmadillo.h> #include "bootstrappers.h" #include "inference.h" #include "gmwm_logic.h" // Used for scales_cpp #include "wave_variance.h" #include "analytical_matrix_derivatives.h" #include "model_selection.h" #include "ts_model_cpp.h" #include "ts_checks.h" //#include "automatic_models.h" using namespace Rcpp; // ---- START helper functions unsigned int count_params(const std::vector<std::string>& desc){ std::map<std::string, int> w = count_models(desc); unsigned int params = 0; for (std::map<std::string, int>::iterator it = w.begin(); it!=w.end(); ++it) { if(it->first == "AR1" ){ params += 2*it->second; }else{ params += 1; } } return params; } //' @title Build List of Unique Models //' @description Creates a set containing unique strings. //' @param combs A \code{mat} that is a binary matrix (0,1) containing the combinations of different variables. //' @param x A \code{vec<string>} that contains a list of model descriptors. //' @return A \code{set<string>} that contains the list of unique models. // [[Rcpp::export]] std::set<std::vector<std::string > > build_model_set(const arma::mat& combs, std::vector <std::string> x) { std::set<std::vector<std::string > > models; for(unsigned int i = 0; i < combs.n_rows; i++) { std::vector< std::string > tmp; for(unsigned int j = 0; j < combs.n_cols; j++){ if(combs(i,j) == 1){ tmp.push_back( x[j] ); } } models.insert(tmp); } return models; } //' @title Conversion function of Vector to Set //' @description Converts a vector into a set //' @param x A \code{vec<vec<string>>} that contains a list of model descriptors. //' @return A \code{set<vector<string>>} that contains the list of unique models. // [[Rcpp::export]] std::set<std::vector<std::string> > vector_to_set(std::vector<std::vector<std::string > > model_str){ // Number of columns to process // Create a set of unique models. std::set<std::vector<std::string > > models; for(std::vector<std::vector<std::string> >::const_iterator it = model_str.begin(); it != model_str.end(); ++it) { models.insert(*it); } return models; } //' @title Find the Common Denominator of the Models //' @description Determines the common denominator among models //' @param x A \code{vector< vector<string> >} that contains all possible models under consideration //' @return A \code{vector<string>} that contains the terms of the common denominator of all models // [[Rcpp::export]] std::vector<std::string> find_full_model(std::vector<std::vector<std::string> > x ){ // Set up iterators to go over the sets std::vector<std::vector<std::string> >::const_iterator it; std::vector<std::string>::const_iterator it2; // Figure out all common terms // AR1s can have an infinite amount of combinations unsigned int maxAR1s = 0; // In the mean time, WN, RW, QN, and DR, can only appear once in a model. bool WN = false; bool RW = false; bool QN = false; bool DR = false; // Begin iterating through the set. for(it = x.begin(); it != x.end(); ++it) { // Create an internal counter of AR1s for a given vector unsigned int num_AR1s = 0; // Iterate through the vector for (it2 = (*it).begin(); it2 != (*it).end(); ++it2){ if(*it2 == "AR1"){ num_AR1s++; // For each AR1 detected, increment by 1. }else if(*it2 == "WN"){ if(!WN){ WN = true; // If WN has yet to be set, set it here. } }else if(*it2 == "RW"){ if(!RW){ RW = true; } }else if(*it2 == "QN"){ if(!QN){ QN = true; } }else if(*it2 == "DR"){ if(!DR){ DR = true; } } // end if block // Does this model have more AR1s than previous models? Y/N? if(num_AR1s > maxAR1s){ maxAR1s = num_AR1s; } } // end inner for } // end outer for // Create a vector holding all the model terms std::vector<std::string> out(maxAR1s+WN+RW+QN+DR); // Begin assigning the terms unsigned int i; for(i = 0; i < maxAR1s; i++){ out[i] = "AR1"; } if(WN){ out[i] = "WN"; i++; } if(RW){ out[i] = "RW"; i++; } if(QN){ out[i] = "QN"; i++; } if(DR){ out[i] = "DR"; i++; } return out; } arma::rowvec bs_optim_calc(const arma::vec& theta, const std::vector<std::string>& desc, const arma::field<arma::vec>& objdesc, std::string model_type, const arma::vec& scales, const arma::mat& omega, unsigned int N, double obj_value, double alpha, std::string compute_v, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff){ arma::field<arma::mat> bso = opt_n_gof_bootstrapper(theta, desc, objdesc, scales, model_type, N, robust, eff, alpha, H); arma::mat cov_nu_nu_theta = bso(0); arma::mat bs_obj_values = bso(1); double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega)); arma::rowvec temp(4); temp(0) = obj_value; temp(1) = optimism; temp(2) = obj_value + optimism; temp(3) = arma::as_scalar(bootstrap_gof_test(obj_value, bs_obj_values, alpha, false).row(0)); return temp; } arma::rowvec asympt_calc(const arma::vec& theta, const std::vector<std::string>& desc, const arma::field<arma::vec>& objdesc, std::string model_type, const arma::vec& scales, const arma::mat& V, const arma::mat& omega, const arma::vec& wv_empir, const arma::vec& theo, double obj_value){ // Take derivatives arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales); /* A note to someone in the future... * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix * and the model_score diff (theo-wv_empir). */ // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file) arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(theo - wv_empir)); arma::rowvec temp(4); arma::vec result = model_score(A, D, omega, V, obj_value); temp(0) = obj_value; temp(1) = arma::as_scalar(result.row(1)); temp(2) = arma::as_scalar(result.row(0)); temp(3) = arma::as_scalar( gof_test(theta, desc, objdesc, model_type, scales, V, wv_empir).row(1) ); // GoF return temp; } // ---- End helper functions arma::field<arma::field<arma::mat> > model_select(const arma::mat& data, const std::set<std::vector<std::string > >& models, const std::vector< std::string >& full_model, std::string model_type, bool bs_optimism, double alpha, std::string compute_v, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff){ // Number of data points unsigned int N = data.n_rows; // Number of models unsigned int num_models = models.size(); // Make an iterator to iterator through it std::set<std::vector<std::string > > ::const_iterator iter; iter = models.begin(); // Get the first model std::vector<std::string> desc = full_model; // Find where the results should be input. (No protection needed, we know it is in the matrix) unsigned int full_model_index = std::distance(models.begin(),models.find(full_model)); // Build the fields off of the first model's description arma::vec theta = model_theta(desc); arma::field<arma::vec> objdesc = model_objdesc(desc); // Build matrix to store results arma::mat results(num_models, 4); std::cout << "Processing model 1 out of " << num_models << std::endl; // Obtain the largest models information arma::field<arma::mat> master = gmwm_master_cpp(data, theta, desc, objdesc, model_type, true, //starting alpha, "fast", // compute V K, H, G, robust, eff); // Theta update theta = master(0); // Define WV Empirical arma::vec wv_empir = master(2); // Get the original "FAST" matrix arma::mat orgV = master(6); // Original V // Take the inverse arma::mat omega = inv(orgV); // Original V => Omega // Get expect_diff for guesses with DR double expect_diff = arma::as_scalar(master(7)); // Obtain the theoretical WV arma::vec theo = master(8); // Obtain the obj_value of the function double obj_value = arma::as_scalar(master(10)); // Calculate the values of the Scales arma::vec scales = scales_cpp(floor(log2(N))); // ------------------------------------ // Here we set up specifics that are used not in a specific mode. // Asymptotic ---- // Get bootstrapped V arma::mat V; // Bootstrap ---- // Hold optimism result arma::mat cov_nu_nu_theta; // Hold the bootstrapped obj values arma::vec bs_obj_values; if(bs_optimism){ results.row(full_model_index) = bs_optim_calc(theta, desc, objdesc, model_type, scales, omega, N, obj_value, alpha, compute_v, K, H, G, robust, eff); }else{ std::cout << "Bootstrapping the covariance matrix... Please stand by." << std::endl; V = cov_bootstrapper(theta, desc, objdesc, N, robust, eff, H, false); // Bootstrapped V (largest model) // Calculate the model score according to model selection criteria paper results.row(full_model_index) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value); } // Initialize counter to keep track of values unsigned int count = 0; unsigned int countModels = 1; while(iter != models.end()){ if(full_model_index != count){ countModels++; std::cout << "Processing model " << countModels << " out of " << num_models << std::endl; // Get the first model desc = *iter; // Build the fields off of the first model's description theta = model_theta(desc); objdesc = model_objdesc(desc); // Run the update version of the GMWM arma::field<arma::mat> update = gmwm_update_cpp(theta, desc, objdesc, model_type, N, expect_diff, orgV, scales, wv_empir, true, //starting "fast", K,H,G, robust,eff); // Theta update theta = update(0); // Update theo theo = update(3); // Update objective function obj_value = arma::as_scalar(update(5)); if(bs_optimism){ results.row(count) = bs_optim_calc(theta, desc, objdesc, model_type, scales, omega, N, obj_value, alpha, compute_v, K, H, G, robust, eff); }else{ // Calculate the model score according to model selection criteria paper results.row(count) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value); } } // end if // Increment iterator iter++; // Increase count count++; } std::set<std::vector<std::string > > ::const_iterator iter2; iter = models.begin(); /* * Iterate through all models * If i != j, then * IF (Complex_i > Complex_j && Obj_i > Obj_j){ * IF(Crit_i < Crit_J) * } */ while(iter != models.end()){ iter2 = models.begin(); while(iter2 != models.end()){ if(iter != iter2){ double m1_index = std::distance(models.begin(),iter); double m2_index = std::distance(models.begin(),iter2); if(count_params(*iter) > count_params(*iter2) && results(m1_index,0) > results(m2_index,0)){ if(results(m1_index,2) < results(m2_index,2)){ results(m1_index,1) = results(m2_index,1) + fabs(R::rnorm(0, sqrt(results(m2_index,0)/10) )); //results(m1_index,2) = results(m1_index,0)+ results(m1_index,1); } } } iter2++; } iter++; } results.col(2) = results.col(0) + results.col(1); arma::field< arma::field<arma::mat> > out(1); arma::field<arma::mat> ms(1); ms(0) = results; out(0) = ms; return out; } // [[Rcpp::export]] arma::field< arma::field<arma::field<arma::mat> > > rank_models(const arma::vec& data, const std::vector<std::vector < std::string > >& model_str, const std::vector< std::string >& full_model, double alpha, std::string compute_v, std::string model_type, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff, bool bs_optimism){ std::set<std::vector < std::string > > models = vector_to_set(model_str); arma::field< arma::field<arma::field<arma::mat> > > h(1); h(0) = model_select(data, models, full_model, model_type, bs_optimism, alpha, compute_v, K, H, G, robust, eff); return h; } // [[Rcpp::export]] arma::field< arma::field<arma::field<arma::mat> > > auto_imu(const arma::mat& data, const arma::mat& combs, const std::vector< std::string >& full_model, double alpha, std::string compute_v, std::string model_type, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff, bool bs_optimism){ // Number of columns to process unsigned int V = data.n_cols; // Create a set of unique models. std::set<std::vector<std::string > > models = build_model_set(combs, full_model); arma::field< arma::field<arma::field<arma::mat> > > h(V); for(unsigned int i = 0; i < V; i++){ h(i) = model_select(data.col(i), models, full_model, model_type, bs_optimism, alpha, compute_v, K, H, G, robust, eff); } return h; } <|endoftext|>
<commit_before> #include <opencv\cv.h> #include <opencv\highgui.h> #include <opencv2\flann\lsh_table.h> #include <limits> using namespace std; using namespace cv; //our sensitivity value to be used in the threshold() function const static int SENSITIVITY_VALUE = 20; //size of blur used to smooth the image to remove possible noise and //increase the size of the object we are trying to track. (Much like dilate and erode) const static int BLUR_SIZE = 10; //we'll have just one object to search for //and keep track of its position. int theObject[2] = { 0, 0 }; //bounding rectangle of the object, we will use the center of this as its position. Rect objectBoundingRectangle = Rect(0, 0, 0, 0); //int to string helper function string intToString(int number){ //this function has a number input and string outpu std::stringstream ss; ss << number; return ss.str(); } void searchForMovement(Mat thresholdImage, Mat &cameraFeed){ //notice how we use the '&' operator for the cameraFeed. This is because we wish //to take the values passed into the function and manipulate them, rather than just working with a copy. //eg. we draw to the cameraFeed in this function which is then displayed in the main() function. bool objectDetected = false; Mat temp; thresholdImage.copyTo(temp); //these two vectors needed for output of findContours vector< vector<Point> > contours; vector<Vec4i> hierarchy; //find contours of filtered image using openCV findContours function //findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE );// retrieves all contours findContours(temp, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);// retrieves external contours //if contours vector is not empty, we have found some objects if (contours.size()>0)objectDetected = true; else objectDetected = false; if (objectDetected){ //the largest contour is found at the end of the contours vector //we will simply assume that the biggest contour is the object we are looking for. vector< vector<Point> > largestContourVec; largestContourVec.push_back(contours.at(contours.size() - 1)); //make a bounding rectangle around the largest contour then find its centroid //this will be the object's final estimated position. objectBoundingRectangle = boundingRect(largestContourVec.at(0)); int xpos = objectBoundingRectangle.x + objectBoundingRectangle.width / 2; int ypos = objectBoundingRectangle.y + objectBoundingRectangle.height / 2; //update the objects positions by changing the 'theObject' array values theObject[0] = xpos, theObject[1] = ypos; } //make some temp x and y variables so we dont have to type out so much int x = theObject[0]; int y = theObject[1]; //draw some crosshairs on the object circle(cameraFeed, Point(x, y), 20, Scalar(0, 255, 0), 2); line(cameraFeed, Point(x, y), Point(x, y - 25), Scalar(0, 255, 0), 2); line(cameraFeed, Point(x, y), Point(x, y + 25), Scalar(0, 255, 0), 2); line(cameraFeed, Point(x, y), Point(x - 25, y), Scalar(0, 255, 0), 2); line(cameraFeed, Point(x, y), Point(x + 25, y), Scalar(0, 255, 0), 2); putText(cameraFeed, "Tracking object at (" + intToString(x) + "," + intToString(y) + ")", Point(x, y), 1, 1, Scalar(255, 0, 0), 2); } int startMotionTracking(){ //some boolean variables for added functionality bool objectDetected = false; //these two can be toggled by pressing 'd' or 't' bool debugMode = false; bool trackingEnabled = false; //pause and resume code bool pause = false; //set up the matrices that we will need //the two frames we will be comparing Mat frame1, frame2; //their grayscale images (needed for absdiff() function) Mat grayImage1, grayImage2; //resulting difference image Mat differenceImage; //thresholded difference image (for use in findContours() function) Mat thresholdImage; //video capture object. VideoCapture capture; while (1){ //we can loop the video by re-opening the capture every time the video reaches its last frame capture.open(0); if (!capture.isOpened()){ cout << "ERROR ACQUIRING VIDEO FEED\n"; getchar(); return -1; } //check if the video has reach its last frame. //we add '-1' because we are reading two frames from the video at a time. //if this is not included, we get a memory error! while (capture.get(CV_CAP_PROP_POS_FRAMES)<capture.get(CV_CAP_PROP_FRAME_COUNT) - 1){ //read first frame capture.read(frame1); //convert frame1 to gray scale for frame differencing //copy second frame //convert frame2 to gray scale for frame differencing //perform frame differencing with the sequential images. This will output an "intensity image" //do not confuse this with a threshold image, we will need to perform thresholding afterwards. //threshold intensity image at a given sensitivity value if (debugMode == true){ //show the difference image and threshold image } else{ //if not in debug mode, destroy the windows so we don't see them anymore } //use blur() to smooth the image, remove possible noise and //increase the size of the object we are trying to track. (Much like dilate and erode) //threshold again to obtain binary image from blur output if (debugMode == true){ //show the threshold image after it's been "blurred" } else { //if not in debug mode, destroy the windows so we don't see them anymore } //if tracking enabled, search for contours in our thresholded image //show our captured frame imshow("Frame1", frame1); //check to see if a button has been pressed. //this 10ms delay is necessary for proper operation of this program //if removed, frames will not have enough time to referesh and a blank //image will appear. switch (waitKey(10)){ case 27: //'esc' key has been pressed, exit program. return 0; case 116: //'t' has been pressed. this will toggle tracking trackingEnabled = !trackingEnabled; if (trackingEnabled == false) cout << "Tracking disabled." << endl; else cout << "Tracking enabled." << endl; break; case 100: //'d' has been pressed. this will debug mode debugMode = !debugMode; if (debugMode == false) cout << "Debug mode disabled." << endl; else cout << "Debug mode enabled." << endl; break; case 112: //'p' has been pressed. this will pause/resume the code. pause = !pause; if (pause == true){ cout << "Code paused, press 'p' again to resume" << endl; while (pause == true){ //stay in this loop until switch (waitKey()){ //a switch statement inside a switch statement? Mind blown. case 112: //change pause back to false pause = false; cout << "Code resumed." << endl; break; } } } } } //release the capture before re-opening and looping again. capture.release(); } return 0; }<commit_msg>Motion detection<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_cxa_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_cxa_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0x801B1F98D8717000 = 0x801B1F98D8717000; constexpr uint64_t literal_0x0000000000000 = 0x0000000000000; constexpr uint64_t literal_0x2080000020080 = 0x2080000020080; constexpr uint64_t literal_0b0000 = 0b0000; constexpr uint64_t literal_0b111 = 0b111; constexpr uint64_t literal_0b0010 = 0b0010; constexpr uint64_t literal_0b0001 = 0b0001; fapi2::ReturnCode p9_cxa_scom(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x2010803ull, l_scom_buffer )); l_scom_buffer.insert<0, 52, 0, uint64_t>(literal_0x801B1F98D8717000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010806ull, l_scom_buffer )); l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x0000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010807ull, l_scom_buffer )); l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x2080000020080 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010807ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010818ull, l_scom_buffer )); constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF = 0x0; l_scom_buffer.insert<1, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF ); if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON = 0x1; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF = 0x0; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010818ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010819ull, l_scom_buffer )); l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0b0000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010819ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x201081bull, l_scom_buffer )); l_scom_buffer.insert<45, 3, 61, uint64_t>(literal_0b111 ); l_scom_buffer.insert<48, 4, 60, uint64_t>(literal_0b0010 ); FAPI_TRY(fapi2::putScom(TGT0, 0x201081bull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x201081cull, l_scom_buffer )); l_scom_buffer.insert<18, 4, 60, uint64_t>(literal_0b0001 ); FAPI_TRY(fapi2::putScom(TGT0, 0x201081cull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <commit_msg>Build p9n 10 and 20 by default.<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_cxa_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_cxa_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0x801B1F98D8717000 = 0x801B1F98D8717000; constexpr uint64_t literal_0x0000000000000 = 0x0000000000000; constexpr uint64_t literal_0x2080000020080 = 0x2080000020080; constexpr uint64_t literal_0b0000 = 0b0000; constexpr uint64_t literal_0b111 = 0b111; constexpr uint64_t literal_0b0010 = 0b0010; constexpr uint64_t literal_0b0001 = 0b0001; fapi2::ReturnCode p9_cxa_scom(const fapi2::Target<fapi2::TARGET_TYPE_CAPP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x2010803ull, l_scom_buffer )); l_scom_buffer.insert<0, 52, 0, uint64_t>(literal_0x801B1F98D8717000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010806ull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x0000000000000 ); } else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) ) { l_scom_buffer.insert<0, 53, 11, uint64_t>(literal_0x0000000000000 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010807ull, l_scom_buffer )); if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { l_scom_buffer.insert<0, 52, 12, uint64_t>(literal_0x2080000020080 ); } else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) ) { l_scom_buffer.insert<0, 53, 11, uint64_t>(literal_0x2080000020080 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010807ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010818ull, l_scom_buffer )); constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF = 0x0; l_scom_buffer.insert<1, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_ADR_BAR_MODE_OFF ); if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON = 0x1; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_ON ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { constexpr auto l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF = 0x0; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_CAPP0_CXA_TOP_CXA_APC0_APCCTL_SKIP_G_OFF ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010818ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010819ull, l_scom_buffer )); l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0b0000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x2010819ull, l_scom_buffer)); } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x201081bull, l_scom_buffer )); l_scom_buffer.insert<45, 3, 61, uint64_t>(literal_0b111 ); l_scom_buffer.insert<48, 4, 60, uint64_t>(literal_0b0010 ); FAPI_TRY(fapi2::putScom(TGT0, 0x201081bull, l_scom_buffer)); } } { FAPI_TRY(fapi2::getScom( TGT0, 0x201081cull, l_scom_buffer )); l_scom_buffer.insert<18, 4, 60, uint64_t>(literal_0b0001 ); FAPI_TRY(fapi2::putScom(TGT0, 0x201081cull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9c_mi_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9c_mi_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_7 = 7; constexpr uint64_t literal_16 = 16; constexpr uint64_t literal_8 = 8; constexpr uint64_t literal_1 = 1; constexpr uint64_t literal_0x19 = 0x19; constexpr uint64_t literal_0 = 0; constexpr uint64_t literal_0b0000000000001000000 = 0b0000000000001000000; constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000; constexpr uint64_t literal_0b01 = 0b01; constexpr uint64_t literal_5 = 5; fapi2::ReturnCode p9c_mi_scom(const fapi2::Target<fapi2::TARGET_TYPE_MI>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { { uint64_t l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC = literal_1; uint64_t l_def_ENABLE_DYNAMIC_64_128B_READS = literal_0; uint64_t l_def_ENABLE_ECRESP = literal_1; uint64_t l_def_ENABLE_AMO_CACHING = literal_1; uint64_t l_def_ENABLE_MCU_TIMEOUTS = literal_1; fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer )); l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_7 ); l_scom_buffer.insert<50, 5, 59, uint64_t>(literal_16 ); l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_8 ); if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1; l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON ); } if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1)) { l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_0x19 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer )); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF = 0x0; l_scom_buffer.insert<48, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON = 0x1; l_scom_buffer.insert<21, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON = 0x1; l_scom_buffer.insert<22, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON = 0x1; l_scom_buffer.insert<23, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON ); if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1; l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON ); } else if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_0)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF = 0x0; l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF ); } if ((l_def_ENABLE_ECRESP == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON = 0x1; l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON ); } constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON = 0x1; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON ); FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer )); l_scom_buffer.insert<33, 19, 45, uint64_t>(literal_0b0000000000001000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer )); if ((l_def_ENABLE_AMO_CACHING == literal_1)) { l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x501081bull, l_scom_buffer )); if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON = 0x1; l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON ); } constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF = 0x0; l_scom_buffer.insert<1, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF ); if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON = 0x1; l_scom_buffer.insert<32, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON = 0x1; l_scom_buffer.insert<33, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON = 0x1; l_scom_buffer.insert<34, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON = 0x1; l_scom_buffer.insert<35, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON ); } l_scom_buffer.insert<2, 2, 62, uint64_t>(literal_0b01 ); if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { l_scom_buffer.insert<24, 8, 56, uint64_t>(literal_1 ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { l_scom_buffer.insert<5, 3, 61, uint64_t>(literal_7 ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { l_scom_buffer.insert<37, 3, 61, uint64_t>(literal_5 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x501081bull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <commit_msg>p9c.mi.scom.initfile -- default to block all sync pipelines<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9c_mi_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9c_mi_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_7 = 7; constexpr uint64_t literal_16 = 16; constexpr uint64_t literal_8 = 8; constexpr uint64_t literal_1 = 1; constexpr uint64_t literal_0x19 = 0x19; constexpr uint64_t literal_0 = 0; constexpr uint64_t literal_0b0000000000001000000 = 0b0000000000001000000; constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000; constexpr uint64_t literal_0b01 = 0b01; constexpr uint64_t literal_5 = 5; fapi2::ReturnCode p9c_mi_scom(const fapi2::Target<fapi2::TARGET_TYPE_MI>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { { uint64_t l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC = literal_1; uint64_t l_def_ENABLE_DYNAMIC_64_128B_READS = literal_0; uint64_t l_def_ENABLE_ECRESP = literal_1; uint64_t l_def_ENABLE_AMO_CACHING = literal_1; uint64_t l_def_ENABLE_MCU_TIMEOUTS = literal_1; fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer )); l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_7 ); l_scom_buffer.insert<50, 5, 59, uint64_t>(literal_16 ); l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_8 ); if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1; l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON ); } if ((l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC == literal_1)) { l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_0x19 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer )); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_SYNC_ON = 0x1; l_scom_buffer.insert<27, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_SYNC_ON ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_PAIR_SYNC_ON = 0x1; l_scom_buffer.insert<28, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_DISABLE_MC_PAIR_SYNC_ON ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF = 0x0; l_scom_buffer.insert<48, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_OFF ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON = 0x1; l_scom_buffer.insert<21, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON = 0x1; l_scom_buffer.insert<22, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON ); constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON = 0x1; l_scom_buffer.insert<23, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON ); if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1; l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON ); } else if ((l_def_ENABLE_DYNAMIC_64_128B_READS == literal_0)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF = 0x0; l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_OFF ); } if ((l_def_ENABLE_ECRESP == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON = 0x1; l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON ); } constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON = 0x1; l_scom_buffer.insert<6, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ASYNC_MODE_ON ); FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer )); l_scom_buffer.insert<33, 19, 45, uint64_t>(literal_0b0000000000001000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer )); if ((l_def_ENABLE_AMO_CACHING == literal_1)) { l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x501081bull, l_scom_buffer )); if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON = 0x1; l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_PB_HANG_PULSE_ON ); } constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF = 0x0; l_scom_buffer.insert<1, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_SELECT_LOCAL_HANG_PULSE_OFF ); if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON = 0x1; l_scom_buffer.insert<32, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_NONMIRROR_HANG_ON ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON = 0x1; l_scom_buffer.insert<33, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_MIRROR_HANG_ON ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON = 0x1; l_scom_buffer.insert<34, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_APO_HANG_ON ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { constexpr auto l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON = 0x1; l_scom_buffer.insert<35, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCTO_ENABLE_CLIB_HANG_ON ); } l_scom_buffer.insert<2, 2, 62, uint64_t>(literal_0b01 ); if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { l_scom_buffer.insert<24, 8, 56, uint64_t>(literal_1 ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { l_scom_buffer.insert<5, 3, 61, uint64_t>(literal_7 ); } if ((l_def_ENABLE_MCU_TIMEOUTS == literal_1)) { l_scom_buffer.insert<37, 3, 61, uint64_t>(literal_5 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x501081bull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/unmask.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file unmask.C /// @brief Subroutines for unmasking and setting up MSS FIR /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <generic/memory/lib/utils/scom.H> #include <lib/fir/fir.H> #include <lib/fir/unmask.H> #include <lib/workarounds/mcbist_workarounds.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; namespace mss { namespace unmask { /// /// @brief Unmask and setup actions performed after draminit_mc /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask mss fir after draminit_mc"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. fir::reg<MCBIST_MCBISTFIRQ> l_mcbist_fir_reg(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); // Setup mcbist fir. All mcbist attentions are already special attentions // Write this out before the work-around as it will read and write. l_mcbist_fir_reg.attention<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() .checkstop<MCBIST_MCBISTFIRQ_MCBIST_BRODCAST_OUT_OF_SYNC>(); FAPI_TRY(l_mcbist_fir_reg.write(), "unable to write fir::reg %d", MCBIST_MCBISTFIRQ); FAPI_TRY(mss::workarounds::mcbist::wat_debug_attention(i_target)); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_FIR> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR); l_mca_fir_reg.checkstop<MCA_FIR_MAINTENANCE_AUE>() .checkstop<MCA_FIR_MAINTENANCE_IAUE>() .recoverable_error<MCA_FIR_SCOM_PARITY_CLASS_STATUS>() .recoverable_error<MCA_FIR_SCOM_PARITY_CLASS_RECOVERABLE>() .checkstop<MCA_FIR_SCOM_PARITY_CLASS_UNRECOVERABLE>() .checkstop<MCA_FIR_ECC_CORRECTOR_INTERNAL_PARITY_ERROR>() .recoverable_error<MCA_FIR_WRITE_RMW_CE>() .checkstop<MCA_FIR_WRITE_RMW_UE>() .checkstop<MCA_FIR_WDF_OVERRUN_ERROR_0>() .checkstop<MCA_FIR_WDF_OVERRUN_ERROR_1>() .checkstop<MCA_FIR_WDF_SCOM_SEQUENCE_ERROR>() .checkstop<MCA_FIR_WDF_STATE_MACHINE_ERROR>() .checkstop<MCA_FIR_WDF_MISC_REGISTER_PARITY_ERROR>() .checkstop<MCA_FIR_WRT_SCOM_SEQUENCE_ERROR>() .checkstop<MCA_FIR_WRT_MISC_REGISTER_PARITY_ERROR>() .checkstop<MCA_FIR_ECC_GENERATOR_INTERNAL_PARITY_ERROR>() .checkstop<MCA_FIR_READ_BUFFER_OVERFLOW_ERROR>() .checkstop<MCA_FIR_WDF_ASYNC_INTERFACE_ERROR>() .checkstop<MCA_FIR_READ_ASYNC_INTERFACE_PARITY_ERROR>() .checkstop<MCA_FIR_READ_ASYNC_INTERFACE_SEQUENCE_ERROR>(); FAPI_TRY(l_mca_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR); } fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions performed after draminit_training /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask mss fir after draminit_training"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. fir::reg<MCBIST_MCBISTFIRQ> l_mcbist_fir_reg(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); // Setup mcbist fir. All mcbist attentions are already special attentions FAPI_TRY(l_mcbist_fir_reg.recoverable_error<MCBIST_MCBISTFIRQ_COMMAND_ADDRESS_TIMEOUT>().write(), "unable to write fir::reg %d", MCBIST_MCBISTFIRQ); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_MBACALFIRQ> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); l_mca_fir_reg.recoverable_error<MCA_MBACALFIRQ_REFRESH_OVERRUN>() .recoverable_error<MCA_MBACALFIRQ_DDR_CAL_TIMEOUT_ERR>() .recoverable_error<MCA_MBACALFIRQ_DDR_CAL_RESET_TIMEOUT>() .recoverable_error<MCA_MBACALFIRQ_WRQ_RRQ_HANG_ERR>() .checkstop<MCA_MBACALFIRQ_ASYNC_IF_ERROR>() .checkstop<MCA_MBACALFIRQ_CMD_PARITY_ERROR>() .recoverable_error<MCA_MBACALFIRQ_RCD_CAL_PARITY_ERROR>(); FAPI_TRY(l_mca_fir_reg.write(), "unable to write fir::reg %d", MCA_MBACALFIRQ); } fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions performed after mss_scominit /// (yeah, it's clearing bits - it's ok) /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_scominit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask (and clear) mss fir after scominit"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. for (const auto& p : mss::find_targets_with_magic<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_IOM_PHY0_DDRPHY_FIR_REG> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_IOM_PHY0_DDRPHY_FIR_REG); fir::reg<MCA_MBACALFIRQ> l_cal_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); FAPI_TRY(l_mca_fir_reg.clear<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_2>()); FAPI_TRY(l_mca_fir_reg.clear<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_4>()); FAPI_TRY(l_cal_fir_reg.clear<MCA_MBACALFIRQ_RCD_PARITY_ERROR>()); // No need to write after clearing - the clear does the read/modify/write. } fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions performed after mss_ddr_phy_reset /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_phy_reset( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask mss fir after phy reset"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. fir::reg<MCBIST_MCBISTFIRQ> l_mcbist_fir_reg(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); l_mcbist_fir_reg.checkstop<MCBIST_MCBISTFIRQ_INTERNAL_FSM_ERROR>() .recoverable_error<MCBIST_MCBISTFIRQ_SCOM_RECOVERABLE_REG_PE>() .checkstop<MCBIST_MCBISTFIRQ_SCOM_FATAL_REG_PE>(); FAPI_TRY(l_mcbist_fir_reg.write(), "unable to write fir::reg %d", MCBIST_MCBISTFIRQ); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_IOM_PHY0_DDRPHY_FIR_REG> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_IOM_PHY0_DDRPHY_FIR_REG); fir::reg<MCA_MBACALFIRQ> l_cal_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); l_cal_fir_reg.recoverable_error<MCA_MBACALFIRQ_MBA_RECOVERABLE_ERROR>() .checkstop<MCA_MBACALFIRQ_MBA_NONRECOVERABLE_ERROR>() .recoverable_error<MCA_MBACALFIRQ_RCD_PARITY_ERROR>() .checkstop<MCA_MBACALFIRQ_SM_1HOT_ERR>(); l_mca_fir_reg.recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_0>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_1>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_3>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_4>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_5>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_6>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_7>(); FAPI_TRY(l_mca_fir_reg.write(), "unable to write fir::reg %d", MCA_IOM_PHY0_DDRPHY_FIR_REG); FAPI_TRY(l_cal_fir_reg.write(), "unable to write fir::reg %d", MCA_MBACALFIRQ); } fapi_try_exit: return fapi2::current_err; } } } <commit_msg>Clear out bogus EVENT_N in scominit<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/fir/unmask.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file unmask.C /// @brief Subroutines for unmasking and setting up MSS FIR /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Marc Gollub <gollub@us.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <generic/memory/lib/utils/scom.H> #include <lib/fir/fir.H> #include <lib/fir/unmask.H> #include <lib/workarounds/mcbist_workarounds.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; namespace mss { namespace unmask { /// /// @brief Unmask and setup actions performed after draminit_mc /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask mss fir after draminit_mc"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. fir::reg<MCBIST_MCBISTFIRQ> l_mcbist_fir_reg(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); // Setup mcbist fir. All mcbist attentions are already special attentions // Write this out before the work-around as it will read and write. l_mcbist_fir_reg.attention<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() .checkstop<MCBIST_MCBISTFIRQ_MCBIST_BRODCAST_OUT_OF_SYNC>(); FAPI_TRY(l_mcbist_fir_reg.write(), "unable to write fir::reg %d", MCBIST_MCBISTFIRQ); FAPI_TRY(mss::workarounds::mcbist::wat_debug_attention(i_target)); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_FIR> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_FIR); l_mca_fir_reg.checkstop<MCA_FIR_MAINTENANCE_AUE>() .checkstop<MCA_FIR_MAINTENANCE_IAUE>() .recoverable_error<MCA_FIR_SCOM_PARITY_CLASS_STATUS>() .recoverable_error<MCA_FIR_SCOM_PARITY_CLASS_RECOVERABLE>() .checkstop<MCA_FIR_SCOM_PARITY_CLASS_UNRECOVERABLE>() .checkstop<MCA_FIR_ECC_CORRECTOR_INTERNAL_PARITY_ERROR>() .recoverable_error<MCA_FIR_WRITE_RMW_CE>() .checkstop<MCA_FIR_WRITE_RMW_UE>() .checkstop<MCA_FIR_WDF_OVERRUN_ERROR_0>() .checkstop<MCA_FIR_WDF_OVERRUN_ERROR_1>() .checkstop<MCA_FIR_WDF_SCOM_SEQUENCE_ERROR>() .checkstop<MCA_FIR_WDF_STATE_MACHINE_ERROR>() .checkstop<MCA_FIR_WDF_MISC_REGISTER_PARITY_ERROR>() .checkstop<MCA_FIR_WRT_SCOM_SEQUENCE_ERROR>() .checkstop<MCA_FIR_WRT_MISC_REGISTER_PARITY_ERROR>() .checkstop<MCA_FIR_ECC_GENERATOR_INTERNAL_PARITY_ERROR>() .checkstop<MCA_FIR_READ_BUFFER_OVERFLOW_ERROR>() .checkstop<MCA_FIR_WDF_ASYNC_INTERFACE_ERROR>() .checkstop<MCA_FIR_READ_ASYNC_INTERFACE_PARITY_ERROR>() .checkstop<MCA_FIR_READ_ASYNC_INTERFACE_SEQUENCE_ERROR>(); FAPI_TRY(l_mca_fir_reg.write(), "unable to write fir::reg %d", MCA_FIR); } fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions performed after draminit_training /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask mss fir after draminit_training"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. fir::reg<MCBIST_MCBISTFIRQ> l_mcbist_fir_reg(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); // Setup mcbist fir. All mcbist attentions are already special attentions FAPI_TRY(l_mcbist_fir_reg.recoverable_error<MCBIST_MCBISTFIRQ_COMMAND_ADDRESS_TIMEOUT>().write(), "unable to write fir::reg %d", MCBIST_MCBISTFIRQ); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_MBACALFIRQ> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); l_mca_fir_reg.recoverable_error<MCA_MBACALFIRQ_REFRESH_OVERRUN>() .recoverable_error<MCA_MBACALFIRQ_DDR_CAL_TIMEOUT_ERR>() .recoverable_error<MCA_MBACALFIRQ_DDR_CAL_RESET_TIMEOUT>() .recoverable_error<MCA_MBACALFIRQ_WRQ_RRQ_HANG_ERR>() .checkstop<MCA_MBACALFIRQ_ASYNC_IF_ERROR>() .checkstop<MCA_MBACALFIRQ_CMD_PARITY_ERROR>() .recoverable_error<MCA_MBACALFIRQ_RCD_CAL_PARITY_ERROR>(); FAPI_TRY(l_mca_fir_reg.write(), "unable to write fir::reg %d", MCA_MBACALFIRQ); } fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions performed after mss_scominit /// (yeah, it's clearing bits - it's ok) /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_scominit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask (and clear) mss fir after scominit"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. for (const auto& p : mss::find_targets_with_magic<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_IOM_PHY0_DDRPHY_FIR_REG> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_IOM_PHY0_DDRPHY_FIR_REG); fir::reg<MCA_MBACALFIRQ> l_cal_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); FAPI_TRY(l_mca_fir_reg.clear<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_2>()); FAPI_TRY(l_mca_fir_reg.clear<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_4>()); FAPI_TRY(l_cal_fir_reg.clear<MCA_MBACALFIRQ_RCD_PARITY_ERROR>()); FAPI_TRY(l_cal_fir_reg.clear<MCA_MBACALFIRQ_DDR_MBA_EVENT_N>()); // No need to write after clearing - the clear does the read/modify/write. } fapi_try_exit: return fapi2::current_err; } /// /// @brief Unmask and setup actions performed after mss_ddr_phy_reset /// @param[in] i_target the fapi2::Target of the MCBIST /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok /// template<> fapi2::ReturnCode after_phy_reset( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("unmask mss fir after phy reset"); fapi2::ReturnCode l_rc; // TK - unclear right now if these can become generic per MCBIST or whether these are specific // to Nimbus. If they can be generic,this whole thing can go back in the H file and the specifics // of the registers and bits can be handled generically. fir::reg<MCBIST_MCBISTFIRQ> l_mcbist_fir_reg(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); l_mcbist_fir_reg.checkstop<MCBIST_MCBISTFIRQ_INTERNAL_FSM_ERROR>() .recoverable_error<MCBIST_MCBISTFIRQ_SCOM_RECOVERABLE_REG_PE>() .checkstop<MCBIST_MCBISTFIRQ_SCOM_FATAL_REG_PE>(); FAPI_TRY(l_mcbist_fir_reg.write(), "unable to write fir::reg %d", MCBIST_MCBISTFIRQ); for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target)) { fir::reg<MCA_IOM_PHY0_DDRPHY_FIR_REG> l_mca_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_IOM_PHY0_DDRPHY_FIR_REG); fir::reg<MCA_MBACALFIRQ> l_cal_fir_reg(p, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCA_MBACALFIRQ); l_cal_fir_reg.recoverable_error<MCA_MBACALFIRQ_MBA_RECOVERABLE_ERROR>() .checkstop<MCA_MBACALFIRQ_MBA_NONRECOVERABLE_ERROR>() .recoverable_error<MCA_MBACALFIRQ_RCD_PARITY_ERROR>() .checkstop<MCA_MBACALFIRQ_SM_1HOT_ERR>(); l_mca_fir_reg.recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_0>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_1>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_3>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_4>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_5>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_6>() .recoverable_error<MCA_IOM_PHY0_DDRPHY_FIR_REG_ERROR_7>(); FAPI_TRY(l_mca_fir_reg.write(), "unable to write fir::reg %d", MCA_IOM_PHY0_DDRPHY_FIR_REG); FAPI_TRY(l_cal_fir_reg.write(), "unable to write fir::reg %d", MCA_MBACALFIRQ); } fapi_try_exit: return fapi2::current_err; } } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qtwizard.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include "qt4target.h" #include "modulespage.h" #include "targetspage.h" #include <coreplugin/icore.h> #include <cpptools/cpptoolsconstants.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QCoreApplication> #include <QtCore/QVariant> using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; static inline Core::BaseFileWizardParameters wizardParameters(const QString &id, const QString &category, const QString &categoryTranslationScope, const QString &displayCategory, const QString &name, const QString &description, const QIcon &icon) { Core::BaseFileWizardParameters rc(Core::IWizard::ProjectWizard); rc.setCategory(category); rc.setDisplayCategory(QCoreApplication::translate(categoryTranslationScope.toLatin1(), displayCategory.toLatin1())); rc.setIcon(icon); rc.setDisplayName(name); rc.setId(id); rc.setDescription(description); return rc; } // -------------------- QtWizard QtWizard::QtWizard(const QString &id, const QString &category, const QString &categoryTranslationScope, const QString &displayCategory, const QString &name, const QString &description, const QIcon &icon) : Core::BaseFileWizard(wizardParameters(id, category, categoryTranslationScope, displayCategory, name, description, icon)) { } QString QtWizard::sourceSuffix() { return preferredSuffix(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)); } QString QtWizard::headerSuffix() { return preferredSuffix(QLatin1String(Constants::CPP_HEADER_MIMETYPE)); } QString QtWizard::formSuffix() { return preferredSuffix(QLatin1String(Constants::FORM_MIMETYPE)); } QString QtWizard::profileSuffix() { return preferredSuffix(QLatin1String(Constants::PROFILE_MIMETYPE)); } bool QtWizard::postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &l, QString *errorMessage) { const QString proFileName = l.back().path(); const BaseQt4ProjectWizardDialog *dialog = qobject_cast<const BaseQt4ProjectWizardDialog *>(w); // Generate user settings: dialog->writeUserFile(proFileName); // Post-Generate: Open the project if (!ProjectExplorer::ProjectExplorerPlugin::instance()->openProject(proFileName)) { *errorMessage = tr("The project %1 could not be opened.").arg(proFileName); return false; } return true; } QString QtWizard::templateDir() { QString rc = Core::ICore::instance()->resourcePath(); rc += QLatin1String("/templates/qt4project"); return rc; } bool QtWizard::lowerCaseFiles() { QString lowerCaseSettingsKey = QLatin1String(CppTools::Constants::CPPTOOLS_SETTINGSGROUP); lowerCaseSettingsKey += QLatin1Char('/'); lowerCaseSettingsKey += QLatin1String(CppTools::Constants::LOWERCASE_CPPFILES_KEY); const bool lowerCaseDefault = CppTools::Constants::lowerCaseFilesDefault; return Core::ICore::instance()->settings()->value(lowerCaseSettingsKey, QVariant(lowerCaseDefault)).toBool(); } bool QtWizard::showModulesPageForApplications() { return false; } bool QtWizard::showModulesPageForLibraries() { return true; } // ----------------- BaseQt4ProjectWizardDialog BaseQt4ProjectWizardDialog::BaseQt4ProjectWizardDialog(bool showModulesPage, QWidget *parent) : ProjectExplorer::BaseProjectWizardDialog(parent), m_modulesPage(0), m_targetsPage(0) { init(showModulesPage); } BaseQt4ProjectWizardDialog::BaseQt4ProjectWizardDialog(bool showModulesPage, Utils::ProjectIntroPage *introPage, int introId, QWidget *parent) : ProjectExplorer::BaseProjectWizardDialog(introPage, introId, parent), m_modulesPage(0), m_targetsPage(0) { init(showModulesPage); } BaseQt4ProjectWizardDialog::~BaseQt4ProjectWizardDialog() { if (m_targetsPage && !m_targetsPage->parent()) delete m_targetsPage; if (m_modulesPage && !m_modulesPage->parent()) delete m_modulesPage; } void BaseQt4ProjectWizardDialog::init(bool showModulesPage) { QtVersionManager *vm = QtVersionManager::instance(); if (showModulesPage) m_modulesPage = new ModulesPage; m_targetsPage = new TargetsPage; } int BaseQt4ProjectWizardDialog::addModulesPage(int id) { if (!m_modulesPage) return -1; if (id >= 0) { setPage(id, m_modulesPage); return id; } return addPage(m_modulesPage); } int BaseQt4ProjectWizardDialog::addTargetsPage(QSet<QString> targets, int id) { m_targetsPage->setValidTargets(targets); if (!m_targetsPage->needToDisplayPage()) return -1; if (id >= 0) { setPage(id, m_targetsPage); return id; } return addPage(m_targetsPage); } QString BaseQt4ProjectWizardDialog::selectedModules() const { return m_modulesPage ? m_modulesPage->selectedModules() : m_selectedModules; } void BaseQt4ProjectWizardDialog::setSelectedModules(const QString &modules, bool lock) { if (m_modulesPage) { foreach(const QString &module, modules.split(QLatin1Char(' '))) { m_modulesPage->setModuleSelected(module, true); m_modulesPage->setModuleEnabled(module, !lock); } } else { m_selectedModules = modules; } } QString BaseQt4ProjectWizardDialog::deselectedModules() const { return m_modulesPage ? m_modulesPage->deselectedModules() : m_deselectedModules; } void BaseQt4ProjectWizardDialog::setDeselectedModules(const QString &modules) { if (m_modulesPage) { foreach(const QString &module, modules.split(QLatin1Char(' '))) m_modulesPage->setModuleSelected(module, false); } else { m_deselectedModules = modules; } } void BaseQt4ProjectWizardDialog::writeUserFile(const QString &proFileName) const { if (m_targetsPage) m_targetsPage->writeUserFile(proFileName); } QSet<QString> BaseQt4ProjectWizardDialog::selectedTargets() const { QSet<QString> targets; if (m_targetsPage) targets = m_targetsPage->selectedTargets(); return targets; } QSet<QString> BaseQt4ProjectWizardDialog::desktopTarget() { QSet<QString> rc; rc.insert(QLatin1String(DESKTOP_TARGET_ID)); return rc; } <commit_msg>Remove unused variable<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qtwizard.h" #include "qt4project.h" #include "qt4projectmanagerconstants.h" #include "qt4target.h" #include "modulespage.h" #include "targetspage.h" #include <coreplugin/icore.h> #include <cpptools/cpptoolsconstants.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QCoreApplication> #include <QtCore/QVariant> using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; static inline Core::BaseFileWizardParameters wizardParameters(const QString &id, const QString &category, const QString &categoryTranslationScope, const QString &displayCategory, const QString &name, const QString &description, const QIcon &icon) { Core::BaseFileWizardParameters rc(Core::IWizard::ProjectWizard); rc.setCategory(category); rc.setDisplayCategory(QCoreApplication::translate(categoryTranslationScope.toLatin1(), displayCategory.toLatin1())); rc.setIcon(icon); rc.setDisplayName(name); rc.setId(id); rc.setDescription(description); return rc; } // -------------------- QtWizard QtWizard::QtWizard(const QString &id, const QString &category, const QString &categoryTranslationScope, const QString &displayCategory, const QString &name, const QString &description, const QIcon &icon) : Core::BaseFileWizard(wizardParameters(id, category, categoryTranslationScope, displayCategory, name, description, icon)) { } QString QtWizard::sourceSuffix() { return preferredSuffix(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)); } QString QtWizard::headerSuffix() { return preferredSuffix(QLatin1String(Constants::CPP_HEADER_MIMETYPE)); } QString QtWizard::formSuffix() { return preferredSuffix(QLatin1String(Constants::FORM_MIMETYPE)); } QString QtWizard::profileSuffix() { return preferredSuffix(QLatin1String(Constants::PROFILE_MIMETYPE)); } bool QtWizard::postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &l, QString *errorMessage) { const QString proFileName = l.back().path(); const BaseQt4ProjectWizardDialog *dialog = qobject_cast<const BaseQt4ProjectWizardDialog *>(w); // Generate user settings: dialog->writeUserFile(proFileName); // Post-Generate: Open the project if (!ProjectExplorer::ProjectExplorerPlugin::instance()->openProject(proFileName)) { *errorMessage = tr("The project %1 could not be opened.").arg(proFileName); return false; } return true; } QString QtWizard::templateDir() { QString rc = Core::ICore::instance()->resourcePath(); rc += QLatin1String("/templates/qt4project"); return rc; } bool QtWizard::lowerCaseFiles() { QString lowerCaseSettingsKey = QLatin1String(CppTools::Constants::CPPTOOLS_SETTINGSGROUP); lowerCaseSettingsKey += QLatin1Char('/'); lowerCaseSettingsKey += QLatin1String(CppTools::Constants::LOWERCASE_CPPFILES_KEY); const bool lowerCaseDefault = CppTools::Constants::lowerCaseFilesDefault; return Core::ICore::instance()->settings()->value(lowerCaseSettingsKey, QVariant(lowerCaseDefault)).toBool(); } bool QtWizard::showModulesPageForApplications() { return false; } bool QtWizard::showModulesPageForLibraries() { return true; } // ----------------- BaseQt4ProjectWizardDialog BaseQt4ProjectWizardDialog::BaseQt4ProjectWizardDialog(bool showModulesPage, QWidget *parent) : ProjectExplorer::BaseProjectWizardDialog(parent), m_modulesPage(0), m_targetsPage(0) { init(showModulesPage); } BaseQt4ProjectWizardDialog::BaseQt4ProjectWizardDialog(bool showModulesPage, Utils::ProjectIntroPage *introPage, int introId, QWidget *parent) : ProjectExplorer::BaseProjectWizardDialog(introPage, introId, parent), m_modulesPage(0), m_targetsPage(0) { init(showModulesPage); } BaseQt4ProjectWizardDialog::~BaseQt4ProjectWizardDialog() { if (m_targetsPage && !m_targetsPage->parent()) delete m_targetsPage; if (m_modulesPage && !m_modulesPage->parent()) delete m_modulesPage; } void BaseQt4ProjectWizardDialog::init(bool showModulesPage) { if (showModulesPage) m_modulesPage = new ModulesPage; m_targetsPage = new TargetsPage; } int BaseQt4ProjectWizardDialog::addModulesPage(int id) { if (!m_modulesPage) return -1; if (id >= 0) { setPage(id, m_modulesPage); return id; } return addPage(m_modulesPage); } int BaseQt4ProjectWizardDialog::addTargetsPage(QSet<QString> targets, int id) { m_targetsPage->setValidTargets(targets); if (!m_targetsPage->needToDisplayPage()) return -1; if (id >= 0) { setPage(id, m_targetsPage); return id; } return addPage(m_targetsPage); } QString BaseQt4ProjectWizardDialog::selectedModules() const { return m_modulesPage ? m_modulesPage->selectedModules() : m_selectedModules; } void BaseQt4ProjectWizardDialog::setSelectedModules(const QString &modules, bool lock) { if (m_modulesPage) { foreach(const QString &module, modules.split(QLatin1Char(' '))) { m_modulesPage->setModuleSelected(module, true); m_modulesPage->setModuleEnabled(module, !lock); } } else { m_selectedModules = modules; } } QString BaseQt4ProjectWizardDialog::deselectedModules() const { return m_modulesPage ? m_modulesPage->deselectedModules() : m_deselectedModules; } void BaseQt4ProjectWizardDialog::setDeselectedModules(const QString &modules) { if (m_modulesPage) { foreach(const QString &module, modules.split(QLatin1Char(' '))) m_modulesPage->setModuleSelected(module, false); } else { m_deselectedModules = modules; } } void BaseQt4ProjectWizardDialog::writeUserFile(const QString &proFileName) const { if (m_targetsPage) m_targetsPage->writeUserFile(proFileName); } QSet<QString> BaseQt4ProjectWizardDialog::selectedTargets() const { QSet<QString> targets; if (m_targetsPage) targets = m_targetsPage->selectedTargets(); return targets; } QSet<QString> BaseQt4ProjectWizardDialog::desktopTarget() { QSet<QString> rc; rc.insert(QLatin1String(DESKTOP_TARGET_ID)); return rc; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_smp_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_fbc_smp_utils.H /// @brief Fabric SMP library functions/constants (FAPI2) /// /// @author Joe McGill <jmcgill@us.ibm.com> /// // // *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com> // *HWP FW Owner: Thi Tran <thi@us.ibm.com> // *HWP Team: Nest // *HWP Level: 2 // *HWP Consumed by: HB,FSP // #ifndef _P9_FBC_SMP_UTILS_H_ #define _P9_FBC_SMP_UTILS_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> #include <p9_perv_scom_addresses.H> #include <p9_perv_scom_addresses_fld.H> #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_xbus_scom_addresses.H> #include <p9_xbus_scom_addresses_fld.H> #include <p9_obus_scom_addresses.H> //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ // link types enum p9_fbc_link_t { ELECTRICAL = fapi2::TARGET_TYPE_XBUS, OPTICAL = fapi2::TARGET_TYPE_OBUS }; // XBUS/ABUS link control structure struct p9_fbc_link_ctl_t { // associated endpoint target type & unit target number p9_fbc_link_t endp_type; uint8_t endp_unit_id; // iovalid SCOM addresses/control field uint64_t iovalid_or_addr; uint64_t iovalid_clear_addr; uint8_t iovalid_field_start_bit; // EXTFIR/RAS control field uint8_t ras_fir_field_bit; // DL layer SCOM addresses uint64_t dl_fir_addr; uint64_t dl_control_addr; // TL layer SCOM addresses uint64_t tl_fir_addr; uint8_t tl_fir_trained_field_start_bit; uint64_t tl_link_delay_addr; uint32_t tl_link_delay_hi_start_bit; uint32_t tl_link_delay_lo_start_bit; }; // link constants const uint32_t P9_FBC_UTILS_MAX_X_LINKS = 7; const uint32_t P9_FBC_UTILS_MAX_A_LINKS = 4; const p9_fbc_link_ctl_t P9_FBC_XBUS_LINK_CTL_ARR[P9_FBC_UTILS_MAX_X_LINKS] = { { ELECTRICAL, 0, PERV_XB_CPLT_CONF1_OR, PERV_XB_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X0_FIR_ERR, XBUS_LL0_LL0_LL0_IOEL_FIR_REG, XBUS_0_LL0_IOEL_CONTROL, PU_PB_IOE_FIR_REG, PU_PB_IOE_FIR_REG_FMR00_TRAINED, PU_PB_ELINK_DLY_0123_REG, 4, 20 }, { ELECTRICAL, 1, PERV_XB_CPLT_CONF1_OR, PERV_XB_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_6D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X1_FIR_ERR, XBUS_1_LL1_LL1_LL1_IOEL_FIR_REG, XBUS_1_LL1_IOEL_CONTROL, PU_PB_IOE_FIR_REG, PU_PB_IOE_FIR_REG_FMR02_TRAINED, PU_PB_ELINK_DLY_0123_REG, 36, 52 }, { ELECTRICAL, 2, PERV_XB_CPLT_CONF1_OR, PERV_XB_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_8D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X2_FIR_ERR, XBUS_2_LL2_LL2_LL2_IOEL_FIR_REG, XBUS_2_LL2_IOEL_CONTROL, PU_PB_IOE_FIR_REG, PU_PB_IOE_FIR_REG_FMR04_TRAINED, PU_PB_ELINK_DLY_45_REG, 4, 20 }, { OPTICAL, 0, PERV_OB0_CPLT_CONF1_OR, PERV_OB0_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X3_FIR_ERR, OBUS_LL0_LL0_LL0_PB_IOOL_FIR_REG, OBUS_0_LL0_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR00_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 4, 20 }, { OPTICAL, 1, PERV_OB1_CPLT_CONF1_OR, PERV_OB1_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X4_FIR_ERR, OBUS_1_LL1_LL1_LL1_PB_IOOL_FIR_REG, OBUS_1_LL1_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR02_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 36, 52 }, { OPTICAL, 2, PERV_OB2_CPLT_CONF1_OR, PERV_OB2_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X5_FIR_ERR, OBUS_2_LL2_LL2_LL2_PB_IOOL_FIR_REG, OBUS_2_LL2_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR04_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 4, 20 }, { OPTICAL, 3, PERV_OB3_CPLT_CONF1_OR, PERV_OB3_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X6_FIR_ERR, OBUS_3_LL3_LL3_LL3_PB_IOOL_FIR_REG, OBUS_3_LL3_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR06_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 36, 52 } }; const p9_fbc_link_ctl_t P9_FBC_ABUS_LINK_CTL_ARR[P9_FBC_UTILS_MAX_A_LINKS] = { { OPTICAL, 0, PERV_OB0_CPLT_CONF1_OR, PERV_OB0_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X3_FIR_ERR, OBUS_LL0_LL0_LL0_PB_IOOL_FIR_REG, OBUS_0_LL0_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR00_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 4, 20 }, { OPTICAL, 1, PERV_OB1_CPLT_CONF1_OR, PERV_OB1_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X4_FIR_ERR, OBUS_1_LL1_LL1_LL1_PB_IOOL_FIR_REG, OBUS_1_LL1_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR02_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 36, 52 }, { OPTICAL, 2, PERV_OB2_CPLT_CONF1_OR, PERV_OB2_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X5_FIR_ERR, OBUS_2_LL2_LL2_LL2_PB_IOOL_FIR_REG, OBUS_2_LL2_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR04_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 4, 20 }, { OPTICAL, 3, PERV_OB3_CPLT_CONF1_OR, PERV_OB3_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X6_FIR_ERR, OBUS_3_LL3_LL3_LL3_PB_IOOL_FIR_REG, OBUS_3_LL3_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR06_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 36, 52 } }; // range of fabric node/chip ID fields const uint8_t P9_FBC_UTILS_NUM_CHIP_IDS = 8; const uint8_t P9_FBC_UTILS_NUM_GROUP_IDS = 8; //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ /// /// @brief Utility function to read & return fabric group ID attribute /// /// @tparam T template parameter, passed in target. /// @param[in] i_target Reference to chip/chiplet target /// @param[out] o_group_id Group ID value /// /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. /// template<fapi2::TargetType T> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<T>& i_target, uint8_t& o_group_id); // Specialization for proc chip target template<> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t& o_group_id); // Specialization for XBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target, uint8_t& o_group_id); // Specialization for OBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target, uint8_t& o_group_id); /// /// @brief Utility function to read & return fabric chip ID attribute /// /// @tparam T template parameter, passed in target. /// @param[in] i_target Reference to chip/chiplet target /// @param[out] o_chip_id chip ID value /// /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. /// template<fapi2::TargetType T> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<T>& i_target, uint8_t& o_chip_id); // Specialization for proc chip target template<> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t& o_chip_id); // Specialization for XBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target, uint8_t& o_chip_id); // Specialization for OBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target, uint8_t& o_chip_id); #endif // _P9_FBC_SMP_UTILS_H_ <commit_msg>L3 updates -- p9_setup_bars, p9_fbc_smp_utils<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_smp_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_fbc_smp_utils.H /// @brief Fabric SMP library functions/constants (FAPI2) /// /// @author Joe McGill <jmcgill@us.ibm.com> /// // // *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com> // *HWP FW Owner: Thi Tran <thi@us.ibm.com> // *HWP Team: Nest // *HWP Level: 3 // *HWP Consumed by: HB,FSP // #ifndef _P9_FBC_SMP_UTILS_H_ #define _P9_FBC_SMP_UTILS_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> #include <p9_perv_scom_addresses.H> #include <p9_perv_scom_addresses_fld.H> #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_xbus_scom_addresses.H> #include <p9_xbus_scom_addresses_fld.H> #include <p9_obus_scom_addresses.H> //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ // link types enum p9_fbc_link_t { ELECTRICAL = fapi2::TARGET_TYPE_XBUS, OPTICAL = fapi2::TARGET_TYPE_OBUS }; // XBUS/ABUS link control structure struct p9_fbc_link_ctl_t { // associated endpoint target type & unit target number p9_fbc_link_t endp_type; uint8_t endp_unit_id; // iovalid SCOM addresses/control field uint64_t iovalid_or_addr; uint64_t iovalid_clear_addr; uint8_t iovalid_field_start_bit; // EXTFIR/RAS control field uint8_t ras_fir_field_bit; // DL layer SCOM addresses uint64_t dl_fir_addr; uint64_t dl_control_addr; // TL layer SCOM addresses uint64_t tl_fir_addr; uint8_t tl_fir_trained_field_start_bit; uint64_t tl_link_delay_addr; uint32_t tl_link_delay_hi_start_bit; uint32_t tl_link_delay_lo_start_bit; }; // link constants const uint32_t P9_FBC_UTILS_MAX_X_LINKS = 7; const uint32_t P9_FBC_UTILS_MAX_A_LINKS = 4; const p9_fbc_link_ctl_t P9_FBC_XBUS_LINK_CTL_ARR[P9_FBC_UTILS_MAX_X_LINKS] = { { ELECTRICAL, 0, PERV_XB_CPLT_CONF1_OR, PERV_XB_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X0_FIR_ERR, XBUS_LL0_LL0_LL0_IOEL_FIR_REG, XBUS_0_LL0_IOEL_CONTROL, PU_PB_IOE_FIR_REG, PU_PB_IOE_FIR_REG_FMR00_TRAINED, PU_PB_ELINK_DLY_0123_REG, 4, 20 }, { ELECTRICAL, 1, PERV_XB_CPLT_CONF1_OR, PERV_XB_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_6D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X1_FIR_ERR, XBUS_1_LL1_LL1_LL1_IOEL_FIR_REG, XBUS_1_LL1_IOEL_CONTROL, PU_PB_IOE_FIR_REG, PU_PB_IOE_FIR_REG_FMR02_TRAINED, PU_PB_ELINK_DLY_0123_REG, 36, 52 }, { ELECTRICAL, 2, PERV_XB_CPLT_CONF1_OR, PERV_XB_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_8D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X2_FIR_ERR, XBUS_2_LL2_LL2_LL2_IOEL_FIR_REG, XBUS_2_LL2_IOEL_CONTROL, PU_PB_IOE_FIR_REG, PU_PB_IOE_FIR_REG_FMR04_TRAINED, PU_PB_ELINK_DLY_45_REG, 4, 20 }, { OPTICAL, 0, PERV_OB0_CPLT_CONF1_OR, PERV_OB0_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X3_FIR_ERR, OBUS_LL0_LL0_LL0_PB_IOOL_FIR_REG, OBUS_0_LL0_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR00_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 4, 20 }, { OPTICAL, 1, PERV_OB1_CPLT_CONF1_OR, PERV_OB1_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X4_FIR_ERR, OBUS_1_LL1_LL1_LL1_PB_IOOL_FIR_REG, OBUS_1_LL1_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR02_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 36, 52 }, { OPTICAL, 2, PERV_OB2_CPLT_CONF1_OR, PERV_OB2_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X5_FIR_ERR, OBUS_2_LL2_LL2_LL2_PB_IOOL_FIR_REG, OBUS_2_LL2_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR04_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 4, 20 }, { OPTICAL, 3, PERV_OB3_CPLT_CONF1_OR, PERV_OB3_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X6_FIR_ERR, OBUS_3_LL3_LL3_LL3_PB_IOOL_FIR_REG, OBUS_3_LL3_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR06_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 36, 52 } }; const p9_fbc_link_ctl_t P9_FBC_ABUS_LINK_CTL_ARR[P9_FBC_UTILS_MAX_A_LINKS] = { { OPTICAL, 0, PERV_OB0_CPLT_CONF1_OR, PERV_OB0_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X3_FIR_ERR, OBUS_LL0_LL0_LL0_PB_IOOL_FIR_REG, OBUS_0_LL0_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR00_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 4, 20 }, { OPTICAL, 1, PERV_OB1_CPLT_CONF1_OR, PERV_OB1_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X4_FIR_ERR, OBUS_1_LL1_LL1_LL1_PB_IOOL_FIR_REG, OBUS_1_LL1_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR02_TRAINED, PU_IOE_PB_OLINK_DLY_0123_REG, 36, 52 }, { OPTICAL, 2, PERV_OB2_CPLT_CONF1_OR, PERV_OB2_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X5_FIR_ERR, OBUS_2_LL2_LL2_LL2_PB_IOOL_FIR_REG, OBUS_2_LL2_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR04_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 4, 20 }, { OPTICAL, 3, PERV_OB3_CPLT_CONF1_OR, PERV_OB3_CPLT_CONF1_CLEAR, PERV_1_CPLT_CONF1_IOVALID_4D, PU_PB_CENT_SM1_EXTFIR_MASK_REG_PB_X6_FIR_ERR, OBUS_3_LL3_LL3_LL3_PB_IOOL_FIR_REG, OBUS_3_LL3_IOOL_CONTROL, PU_IOE_PB_IOO_FIR_REG, PU_IOE_PB_IOO_FIR_REG_FMR06_TRAINED, PU_IOE_PB_OLINK_DLY_4567_REG, 36, 52 } }; // range of fabric node/chip ID fields const uint8_t P9_FBC_UTILS_NUM_CHIP_IDS = 8; const uint8_t P9_FBC_UTILS_NUM_GROUP_IDS = 8; //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ /// /// @brief Utility function to read & return fabric group ID attribute /// /// @tparam T template parameter, passed in target. /// @param[in] i_target Reference to chip/chiplet target /// @param[out] o_group_id Group ID value /// /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. /// template<fapi2::TargetType T> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<T>& i_target, uint8_t& o_group_id); // Specialization for proc chip target template<> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t& o_group_id); // Specialization for XBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target, uint8_t& o_group_id); // Specialization for OBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_group_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target, uint8_t& o_group_id); /// /// @brief Utility function to read & return fabric chip ID attribute /// /// @tparam T template parameter, passed in target. /// @param[in] i_target Reference to chip/chiplet target /// @param[out] o_chip_id chip ID value /// /// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. /// template<fapi2::TargetType T> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<T>& i_target, uint8_t& o_chip_id); // Specialization for proc chip target template<> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t& o_chip_id); // Specialization for XBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target, uint8_t& o_chip_id); // Specialization for OBUS chiplet target template<> fapi2::ReturnCode p9_fbc_utils_get_chip_id_attr( const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target, uint8_t& o_chip_id); #endif // _P9_FBC_SMP_UTILS_H_ <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org> // #include "GosmoreRunner.h" #include "MarbleDebug.h" #include "MarbleDirs.h" #include "routing/RouteSkeleton.h" #include "GeoDataDocument.h" #include <QtCore/QProcess> #include <QtCore/QMap> namespace Marble { class GosmoreRunnerPrivate { public: QFileInfo m_gosmoreMapFile; GeoDataLineString retrieveWaypoints( const QString &query ) const; GeoDataDocument* createDocument( GeoDataLineString* routeWaypoints ) const; GeoDataLineString parseGosmoreOutput( const QByteArray &content ) const; void merge( GeoDataLineString* one, const GeoDataLineString& two ) const; /** Static to share the cache among all instances */ static QMap<QString, GeoDataLineString> m_partialRoutes; }; QMap<QString, GeoDataLineString> GosmoreRunnerPrivate::m_partialRoutes; void GosmoreRunnerPrivate::merge( GeoDataLineString* one, const GeoDataLineString& two ) const { Q_ASSERT( one ); QVector<GeoDataCoordinates>::const_iterator iter = two.constBegin(); for( ; iter != two.constEnd(); ++iter ) { /** @todo: It might be needed to cut off some points at the start or end */ one->append( *iter ); } } GeoDataLineString GosmoreRunnerPrivate::retrieveWaypoints( const QString &query ) const { if ( m_partialRoutes.contains(query) ) { return m_partialRoutes[query]; } QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("QUERY_STRING", query); QProcess gosmore; gosmore.setProcessEnvironment(env); gosmore.start("gosmore", QStringList() << m_gosmoreMapFile.absoluteFilePath() ); if (!gosmore.waitForStarted(5000)) { mDebug() << "Couldn't start gosmore from the current PATH. Install it to retrieve routing results from gosmore."; return GeoDataLineString(); } if ( gosmore.waitForFinished(15000) ) { m_partialRoutes[query] = parseGosmoreOutput( gosmore.readAllStandardOutput() ); return m_partialRoutes[query]; } else { mDebug() << "Couldn't stop gosmore"; } return GeoDataLineString(); } GeoDataLineString GosmoreRunnerPrivate::parseGosmoreOutput( const QByteArray &content ) const { GeoDataLineString routeWaypoints; QStringList lines = QString::fromLocal8Bit( content ).split( '\r' ); foreach( const QString &line, lines ) { QStringList fields = line.split(','); if (fields.size() >= 5) { qreal lon = fields.at(1).toDouble(); qreal lat = fields.at(0).toDouble(); GeoDataCoordinates coordinates( lon, lat, 0.0, GeoDataCoordinates::Degree ); routeWaypoints.append( coordinates ); } } return routeWaypoints; } GeoDataDocument* GosmoreRunnerPrivate::createDocument( GeoDataLineString* routeWaypoints ) const { if ( !routeWaypoints || routeWaypoints->isEmpty() ) { return 0; } GeoDataDocument* result = new GeoDataDocument(); GeoDataPlacemark* routePlacemark = new GeoDataPlacemark; routePlacemark->setName( "Route" ); routePlacemark->setGeometry( routeWaypoints ); result->append( routePlacemark ); QString name = "%1 %2 (Gosmore)"; QString unit = "m"; qreal length = routeWaypoints->length( EARTH_RADIUS ); if (length >= 1000) { length /= 1000.0; unit = "km"; } result->setName( name.arg( length, 0, 'f', 1 ).arg( unit ) ); return result; } GosmoreRunner::GosmoreRunner( QObject *parent ) : MarbleAbstractRunner( parent ), d( new GosmoreRunnerPrivate ) { // Check installation QDir mapDir( MarbleDirs::localPath() + "/maps/earth/gosmore/" ); d->m_gosmoreMapFile = QFileInfo ( mapDir, "gosmore.pak" ); } GosmoreRunner::~GosmoreRunner() { delete d; } GeoDataFeature::GeoDataVisualCategory GosmoreRunner::category() const { return GeoDataFeature::OsmSite; } void GosmoreRunner::retrieveRoute( RouteSkeleton *route ) { if ( !d->m_gosmoreMapFile.exists() ) { emit routeCalculated( 0 ); return; } GeoDataLineString* wayPoints = new GeoDataLineString; for( int i=0; i<route->size()-1; ++i ) { QString queryString = "flat=%1&flon=%2&tlat=%3&tlon=%4&fastest=1&v=motorcar"; GeoDataCoordinates source = route->at(i); double fLon = source.longitude( GeoDataCoordinates::Degree ); double fLat = source.latitude( GeoDataCoordinates::Degree ); queryString = queryString.arg(fLat, 0, 'f', 8).arg(fLon, 0, 'f', 8); GeoDataCoordinates destination = route->at(i+1); double tLon = destination.longitude( GeoDataCoordinates::Degree ); double tLat = destination.latitude( GeoDataCoordinates::Degree ); queryString = queryString.arg(tLat, 0, 'f', 8).arg(tLon, 0, 'f', 8); d->merge( wayPoints, d->retrieveWaypoints( queryString ) ); } GeoDataDocument* result = d->createDocument( wayPoints ); emit routeCalculated( result ); } } // namespace Marble <commit_msg>set LC_ALL to C in the gosmore process environment<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org> // #include "GosmoreRunner.h" #include "MarbleDebug.h" #include "MarbleDirs.h" #include "routing/RouteSkeleton.h" #include "GeoDataDocument.h" #include <QtCore/QProcess> #include <QtCore/QMap> namespace Marble { class GosmoreRunnerPrivate { public: QFileInfo m_gosmoreMapFile; GeoDataLineString retrieveWaypoints( const QString &query ) const; GeoDataDocument* createDocument( GeoDataLineString* routeWaypoints ) const; GeoDataLineString parseGosmoreOutput( const QByteArray &content ) const; void merge( GeoDataLineString* one, const GeoDataLineString& two ) const; /** Static to share the cache among all instances */ static QMap<QString, GeoDataLineString> m_partialRoutes; }; QMap<QString, GeoDataLineString> GosmoreRunnerPrivate::m_partialRoutes; void GosmoreRunnerPrivate::merge( GeoDataLineString* one, const GeoDataLineString& two ) const { Q_ASSERT( one ); QVector<GeoDataCoordinates>::const_iterator iter = two.constBegin(); for( ; iter != two.constEnd(); ++iter ) { /** @todo: It might be needed to cut off some points at the start or end */ one->append( *iter ); } } GeoDataLineString GosmoreRunnerPrivate::retrieveWaypoints( const QString &query ) const { if ( m_partialRoutes.contains(query) ) { return m_partialRoutes[query]; } QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("QUERY_STRING", query); env.insert("LC_ALL", "C"); QProcess gosmore; gosmore.setProcessEnvironment(env); gosmore.start("gosmore", QStringList() << m_gosmoreMapFile.absoluteFilePath() ); if (!gosmore.waitForStarted(5000)) { mDebug() << "Couldn't start gosmore from the current PATH. Install it to retrieve routing results from gosmore."; return GeoDataLineString(); } if ( gosmore.waitForFinished(15000) ) { m_partialRoutes[query] = parseGosmoreOutput( gosmore.readAllStandardOutput() ); return m_partialRoutes[query]; } else { mDebug() << "Couldn't stop gosmore"; } return GeoDataLineString(); } GeoDataLineString GosmoreRunnerPrivate::parseGosmoreOutput( const QByteArray &content ) const { GeoDataLineString routeWaypoints; QStringList lines = QString::fromLocal8Bit( content ).split( '\r' ); foreach( const QString &line, lines ) { QStringList fields = line.split(','); if (fields.size() >= 5) { qreal lon = fields.at(1).toDouble(); qreal lat = fields.at(0).toDouble(); GeoDataCoordinates coordinates( lon, lat, 0.0, GeoDataCoordinates::Degree ); routeWaypoints.append( coordinates ); } } return routeWaypoints; } GeoDataDocument* GosmoreRunnerPrivate::createDocument( GeoDataLineString* routeWaypoints ) const { if ( !routeWaypoints || routeWaypoints->isEmpty() ) { return 0; } GeoDataDocument* result = new GeoDataDocument(); GeoDataPlacemark* routePlacemark = new GeoDataPlacemark; routePlacemark->setName( "Route" ); routePlacemark->setGeometry( routeWaypoints ); result->append( routePlacemark ); QString name = "%1 %2 (Gosmore)"; QString unit = "m"; qreal length = routeWaypoints->length( EARTH_RADIUS ); if (length >= 1000) { length /= 1000.0; unit = "km"; } result->setName( name.arg( length, 0, 'f', 1 ).arg( unit ) ); return result; } GosmoreRunner::GosmoreRunner( QObject *parent ) : MarbleAbstractRunner( parent ), d( new GosmoreRunnerPrivate ) { // Check installation QDir mapDir( MarbleDirs::localPath() + "/maps/earth/gosmore/" ); d->m_gosmoreMapFile = QFileInfo ( mapDir, "gosmore.pak" ); } GosmoreRunner::~GosmoreRunner() { delete d; } GeoDataFeature::GeoDataVisualCategory GosmoreRunner::category() const { return GeoDataFeature::OsmSite; } void GosmoreRunner::retrieveRoute( RouteSkeleton *route ) { if ( !d->m_gosmoreMapFile.exists() ) { emit routeCalculated( 0 ); return; } GeoDataLineString* wayPoints = new GeoDataLineString; for( int i=0; i<route->size()-1; ++i ) { QString queryString = "flat=%1&flon=%2&tlat=%3&tlon=%4&fastest=1&v=motorcar"; GeoDataCoordinates source = route->at(i); double fLon = source.longitude( GeoDataCoordinates::Degree ); double fLat = source.latitude( GeoDataCoordinates::Degree ); queryString = queryString.arg(fLat, 0, 'f', 8).arg(fLon, 0, 'f', 8); GeoDataCoordinates destination = route->at(i+1); double tLon = destination.longitude( GeoDataCoordinates::Degree ); double tLat = destination.latitude( GeoDataCoordinates::Degree ); queryString = queryString.arg(tLat, 0, 'f', 8).arg(tLon, 0, 'f', 8); d->merge( wayPoints, d->retrieveWaypoints( queryString ) ); } GeoDataDocument* result = d->createDocument( wayPoints ); emit routeCalculated( result ); } } // namespace Marble <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Research In Motion ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtSensors module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "bbsensorbackend.h" #include "bbguihelper.h" #include <QtCore/QDebug> #include <QtCore/qmath.h> #include <fcntl.h> static const int microSecondsPerSecond = 1000 * 1000; static const int defaultBufferSize = 10; static int microSecondsToHertz(uint microSeconds) { return microSecondsPerSecond / microSeconds; } static uint hertzToMicroSeconds(int hertz) { return microSecondsPerSecond / hertz; } static void remapMatrix(const float inputMatrix[3*3], const float mappingMatrix[4], float outputMatrix[3*3]) { int i,j,k; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { //only goto 2 because last column stays unchanged outputMatrix[i*3+j] = 0; for (k = 0; k < 2; k++) { //only goto 2 because we know rotation matrix is zero in bottom row outputMatrix[i*3+j] += inputMatrix[i*3+k] * mappingMatrix[k*2+j]; } } outputMatrix[i*3+2] = inputMatrix[i*3+2]; } } BbSensorBackendBase::BbSensorBackendBase(const QString &devicePath, sensor_type_e sensorType, QSensor *sensor) : QSensorBackend(sensor), m_deviceFile(devicePath), m_sensorType(sensorType), m_guiHelper(0) { m_mappingMatrix[0] = m_mappingMatrix[3] = 1; m_mappingMatrix[1] = m_mappingMatrix[2] = 0; connect(sensor, SIGNAL(alwaysOnChanged()), this, SLOT(applyAlwaysOnProperty())); // Set some sensible default values sensor->setProperty("efficientBufferSize", defaultBufferSize); sensor->setProperty("maxBufferSize", defaultBufferSize); } BbGuiHelper *BbSensorBackendBase::guiHelper() const { return m_guiHelper; } QFile &BbSensorBackendBase::deviceFile() { return m_deviceFile; } sensor_type_e BbSensorBackendBase::sensorType() const { return m_sensorType; } void BbSensorBackendBase::initSensorInfo() { if (!m_deviceFile.open(QFile::ReadOnly)) { qDebug() << "initSensorInfo(): Failed to open" << m_deviceFile.fileName() << ":" << m_deviceFile.errorString(); } else { sensor_devctl_info_u deviceInfo; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_INFO, &deviceInfo, sizeof(deviceInfo), NULL); if (result != EOK) { perror(QString::fromLatin1("Querying sensor info for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } else { if (addDefaultRange()) { addOutputRange(convertValue(deviceInfo.rx.info.range_min), convertValue(deviceInfo.rx.info.range_max), convertValue(deviceInfo.rx.info.resolution)); } // Min and max intentionally swapped here, as the minimum delay is the maximum rate addDataRate(microSecondsToHertz(deviceInfo.rx.info.delay_max), microSecondsToHertz(deviceInfo.rx.info.delay_min)); } additionalDeviceInit(); m_deviceFile.close(); } } void BbSensorBackendBase::setGuiHelper(BbGuiHelper *guiHelper) { Q_ASSERT(!m_guiHelper); m_guiHelper = guiHelper; connect(m_guiHelper, SIGNAL(applicationActiveChanged()), this, SLOT(updatePauseState())); connect(guiHelper, SIGNAL(orientationChanged()), this, SLOT(updateOrientation())); updateOrientation(); } void BbSensorBackendBase::additionalDeviceInit() { } bool BbSensorBackendBase::addDefaultRange() { return true; } qreal BbSensorBackendBase::convertValue(float bbValue) { return bbValue; } bool BbSensorBackendBase::isAutoAxisRemappingEnabled() const { return sensor()->property("automaticAxisRemapping").toBool(); } void BbSensorBackendBase::remapMatrix(const float inputMatrix[], float outputMatrix[]) { if (!isAutoAxisRemappingEnabled() || m_guiHelper->currentOrientation() == 0) { memcpy(outputMatrix, inputMatrix, sizeof(float) * 9); return; } ::remapMatrix(inputMatrix, m_mappingMatrix, outputMatrix); } void BbSensorBackendBase::remapAxes(float *x, float *y, float *z) { Q_ASSERT(x && y && z); if (!isAutoAxisRemappingEnabled() || m_guiHelper->currentOrientation() == 0) return; const int angle = m_guiHelper->currentOrientation(); const float oldX = *x; const float oldY = *y; switch (angle) { case 90: *x = -oldY; *y = oldX; break; case 180: *x = -oldX; *y = -oldY; break; case 270: *x = oldY; *y = -oldX; break; } } void BbSensorBackendBase::start() { Q_ASSERT(m_guiHelper); if (!m_deviceFile.open(QFile::ReadOnly | QFile::Unbuffered)) { qDebug() << "Starting sensor" << m_deviceFile.fileName() << "failed:" << m_deviceFile.errorString(); sensorError(m_deviceFile.error()); return; } const int rateInHertz = sensor()->dataRate(); if (rateInHertz != 0) { const uint rateInMicroseconds = hertzToMicroSeconds(rateInHertz); sensor_devctl_rate_u deviceRate; deviceRate.tx.rate = rateInMicroseconds; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_RATE, &deviceRate, sizeof(deviceRate), NULL); if (result != EOK) { perror(QString::fromLatin1("Setting sensor rate for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } } // Explicitly switch to non-blocking mode, otherwise read() will wait until new sensor // data is available, and we have no way to check if there is more data or not (bytesAvailable() // does not work for unbuffered mode) const int oldFlags = fcntl(m_deviceFile.handle(), F_GETFL); if (fcntl(m_deviceFile.handle(), F_SETFL, oldFlags | O_NONBLOCK) == -1) { perror(QString::fromLatin1("Starting sensor %1 failed, fcntl() returned -1") .arg(m_deviceFile.fileName()).toLocal8Bit()); sensorError(errno); stop(); return; } // Activate event queuing if needed bool ok = false; const int requestedBufferSize = sensor()->property("bufferSize").toInt(&ok); if (ok && requestedBufferSize > 1) { sensor_devctl_queue_u queueControl; queueControl.tx.enable = 1; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_QUEUE, &queueControl, sizeof(queueControl), NULL); if (result != EOK) { perror(QString::fromLatin1("Enabling sensor queuing for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } const int actualBufferSize = queueControl.rx.size; sensor()->setProperty("bufferSize", actualBufferSize); sensor()->setProperty("efficientBufferSize", actualBufferSize); sensor()->setProperty("maxBufferSize", actualBufferSize); } applyAlwaysOnProperty(); m_socketNotifier.reset(new QSocketNotifier(m_deviceFile.handle(), QSocketNotifier::Read)); connect(m_socketNotifier.data(), SIGNAL(activated(int)), this, SLOT(dataAvailable())); } void BbSensorBackendBase::stop() { m_socketNotifier.reset(); m_deviceFile.close(); } bool BbSensorBackendBase::isFeatureSupported(QSensor::Feature feature) const { switch (feature) { case QSensor::AlwaysOn: case QSensor::Buffering: return true; case QSensor::Reserved: case QSensor::GeoValues: case QSensor::FieldOfView: break; } return false; } void BbSensorBackendBase::dataAvailable() { Q_FOREVER { sensor_event_t event; const qint64 numBytes = m_deviceFile.read(reinterpret_cast<char *>(&event), sizeof(sensor_event_t)); if (numBytes == -1) { break; } else if (numBytes == sizeof(sensor_event_t)) { processEvent(event); } else { qDebug() << "Reading sensor event data for" << m_deviceFile.fileName() << "failed (unexpected data size):" << m_deviceFile.errorString(); } } } void BbSensorBackendBase::applyAlwaysOnProperty() { if (!m_deviceFile.isOpen()) return; sensor_devctl_bkgrnd_u bgState; bgState.tx.enable = sensor()->isAlwaysOn() ? 1 : 0; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_BKGRND, &bgState, sizeof(bgState), NULL); if (result != EOK) { perror(QString::fromLatin1("Setting sensor always on for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } // We might need to pause now updatePauseState(); } void BbSensorBackendBase::setPaused(bool paused) { if (!m_deviceFile.isOpen()) return; sensor_devctl_enable_u enableState; enableState.tx.enable = paused ? 0 : 1; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_ENABLE, &enableState, sizeof(enableState), NULL); if (result != EOK) { perror(QString::fromLatin1("Setting sensor enabled (%1) for %2 failed") .arg(paused) .arg(m_deviceFile.fileName()).toLocal8Bit()); } } void BbSensorBackendBase::updatePauseState() { setPaused(!sensor()->isAlwaysOn() && !m_guiHelper->applicationActive()); } void BbSensorBackendBase::updateOrientation() { // ### I can't really test this, the rotation matrix has too many glitches and drifts over time, // making any measurement quite hard const int rotationAngle = guiHelper()->currentOrientation(); m_mappingMatrix[0] = cos(rotationAngle*M_PI/180); m_mappingMatrix[1] = sin(rotationAngle*M_PI/180); m_mappingMatrix[2] = -sin(rotationAngle*M_PI/180); m_mappingMatrix[3] = cos(rotationAngle*M_PI/180); } <commit_msg>Blackberry: Fix potential division by zero.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Research In Motion ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtSensors module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "bbsensorbackend.h" #include "bbguihelper.h" #include <QtCore/QDebug> #include <QtCore/qmath.h> #include <fcntl.h> static const int microSecondsPerSecond = 1000 * 1000; static const int defaultBufferSize = 10; static int microSecondsToHertz(uint microSeconds) { return microSecondsPerSecond / microSeconds; } static uint hertzToMicroSeconds(int hertz) { return microSecondsPerSecond / hertz; } static void remapMatrix(const float inputMatrix[3*3], const float mappingMatrix[4], float outputMatrix[3*3]) { int i,j,k; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { //only goto 2 because last column stays unchanged outputMatrix[i*3+j] = 0; for (k = 0; k < 2; k++) { //only goto 2 because we know rotation matrix is zero in bottom row outputMatrix[i*3+j] += inputMatrix[i*3+k] * mappingMatrix[k*2+j]; } } outputMatrix[i*3+2] = inputMatrix[i*3+2]; } } BbSensorBackendBase::BbSensorBackendBase(const QString &devicePath, sensor_type_e sensorType, QSensor *sensor) : QSensorBackend(sensor), m_deviceFile(devicePath), m_sensorType(sensorType), m_guiHelper(0) { m_mappingMatrix[0] = m_mappingMatrix[3] = 1; m_mappingMatrix[1] = m_mappingMatrix[2] = 0; connect(sensor, SIGNAL(alwaysOnChanged()), this, SLOT(applyAlwaysOnProperty())); // Set some sensible default values sensor->setProperty("efficientBufferSize", defaultBufferSize); sensor->setProperty("maxBufferSize", defaultBufferSize); } BbGuiHelper *BbSensorBackendBase::guiHelper() const { return m_guiHelper; } QFile &BbSensorBackendBase::deviceFile() { return m_deviceFile; } sensor_type_e BbSensorBackendBase::sensorType() const { return m_sensorType; } void BbSensorBackendBase::initSensorInfo() { if (!m_deviceFile.open(QFile::ReadOnly)) { qDebug() << "initSensorInfo(): Failed to open" << m_deviceFile.fileName() << ":" << m_deviceFile.errorString(); } else { sensor_devctl_info_u deviceInfo; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_INFO, &deviceInfo, sizeof(deviceInfo), NULL); if (result != EOK) { perror(QString::fromLatin1("Querying sensor info for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } else { if (addDefaultRange()) { addOutputRange(convertValue(deviceInfo.rx.info.range_min), convertValue(deviceInfo.rx.info.range_max), convertValue(deviceInfo.rx.info.resolution)); } if (deviceInfo.rx.info.delay_max > 0 && deviceInfo.rx.info.delay_min > 0) { // Min and max intentionally swapped here, as the minimum delay is the maximum rate addDataRate(microSecondsToHertz(deviceInfo.rx.info.delay_max), microSecondsToHertz(deviceInfo.rx.info.delay_min)); } } additionalDeviceInit(); m_deviceFile.close(); } } void BbSensorBackendBase::setGuiHelper(BbGuiHelper *guiHelper) { Q_ASSERT(!m_guiHelper); m_guiHelper = guiHelper; connect(m_guiHelper, SIGNAL(applicationActiveChanged()), this, SLOT(updatePauseState())); connect(guiHelper, SIGNAL(orientationChanged()), this, SLOT(updateOrientation())); updateOrientation(); } void BbSensorBackendBase::additionalDeviceInit() { } bool BbSensorBackendBase::addDefaultRange() { return true; } qreal BbSensorBackendBase::convertValue(float bbValue) { return bbValue; } bool BbSensorBackendBase::isAutoAxisRemappingEnabled() const { return sensor()->property("automaticAxisRemapping").toBool(); } void BbSensorBackendBase::remapMatrix(const float inputMatrix[], float outputMatrix[]) { if (!isAutoAxisRemappingEnabled() || m_guiHelper->currentOrientation() == 0) { memcpy(outputMatrix, inputMatrix, sizeof(float) * 9); return; } ::remapMatrix(inputMatrix, m_mappingMatrix, outputMatrix); } void BbSensorBackendBase::remapAxes(float *x, float *y, float *z) { Q_ASSERT(x && y && z); if (!isAutoAxisRemappingEnabled() || m_guiHelper->currentOrientation() == 0) return; const int angle = m_guiHelper->currentOrientation(); const float oldX = *x; const float oldY = *y; switch (angle) { case 90: *x = -oldY; *y = oldX; break; case 180: *x = -oldX; *y = -oldY; break; case 270: *x = oldY; *y = -oldX; break; } } void BbSensorBackendBase::start() { Q_ASSERT(m_guiHelper); if (!m_deviceFile.open(QFile::ReadOnly | QFile::Unbuffered)) { qDebug() << "Starting sensor" << m_deviceFile.fileName() << "failed:" << m_deviceFile.errorString(); sensorError(m_deviceFile.error()); return; } const int rateInHertz = sensor()->dataRate(); if (rateInHertz != 0) { const uint rateInMicroseconds = hertzToMicroSeconds(rateInHertz); sensor_devctl_rate_u deviceRate; deviceRate.tx.rate = rateInMicroseconds; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_RATE, &deviceRate, sizeof(deviceRate), NULL); if (result != EOK) { perror(QString::fromLatin1("Setting sensor rate for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } } // Explicitly switch to non-blocking mode, otherwise read() will wait until new sensor // data is available, and we have no way to check if there is more data or not (bytesAvailable() // does not work for unbuffered mode) const int oldFlags = fcntl(m_deviceFile.handle(), F_GETFL); if (fcntl(m_deviceFile.handle(), F_SETFL, oldFlags | O_NONBLOCK) == -1) { perror(QString::fromLatin1("Starting sensor %1 failed, fcntl() returned -1") .arg(m_deviceFile.fileName()).toLocal8Bit()); sensorError(errno); stop(); return; } // Activate event queuing if needed bool ok = false; const int requestedBufferSize = sensor()->property("bufferSize").toInt(&ok); if (ok && requestedBufferSize > 1) { sensor_devctl_queue_u queueControl; queueControl.tx.enable = 1; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_QUEUE, &queueControl, sizeof(queueControl), NULL); if (result != EOK) { perror(QString::fromLatin1("Enabling sensor queuing for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } const int actualBufferSize = queueControl.rx.size; sensor()->setProperty("bufferSize", actualBufferSize); sensor()->setProperty("efficientBufferSize", actualBufferSize); sensor()->setProperty("maxBufferSize", actualBufferSize); } applyAlwaysOnProperty(); m_socketNotifier.reset(new QSocketNotifier(m_deviceFile.handle(), QSocketNotifier::Read)); connect(m_socketNotifier.data(), SIGNAL(activated(int)), this, SLOT(dataAvailable())); } void BbSensorBackendBase::stop() { m_socketNotifier.reset(); m_deviceFile.close(); } bool BbSensorBackendBase::isFeatureSupported(QSensor::Feature feature) const { switch (feature) { case QSensor::AlwaysOn: case QSensor::Buffering: return true; case QSensor::Reserved: case QSensor::GeoValues: case QSensor::FieldOfView: break; } return false; } void BbSensorBackendBase::dataAvailable() { Q_FOREVER { sensor_event_t event; const qint64 numBytes = m_deviceFile.read(reinterpret_cast<char *>(&event), sizeof(sensor_event_t)); if (numBytes == -1) { break; } else if (numBytes == sizeof(sensor_event_t)) { processEvent(event); } else { qDebug() << "Reading sensor event data for" << m_deviceFile.fileName() << "failed (unexpected data size):" << m_deviceFile.errorString(); } } } void BbSensorBackendBase::applyAlwaysOnProperty() { if (!m_deviceFile.isOpen()) return; sensor_devctl_bkgrnd_u bgState; bgState.tx.enable = sensor()->isAlwaysOn() ? 1 : 0; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_BKGRND, &bgState, sizeof(bgState), NULL); if (result != EOK) { perror(QString::fromLatin1("Setting sensor always on for %1 failed") .arg(m_deviceFile.fileName()).toLocal8Bit()); } // We might need to pause now updatePauseState(); } void BbSensorBackendBase::setPaused(bool paused) { if (!m_deviceFile.isOpen()) return; sensor_devctl_enable_u enableState; enableState.tx.enable = paused ? 0 : 1; const int result = devctl(m_deviceFile.handle(), DCMD_SENSOR_ENABLE, &enableState, sizeof(enableState), NULL); if (result != EOK) { perror(QString::fromLatin1("Setting sensor enabled (%1) for %2 failed") .arg(paused) .arg(m_deviceFile.fileName()).toLocal8Bit()); } } void BbSensorBackendBase::updatePauseState() { setPaused(!sensor()->isAlwaysOn() && !m_guiHelper->applicationActive()); } void BbSensorBackendBase::updateOrientation() { // ### I can't really test this, the rotation matrix has too many glitches and drifts over time, // making any measurement quite hard const int rotationAngle = guiHelper()->currentOrientation(); m_mappingMatrix[0] = cos(rotationAngle*M_PI/180); m_mappingMatrix[1] = sin(rotationAngle*M_PI/180); m_mappingMatrix[2] = -sin(rotationAngle*M_PI/180); m_mappingMatrix[3] = cos(rotationAngle*M_PI/180); } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * combocid.c * Combo command ID support routines * * Before version 8.3, HeapTupleHeaderData had separate fields for cmin * and cmax. To reduce the header size, cmin and cmax are now overlayed * in the same field in the header. That usually works because you rarely * insert and delete a tuple in the same transaction, and we don't need * either field to remain valid after the originating transaction exits. * To make it work when the inserting transaction does delete the tuple, * we create a "combo" command ID and store that in the tuple header * instead of cmin and cmax. The combo command ID can be mapped to the * real cmin and cmax using a backend-private___ array, which is managed by * this module. * * To allow reusing existing combo cids, we also keep a hash table that * maps cmin,cmax pairs to combo cids. This keeps the data structure size * reasonable in most cases, since the number of unique pairs used by any * one transaction is likely to be small. * * With a 32-bit combo command id we can represent 2^32 distinct cmin,cmax * combinations. In the most perverse case where each command deletes a tuple * generated by every previous command, the number of combo command ids * required for N commands is N*(N+1)/2. That means that in the worst case, * that's enough for 92682 commands. In practice, you'll run out of memory * and/or disk space way before you reach that limit. * * The array and hash table are kept in TopTransactionContext, and are * destroyed at the end of each transaction. * * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/backend/utils/time/combocid.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "miscadmin.h" #include "access/htup_details.h" #include "access/xact.h" #include "storage/shmem.h" #include "utils/combocid.h" #include "utils/hsearch.h" #include "utils/memutils.h" /* Hash table to lookup combo cids by cmin and cmax */ thread_local static HTAB *comboHash = NULL; /* Key and entry structures for the hash table */ typedef struct { CommandId cmin; CommandId cmax; } ComboCidKeyData; typedef ComboCidKeyData *ComboCidKey; typedef struct { ComboCidKeyData key; CommandId combocid; } ComboCidEntryData; typedef ComboCidEntryData *ComboCidEntry; /* Initial size of the hash table */ #define CCID_HASH_SIZE 100 /* * An array of cmin,cmax pairs, indexed by combo command id. * To convert a combo cid to cmin and cmax, you do a simple array lookup. */ static ComboCidKey comboCids = NULL; static int usedComboCids = 0; /* number of elements in comboCids */ static int sizeComboCids = 0; /* allocated size of array */ /* Initial size of the array */ #define CCID_ARRAY_SIZE 100 /* prototypes for internal functions */ static CommandId GetComboCommandId(CommandId cmin, CommandId cmax); static CommandId GetRealCmin(CommandId combocid); static CommandId GetRealCmax(CommandId combocid); /**** External API ****/ /* * GetCmin and GetCmax assert that they are only called in situations where * they make sense, that is, can deliver a useful answer. If you have * reason to examine a tuple's t_cid field from a transaction other than * the originating one, use HeapTupleHeaderGetRawCommandId() directly. */ CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup) { CommandId cid = HeapTupleHeaderGetRawCommandId(tup); Assert(!(tup->t_infomask & HEAP_MOVED)); Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tup))); if (tup->t_infomask & HEAP_COMBOCID) return GetRealCmin(cid); else return cid; } CommandId HeapTupleHeaderGetCmax(HeapTupleHeader tup) { CommandId cid = HeapTupleHeaderGetRawCommandId(tup); Assert(!(tup->t_infomask & HEAP_MOVED)); /* * Because GetUpdateXid() performs memory allocations if xmax is a * multixact we can't Assert() if we're inside a critical section. This * weakens the check, but not using GetCmax() inside one would complicate * things too much. */ Assert(CritSectionCount > 0 || TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(tup))); if (tup->t_infomask & HEAP_COMBOCID) return GetRealCmax(cid); else return cid; } /* * Given a tuple we are about to delete, determine the correct value to store * into its t_cid field. * * If we don't need a combo CID, *cmax is unchanged and *iscombo is set to * FALSE. If we do need one, *cmax is replaced by a combo CID and *iscombo * is set to TRUE. * * The reason this is separate from the actual HeapTupleHeaderSetCmax() * operation is that this could fail due to out-of-memory conditions. Hence * we need to do this before entering the critical section that actually * changes the tuple in shared buffers. */ void HeapTupleHeaderAdjustCmax(HeapTupleHeader tup, CommandId *cmax, bool *iscombo) { /* * If we're marking a tuple deleted that was inserted by (any * subtransaction of) our transaction, we need to use a combo command id. * Test for HeapTupleHeaderXminCommitted() first, because it's cheaper * than a TransactionIdIsCurrentTransactionId call. */ if (!HeapTupleHeaderXminCommitted(tup) && TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetRawXmin(tup))) { CommandId cmin = HeapTupleHeaderGetCmin(tup); *cmax = GetComboCommandId(cmin, *cmax); *iscombo = true; } else { *iscombo = false; } } /* * Combo command ids are only interesting to the inserting and deleting * transaction, so we can forget about them at the end of transaction. */ void AtEOXact_ComboCid(void) { /* * Don't bother to pfree. These are allocated in TopTransactionContext, so * they're going to go away at the end of transaction anyway. */ comboHash = NULL; comboCids = NULL; usedComboCids = 0; sizeComboCids = 0; } /**** Internal routines ****/ /* * Get a combo command id that maps to cmin and cmax. * * We try to reuse old combo command ids when possible. */ static CommandId GetComboCommandId(CommandId cmin, CommandId cmax) { CommandId combocid; ComboCidKeyData key; ComboCidEntry entry; bool found; /* * Create the hash table and array the first time we need to use combo * cids in the transaction. */ if (comboHash == NULL) { HASHCTL hash_ctl; memset(&hash_ctl, 0, sizeof(hash_ctl)); hash_ctl.keysize = sizeof(ComboCidKeyData); hash_ctl.entrysize = sizeof(ComboCidEntryData); hash_ctl.hcxt = TopTransactionContext; comboHash = hash_create("Combo CIDs", CCID_HASH_SIZE, &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); comboCids = (ComboCidKeyData *) MemoryContextAlloc(TopTransactionContext, sizeof(ComboCidKeyData) * CCID_ARRAY_SIZE); sizeComboCids = CCID_ARRAY_SIZE; usedComboCids = 0; } /* Lookup or create a hash entry with the desired cmin/cmax */ /* We assume there is no struct padding in ComboCidKeyData! */ key.cmin = cmin; key.cmax = cmax; entry = (ComboCidEntry) hash_search(comboHash, (void *) &key, HASH_ENTER, &found); if (found) { /* Reuse an existing combo cid */ return entry->combocid; } /* * We have to create a new___ combo cid. Check that there's room for it in * the array, and grow it if there isn't. */ if (usedComboCids >= sizeComboCids) { /* We need to grow the array */ int newsize = sizeComboCids * 2; comboCids = (ComboCidKeyData *) repalloc(comboCids, sizeof(ComboCidKeyData) * newsize); sizeComboCids = newsize; } combocid = usedComboCids; comboCids[combocid].cmin = cmin; comboCids[combocid].cmax = cmax; usedComboCids++; entry->combocid = combocid; return combocid; } static CommandId GetRealCmin(CommandId combocid) { Assert(combocid < usedComboCids); return comboCids[combocid].cmin; } static CommandId GetRealCmax(CommandId combocid) { Assert(combocid < usedComboCids); return comboCids[combocid].cmax; } /* * Estimate the amount of space required to serialize the current ComboCID * state. */ Size EstimateComboCIDStateSpace(void) { Size size; /* Add space required for saving usedComboCids */ size = sizeof(int); /* Add space required for saving the combocids key */ size = add_size(size, mul_size(sizeof(ComboCidKeyData), usedComboCids)); return size; } /* * Serialize the ComboCID state into the memory, beginning at start_address. * maxsize should be at least as large as the value returned by * EstimateComboCIDStateSpace. */ void SerializeComboCIDState(Size maxsize, char *start_address) { char *endptr; /* First, we store the number of currently-existing ComboCIDs. */ * (int *) start_address = usedComboCids; /* If maxsize is too small, throw an error. */ endptr = start_address + sizeof(int) + (sizeof(ComboCidKeyData) * usedComboCids); if (endptr < start_address || endptr > start_address + maxsize) elog(ERROR, "not enough space to serialize ComboCID state"); /* Now, copy the actual cmin/cmax pairs. */ memcpy(start_address + sizeof(int), comboCids, (sizeof(ComboCidKeyData) * usedComboCids)); } /* * Read the ComboCID state at the specified address and initialize this * backend with the same ComboCIDs. This is only valid in a backend that * currently has no ComboCIDs (and only makes sense if the transaction state * is serialized and restored as well). */ void RestoreComboCIDState(char *comboCIDstate) { int num_elements; ComboCidKeyData *keydata; int i; CommandId cid; Assert(!comboCids && !comboHash); /* First, we retrieve the number of ComboCIDs that were serialized. */ num_elements = * (int *) comboCIDstate; keydata = (ComboCidKeyData *) (comboCIDstate + sizeof(int)); /* Use GetComboCommandId to restore each ComboCID. */ for (i = 0; i < num_elements; i++) { cid = GetComboCommandId(keydata[i].cmin, keydata[i].cmax); /* Verify that we got the expected answer. */ if (cid != i) elog(ERROR, "unexpected command ID while restoring combo CIDs"); } } <commit_msg>looks like these should be thread_local<commit_after>/*------------------------------------------------------------------------- * * combocid.c * Combo command ID support routines * * Before version 8.3, HeapTupleHeaderData had separate fields for cmin * and cmax. To reduce the header size, cmin and cmax are now overlayed * in the same field in the header. That usually works because you rarely * insert and delete a tuple in the same transaction, and we don't need * either field to remain valid after the originating transaction exits. * To make it work when the inserting transaction does delete the tuple, * we create a "combo" command ID and store that in the tuple header * instead of cmin and cmax. The combo command ID can be mapped to the * real cmin and cmax using a backend-private___ array, which is managed by * this module. * * To allow reusing existing combo cids, we also keep a hash table that * maps cmin,cmax pairs to combo cids. This keeps the data structure size * reasonable in most cases, since the number of unique pairs used by any * one transaction is likely to be small. * * With a 32-bit combo command id we can represent 2^32 distinct cmin,cmax * combinations. In the most perverse case where each command deletes a tuple * generated by every previous command, the number of combo command ids * required for N commands is N*(N+1)/2. That means that in the worst case, * that's enough for 92682 commands. In practice, you'll run out of memory * and/or disk space way before you reach that limit. * * The array and hash table are kept in TopTransactionContext, and are * destroyed at the end of each transaction. * * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/backend/utils/time/combocid.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "miscadmin.h" #include "access/htup_details.h" #include "access/xact.h" #include "storage/shmem.h" #include "utils/combocid.h" #include "utils/hsearch.h" #include "utils/memutils.h" /* Hash table to lookup combo cids by cmin and cmax */ thread_local static HTAB *comboHash = NULL; /* Key and entry structures for the hash table */ typedef struct { CommandId cmin; CommandId cmax; } ComboCidKeyData; typedef ComboCidKeyData *ComboCidKey; typedef struct { ComboCidKeyData key; CommandId combocid; } ComboCidEntryData; typedef ComboCidEntryData *ComboCidEntry; /* Initial size of the hash table */ #define CCID_HASH_SIZE 100 /* * An array of cmin,cmax pairs, indexed by combo command id. * To convert a combo cid to cmin and cmax, you do a simple array lookup. */ thread_local static ComboCidKey comboCids = NULL; thread_local static int usedComboCids = 0; /* number of elements in comboCids */ thread_local static int sizeComboCids = 0; /* allocated size of array */ /* Initial size of the array */ #define CCID_ARRAY_SIZE 100 /* prototypes for internal functions */ static CommandId GetComboCommandId(CommandId cmin, CommandId cmax); static CommandId GetRealCmin(CommandId combocid); static CommandId GetRealCmax(CommandId combocid); /**** External API ****/ /* * GetCmin and GetCmax assert that they are only called in situations where * they make sense, that is, can deliver a useful answer. If you have * reason to examine a tuple's t_cid field from a transaction other than * the originating one, use HeapTupleHeaderGetRawCommandId() directly. */ CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup) { CommandId cid = HeapTupleHeaderGetRawCommandId(tup); Assert(!(tup->t_infomask & HEAP_MOVED)); Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tup))); if (tup->t_infomask & HEAP_COMBOCID) return GetRealCmin(cid); else return cid; } CommandId HeapTupleHeaderGetCmax(HeapTupleHeader tup) { CommandId cid = HeapTupleHeaderGetRawCommandId(tup); Assert(!(tup->t_infomask & HEAP_MOVED)); /* * Because GetUpdateXid() performs memory allocations if xmax is a * multixact we can't Assert() if we're inside a critical section. This * weakens the check, but not using GetCmax() inside one would complicate * things too much. */ Assert(CritSectionCount > 0 || TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(tup))); if (tup->t_infomask & HEAP_COMBOCID) return GetRealCmax(cid); else return cid; } /* * Given a tuple we are about to delete, determine the correct value to store * into its t_cid field. * * If we don't need a combo CID, *cmax is unchanged and *iscombo is set to * FALSE. If we do need one, *cmax is replaced by a combo CID and *iscombo * is set to TRUE. * * The reason this is separate from the actual HeapTupleHeaderSetCmax() * operation is that this could fail due to out-of-memory conditions. Hence * we need to do this before entering the critical section that actually * changes the tuple in shared buffers. */ void HeapTupleHeaderAdjustCmax(HeapTupleHeader tup, CommandId *cmax, bool *iscombo) { /* * If we're marking a tuple deleted that was inserted by (any * subtransaction of) our transaction, we need to use a combo command id. * Test for HeapTupleHeaderXminCommitted() first, because it's cheaper * than a TransactionIdIsCurrentTransactionId call. */ if (!HeapTupleHeaderXminCommitted(tup) && TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetRawXmin(tup))) { CommandId cmin = HeapTupleHeaderGetCmin(tup); *cmax = GetComboCommandId(cmin, *cmax); *iscombo = true; } else { *iscombo = false; } } /* * Combo command ids are only interesting to the inserting and deleting * transaction, so we can forget about them at the end of transaction. */ void AtEOXact_ComboCid(void) { /* * Don't bother to pfree. These are allocated in TopTransactionContext, so * they're going to go away at the end of transaction anyway. */ comboHash = NULL; comboCids = NULL; usedComboCids = 0; sizeComboCids = 0; } /**** Internal routines ****/ /* * Get a combo command id that maps to cmin and cmax. * * We try to reuse old combo command ids when possible. */ static CommandId GetComboCommandId(CommandId cmin, CommandId cmax) { CommandId combocid; ComboCidKeyData key; ComboCidEntry entry; bool found; /* * Create the hash table and array the first time we need to use combo * cids in the transaction. */ if (comboHash == NULL) { HASHCTL hash_ctl; memset(&hash_ctl, 0, sizeof(hash_ctl)); hash_ctl.keysize = sizeof(ComboCidKeyData); hash_ctl.entrysize = sizeof(ComboCidEntryData); hash_ctl.hcxt = TopTransactionContext; comboHash = hash_create("Combo CIDs", CCID_HASH_SIZE, &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); comboCids = (ComboCidKeyData *) MemoryContextAlloc(TopTransactionContext, sizeof(ComboCidKeyData) * CCID_ARRAY_SIZE); sizeComboCids = CCID_ARRAY_SIZE; usedComboCids = 0; } /* Lookup or create a hash entry with the desired cmin/cmax */ /* We assume there is no struct padding in ComboCidKeyData! */ key.cmin = cmin; key.cmax = cmax; entry = (ComboCidEntry) hash_search(comboHash, (void *) &key, HASH_ENTER, &found); if (found) { /* Reuse an existing combo cid */ return entry->combocid; } /* * We have to create a new___ combo cid. Check that there's room for it in * the array, and grow it if there isn't. */ if (usedComboCids >= sizeComboCids) { /* We need to grow the array */ int newsize = sizeComboCids * 2; comboCids = (ComboCidKeyData *) repalloc(comboCids, sizeof(ComboCidKeyData) * newsize); sizeComboCids = newsize; } combocid = usedComboCids; comboCids[combocid].cmin = cmin; comboCids[combocid].cmax = cmax; usedComboCids++; entry->combocid = combocid; return combocid; } static CommandId GetRealCmin(CommandId combocid) { Assert(combocid < usedComboCids); return comboCids[combocid].cmin; } static CommandId GetRealCmax(CommandId combocid) { Assert(combocid < usedComboCids); return comboCids[combocid].cmax; } /* * Estimate the amount of space required to serialize the current ComboCID * state. */ Size EstimateComboCIDStateSpace(void) { Size size; /* Add space required for saving usedComboCids */ size = sizeof(int); /* Add space required for saving the combocids key */ size = add_size(size, mul_size(sizeof(ComboCidKeyData), usedComboCids)); return size; } /* * Serialize the ComboCID state into the memory, beginning at start_address. * maxsize should be at least as large as the value returned by * EstimateComboCIDStateSpace. */ void SerializeComboCIDState(Size maxsize, char *start_address) { char *endptr; /* First, we store the number of currently-existing ComboCIDs. */ * (int *) start_address = usedComboCids; /* If maxsize is too small, throw an error. */ endptr = start_address + sizeof(int) + (sizeof(ComboCidKeyData) * usedComboCids); if (endptr < start_address || endptr > start_address + maxsize) elog(ERROR, "not enough space to serialize ComboCID state"); /* Now, copy the actual cmin/cmax pairs. */ memcpy(start_address + sizeof(int), comboCids, (sizeof(ComboCidKeyData) * usedComboCids)); } /* * Read the ComboCID state at the specified address and initialize this * backend with the same ComboCIDs. This is only valid in a backend that * currently has no ComboCIDs (and only makes sense if the transaction state * is serialized and restored as well). */ void RestoreComboCIDState(char *comboCIDstate) { int num_elements; ComboCidKeyData *keydata; int i; CommandId cid; Assert(!comboCids && !comboHash); /* First, we retrieve the number of ComboCIDs that were serialized. */ num_elements = * (int *) comboCIDstate; keydata = (ComboCidKeyData *) (comboCIDstate + sizeof(int)); /* Use GetComboCommandId to restore each ComboCID. */ for (i = 0; i < num_elements; i++) { cid = GetComboCommandId(keydata[i].cmin, keydata[i].cmax); /* Verify that we got the expected answer. */ if (cid != i) elog(ERROR, "unexpected command ID while restoring combo CIDs"); } } <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #include "RateThreadOutput.hpp" void rd::RateThreadOutput::init(yarp::os::ResourceFinder &rf) { rateMs = DEFAULT_RATE_MS; printf("--------------------------------------------------------------\n"); if (rf.check("help")) { printf("RateThreadOutput options:\n"); printf("\t--help (this help)\t--from [file.ini]\t--context [path]\n"); printf("\t--rateMs (default: \"%d\")\n",rateMs); } if (rf.check("rateMs")) rateMs = rf.find("rateMs").asInt(); printf("RateThreadOutput using rateMs: %d.\n", rateMs); printf("--------------------------------------------------------------\n"); if(rf.check("help")) { ::exit(1); } // http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-3-your-first.html if (SDL_Init(SDL_INIT_VIDEO) != 0) { RD_ERROR("SDL_Init(): %s\n",SDL_GetError()); ::exit(1); } //display = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF); display = SDL_SetVideoMode(128, 128, 8, SDL_HWSURFACE | SDL_DOUBLEBUF); if (display == NULL) { RD_ERROR("SDL_SetVideoMode(): %s\n",SDL_GetError()); ::exit(1); } // Set the title bar SDL_WM_SetCaption("Robot Devastation", "Robot Devastation"); this->setRate(rateMs); this->start(); } void rd::RateThreadOutput::run() { //printf("[RateThreadOutput] run()\n"); yarp::sig::ImageOf<yarp::sig::PixelRgb> *inYarpImg = pInImg->read(false); if (inYarpImg==NULL) { printf("No img yet...\n"); return; }; // http://stackoverflow.com/questions/393954/how-to-convert-an-opencv-iplimage-to-an-sdl-surface SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)inYarpImg->getIplImage(), inYarpImg->width(), inYarpImg->height(), inYarpImg->depth, 3, 0xff0000, 0x00ff00, 0x0000ff, 0 ); printf("[RateThreadOutput] w:%d h:%d.\n",inYarpImg->width(), inYarpImg->height()); //http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-4-how-to-load.html // Apply the image to the display if (SDL_BlitSurface(surface, NULL, display, NULL) != 0) { //cerr << "SDL_BlitSurface() Failed: " << SDL_GetError() << endl; RD_ERROR("SDL_BlitSurface(): %s\n", SDL_GetError()); ::exit(1); } //int x_pos=0, y_pos=0; //SDL_Rect rcDest = { x_pos, y_pos, 0, 0 }; //SDL_BlitSurface ( image, NULL, surface, &rcDest ); // {yarp ImageOf Rgb -> openCv Mat Bgr} //IplImage *inIplImage = cvCreateImage(cvSize(inYarpImg->width(), inYarpImg->height()), // IPL_DEPTH_8U, 3 ); //cvCvtColor((IplImage*)inYarpImg->getIplImage(), inIplImage, CV_RGB2BGR); //Mat inCvMat(inIplImage); } void rd::RateThreadOutput::setInImg(yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelRgb> > * pInImg) { this->pInImg = pInImg; } <commit_msg>bad color but okay shape on output of cam stream<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #include "RateThreadOutput.hpp" void rd::RateThreadOutput::init(yarp::os::ResourceFinder &rf) { rateMs = DEFAULT_RATE_MS; printf("--------------------------------------------------------------\n"); if (rf.check("help")) { printf("RateThreadOutput options:\n"); printf("\t--help (this help)\t--from [file.ini]\t--context [path]\n"); printf("\t--rateMs (default: \"%d\")\n",rateMs); } if (rf.check("rateMs")) rateMs = rf.find("rateMs").asInt(); printf("RateThreadOutput using rateMs: %d.\n", rateMs); printf("--------------------------------------------------------------\n"); if(rf.check("help")) { ::exit(1); } // http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-3-your-first.html if (SDL_Init(SDL_INIT_VIDEO) != 0) { RD_ERROR("SDL_Init(): %s\n",SDL_GetError()); ::exit(1); } //display = SDL_SetVideoMode(640, 480, 24, SDL_HWSURFACE | SDL_DOUBLEBUF);SDL_SWSURFACE display = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE); //display = SDL_SetVideoMode(128, 128, 8, SDL_HWSURFACE | SDL_DOUBLEBUF); if (display == NULL) { RD_ERROR("SDL_SetVideoMode(): %s\n",SDL_GetError()); ::exit(1); } // Set the title bar SDL_WM_SetCaption("Robot Devastation", "Robot Devastation"); this->setRate(rateMs); this->start(); } void rd::RateThreadOutput::run() { //printf("[RateThreadOutput] run()\n"); yarp::sig::ImageOf<yarp::sig::PixelRgb> *inYarpImg = pInImg->read(false); if (inYarpImg==NULL) { printf("No img yet...\n"); return; }; int depth=8; // the depth of the surface in bits int channels=3; // int widthstep = 1920; // the length of a row of pixels in bytes // http://stackoverflow.com/1questions/393954/how-to-convert-an-opencv-iplimage-to-an-sdl-surface // SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)inYarpImg->getIplImage(), SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)inYarpImg->getRawImage(), inYarpImg->width(), inYarpImg->height(), depth*channels, widthstep, 0x0000ff, 0x00ff00, 0xff0000, 0 ); //http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-4-how-to-load.html // Apply the image to the display if (SDL_BlitSurface(surface, NULL, display, NULL) != 0) { RD_ERROR("SDL_BlitSurface(): %s\n", SDL_GetError()); ::exit(1); } SDL_Flip(display); printf("[RateThreadOutput] p:%p, w:%d h:%d, %d.\n",surface,inYarpImg->width(), inYarpImg->height(),inYarpImg->getRowSize()); //SDL_Event evt; //SDL_WaitEvent(&evt); //int x_pos=0, y_pos=0; //SDL_Rect rcDest = { x_pos, y_pos, 0, 0 }; //SDL_BlitSurface ( image, NULL, surface, &rcDest ); // {yarp ImageOf Rgb -> openCv Mat Bgr} //IplImage *inIplImage = cvCreateImage(cvSize(inYarpImg->width(), inYarpImg->height()), // IPL_DEPTH_8U, 3 ); //cvCvtColor((IplImage*)inYarpImg->getIplImage(), inIplImage, CV_RGB2BGR); //Mat inCvMat(inIplImage); } void rd::RateThreadOutput::setInImg(yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelRgb> > * pInImg) { this->pInImg = pInImg; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_scan_compression.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __P9_SCAN_COMPRESSION_H__ #define __P9_SCAN_COMPRESSION_H__ /// This header declares and documents the entry points defined in /// p9_scan_compression.C. Some constants are also required by the scan /// decompression HOMER assembly procedures. #ifndef __ASSEMBLER__ #include <stdint.h> /// Compressed Scan Chain Data Structure Format /// /// The compressed scan ring data structure must be 8-byte aligned in /// memory. The container data structure consists of a header /// followed by an arbitrary number of 8 byte doublewords containing the /// compressed scan data. Images are always stored and processed in /// big-endian byte order. The header format is common across all /// decompression algorithms. /// /// ATTENTION: /// The RS4v2 CompressedScanData had a 4 byte magic value with 0x34 ("4") /// within its third byte, which is at the same byte position as iv_version /// now. Users of CompressedScanData which use the magic value to detect /// a ring data structure won't be able to distingish old and new /// CompressedScanData for iv_version being 0x34. In the very unlikely case /// that we would have that many versions of ComprossedScanData, it is /// strongly suggested to simply skip 0x34 as version number. /// /// Bytes - Content /// /// 0:1 - A 16-bit "magic number" that identifies and validates the /// compression algorithm used to compress the data ("RS"). /// /// 2 - An 8-bit version number (3 for the time being). /// /// 3 - An 8-bit type field distinguishing different scan data types /// (0 for non-CMSK, 1 for CMSK). /// /// 4:5 - The 16-bit size of the uncompressed scan data with /// this header in \e bytes. This is not the exact length of actual scan data /// in bits, but the number of bytes used by the RS4 encoding to store those /// compressed scan bits. /// /// 6:7 - The 16-bit ring ID uniquely identifying the ring. /// /// 8:11 - scan scom register value typedef struct { uint16_t iv_magic; uint8_t iv_version; uint8_t iv_type; uint16_t iv_size; uint16_t iv_ringId; uint32_t iv_scanAddr; } CompressedScanData; /// Endian-translate a CompressedScanData structure /// /// \param o_data A pointer to a CompressedScanData structure to receive the /// endian-translated form of \a i_data. /// /// \param i_data A pointer to the original CompressedScanData structure. /// /// This API performs an endian-converting copy of a CompressedScanData /// structure. This copy is guaranteed to be done in such a way that \a i_data /// and \a o_data may be the same pointer for in-place conversion. Due to the /// symmetry of reverse, translating a structure twice is always guaranteed to /// return the origial structure to its original byte order. void compressed_scan_data_translate(CompressedScanData* o_data, CompressedScanData* i_data); /// Compress a scan string using the RS4 compression algorithm /// /// \param[in,out] io_rs4 This is a pointer to a memory area which must be /// large enough to hold the worst-case result of compressing \a i_data_str /// and \a i_care_str (see below). Note that the CompressedScanData is /// always created in big-endian format, however the caller can use /// compresed_scan_data_translate() to create a copy of the header in /// host format. /// /// \param[in] i_size The size of the buffer pointed to by \a io_rs4. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.h for more info.) /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_compress() instead. /// /// We always require the worst-case amount of memory including the header and /// any rounding required to guarantee that the data size is a multiple of 8 /// bytes. The final image size is also rounded up to a multiple of 8 bytes. /// If the \a io_size is less than this amount (based on \a i_length) the /// call will fail. /// /// \returns See \ref scan_compression_codes int _rs4_compress(CompressedScanData* io_rs4, const uint32_t i_size, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint16_t i_ringId); /// Compress a scan string using the RS4 compression algorithm /// /// \param[out] o_rs4 This algorithm uses malloc() to allocate memory for the /// compressed data, and returns a pointer to this memory in \a o_rs4. After /// the call this memory is owned by the caller who is responsible for /// free()-ing the data area once it is no longer required. Note that the /// CompressedScanData is always created in big-endian format, however the /// caller can use compresed_scan_data_translate() to create a copy of the /// header in host format. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.c for more info.) /// /// \returns See \ref scan_compression_codes int rs4_compress(CompressedScanData** o_rs4, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint8_t i_ringId); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[in,out] io_data_str A caller-supplied data area to contain the /// decompressed string. The \a i_stringSize must be large enough to contain /// the decompressed string, which is the size of the original string in bits /// rounded up to the nearest byte. /// /// \param[in,out] io_care_str A caller-supplied data area to contain the /// decompressed care mask. The \a i_stringSize must be large enough to contain /// the decompressed care mask, which is the size of the original string in /// bits rounded up to the nearest byte. /// /// \param[in] i_size The size in \e bytes of \a io_data_str and \a io_care_str. /// /// \param[out] o_length The length of the decompressed string in \e bits. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header + data to be /// decompressed. /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_decompress() instead. /// /// \returns See \ref scan_compression_codes int _rs4_decompress(uint8_t* io_data_str, uint8_t* io_care_str, uint32_t i_size, uint32_t* o_length, const CompressedScanData* i_rs4); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[out] o_data_str The API malloc()-s this data area to contain the /// decompressed string. After this call the caller owns \a o_data_str and is /// responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_care_str The API malloc()-s this data area to contain the /// decompressed care mask. After this call the caller owns \a o_care_str and /// is responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_length The length of the decompressed string and care mask /// in \e bits. The caller may assume that \a o_data_str and o_care_str each /// contain at least (\a o_length + 7) / 8 \e bytes. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header and data to be /// decompressed. /// /// \returns See \ref scan_compression_codes int rs4_decompress(uint8_t** o_data_str, uint8_t** o_care_str, uint32_t* o_length, const CompressedScanData* i_rs4); /// Determine if an RS4 compressed scan string is all 0 /// /// \param[in] i_data A pointer to the CompressedScanData header + data to be /// /// \param[out] o_redundant Set to 1 if the RS4 string is the compressed form /// of a scan string that is all 0; Otherwise set to 0. /// /// \returns See \ref scan _compression_code int rs4_redundant(const CompressedScanData* i_data, int* o_redundant); #endif // __ASSEMBLER__ /// \defgroup scan_compression_magic Scan Compression Magic Numbers /// /// @ { /// RS4 Magic #define RS4_MAGIC 0x5253 /* "RS" */ /// @} /// \defgroup scan_compression_version_type version and type accessors /// /// @{ /// The current version of the CompressedScanData structure /// /// This constant is required to be a #define to guarantee consistency between /// the header format and compiled code. #define RS4_VERSION 3 /// Scan data types #define RS4_SCAN_DATA_TYPE_CMSK 1 #define RS4_SCAN_DATA_TYPE_NON_CMSK 0 /// @} /// \defgroup scan_compression_codes Scan Compression Return Codes /// /// @{ /// Normal return code #define SCAN_COMPRESSION_OK (uint8_t)0 /// The (de)compression algorithm could not allocate enough memory for the /// (de)compression. #define SCAN_COMPRESSION_NO_MEMORY (uint8_t)1 /// Magic number mismatch on scan decompression #define SCAN_DECOMPRESSION_MAGIC_ERROR (uint8_t)2 /// Decompression size error /// /// Decompression produced a string of a size different than indicated in the /// header, indicating either a bug or data corruption. Note that the entire /// application should be considered corrupted if this error occurs since it /// may not be discovered until after the decompression buffer is /// overrun. This error may also be returned by rs4_redundant() in the event /// of inconsistencies in the compressed string. #define SCAN_DECOMPRESSION_SIZE_ERROR (uint8_t)3 /// A buffer would overflow /// /// Either the caller-supplied memory buffer to _rs4_decompress() was too /// small to contain the decompressed string, or a caller-supplied buffer to /// _rs4_compress() was not large enough to hold the worst-case compressed /// string. #define SCAN_COMPRESSION_BUFFER_OVERFLOW (uint8_t)4 /// Inconsistent input data /// /// 1 in data is masked by 0 in care mask #define SCAN_COMPRESSION_INPUT_ERROR 5 /// Invalid transition in state machine #define SCAN_COMPRESSION_STATE_ERROR 6 /// wrong compression version #define SCAN_COMPRESSION_VERSION_ERROR 7 /// @} #endif // __P9_SCAN_COMPRESSION_H__ <commit_msg>Enablement of support for Stumped and Cmsk rings<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_scan_compression.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __P9_SCAN_COMPRESSION_H__ #define __P9_SCAN_COMPRESSION_H__ /// This header declares and documents the entry points defined in /// p9_scan_compression.C. Some constants are also required by the scan /// decompression HOMER assembly procedures. #ifndef __ASSEMBLER__ #include <stdint.h> /// Compressed Scan Chain Data Structure Format /// /// The compressed scan ring data structure must be 8-byte aligned in /// memory. The container data structure consists of a header /// followed by an arbitrary number of 8 byte doublewords containing the /// compressed scan data. Images are always stored and processed in /// big-endian byte order. The header format is common across all /// decompression algorithms. /// /// ATTENTION: /// The RS4v2 CompressedScanData had a 4 byte magic value with 0x34 ("4") /// within its third byte, which is at the same byte position as iv_version /// now. Users of CompressedScanData which use the magic value to detect /// a ring data structure won't be able to distingish old and new /// CompressedScanData for iv_version being 0x34. In the very unlikely case /// that we would have that many versions of ComprossedScanData, it is /// strongly suggested to simply skip 0x34 as version number. /// /// Bytes - Content /// /// 0:1 - A 16-bit "magic number" that identifies and validates the /// compression algorithm used to compress the data ("RS"). /// /// 2 - An 8-bit version number (3 for the time being). /// /// 3 - An 8-bit type field distinguishing different scan data types /// (0 for non-CMSK, 1 for CMSK). /// /// 4:5 - The 16-bit size of the compressed scan data with /// this header in \e bytes. This is not the exact length of actual scan data /// in bits, but the number of bytes used by the RS4 encoding to store those /// compressed scan bits. /// /// 6:7 - The 16-bit ring ID uniquely identifying the ring. /// /// 8:11 - scan scom register value typedef struct { uint16_t iv_magic; uint8_t iv_version; uint8_t iv_type; uint16_t iv_size; uint16_t iv_ringId; uint32_t iv_scanAddr; } CompressedScanData; /// Endian-translate a CompressedScanData structure /// /// \param o_data A pointer to a CompressedScanData structure to receive the /// endian-translated form of \a i_data. /// /// \param i_data A pointer to the original CompressedScanData structure. /// /// This API performs an endian-converting copy of a CompressedScanData /// structure. This copy is guaranteed to be done in such a way that \a i_data /// and \a o_data may be the same pointer for in-place conversion. Due to the /// symmetry of reverse, translating a structure twice is always guaranteed to /// return the origial structure to its original byte order. void compressed_scan_data_translate(CompressedScanData* o_data, CompressedScanData* i_data); /// Compress a scan string using the RS4 compression algorithm /// /// \param[in,out] io_rs4 This is a pointer to a memory area which must be /// large enough to hold the worst-case result of compressing \a i_data_str /// and \a i_care_str (see below). Note that the CompressedScanData is /// always created in big-endian format, however the caller can use /// compresed_scan_data_translate() to create a copy of the header in /// host format. /// /// \param[in] i_size The size of the buffer pointed to by \a io_rs4. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.h for more info.) /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_compress() instead. /// /// We always require the worst-case amount of memory including the header and /// any rounding required to guarantee that the data size is a multiple of 8 /// bytes. The final image size is also rounded up to a multiple of 8 bytes. /// If the \a io_size is less than this amount (based on \a i_length) the /// call will fail. /// /// \returns See \ref scan_compression_codes int _rs4_compress(CompressedScanData* io_rs4, const uint32_t i_size, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint16_t i_ringId); /// Compress a scan string using the RS4 compression algorithm /// /// \param[out] o_rs4 This algorithm uses malloc() to allocate memory for the /// compressed data, and returns a pointer to this memory in \a o_rs4. After /// the call this memory is owned by the caller who is responsible for /// free()-ing the data area once it is no longer required. Note that the /// CompressedScanData is always created in big-endian format, however the /// caller can use compresed_scan_data_translate() to create a copy of the /// header in host format. /// /// \param[in] i_data_str The string to compress. Scan data to compress is /// left-justified in this input string. /// /// \param[in] i_care_str The care mask that identifies which bits in the /// i_data_str that need to be scanned (written). String is left-justified. /// /// \param[in] i_length The length of the input string in \e bits. It is /// assumed the \a i_string contains at least (\a i_length + 7) / 8 bytes. /// /// \param[in] i_scanAddr The 32-bit scan address. /// /// \param[in] i_ringId The ring ID that uniquely identifies the ring name of /// a repair ring. (See p9_ring_id.c for more info.) /// /// \returns See \ref scan_compression_codes int rs4_compress(CompressedScanData** o_rs4, const uint8_t* i_data_str, const uint8_t* i_care_str, const uint32_t i_length, const uint32_t i_scanAddr, const uint8_t i_ringId); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[in,out] io_data_str A caller-supplied data area to contain the /// decompressed string. The \a i_stringSize must be large enough to contain /// the decompressed string, which is the size of the original string in bits /// rounded up to the nearest byte. /// /// \param[in,out] io_care_str A caller-supplied data area to contain the /// decompressed care mask. The \a i_stringSize must be large enough to contain /// the decompressed care mask, which is the size of the original string in /// bits rounded up to the nearest byte. /// /// \param[in] i_size The size in \e bytes of \a io_data_str and \a io_care_str. /// /// \param[out] o_length The length of the decompressed string in \e bits. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header + data to be /// decompressed. /// /// This API is required for integration with PHYP which does not support /// malloc(). Applications in environments supporting malloc() can use /// rs4_decompress() instead. /// /// \returns See \ref scan_compression_codes int _rs4_decompress(uint8_t* io_data_str, uint8_t* io_care_str, uint32_t i_size, uint32_t* o_length, const CompressedScanData* i_rs4); /// Decompress a scan string compressed using the RS4 compression algorithm /// /// \param[out] o_data_str The API malloc()-s this data area to contain the /// decompressed string. After this call the caller owns \a o_data_str and is /// responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_care_str The API malloc()-s this data area to contain the /// decompressed care mask. After this call the caller owns \a o_care_str and /// is responsible for free()-ing this data area once it is no longer required. /// /// \param[out] o_length The length of the decompressed string and care mask /// in \e bits. The caller may assume that \a o_data_str and o_care_str each /// contain at least (\a o_length + 7) / 8 \e bytes. /// /// \param[in] i_rs4 A pointer to the CompressedScanData header and data to be /// decompressed. /// /// \returns See \ref scan_compression_codes int rs4_decompress(uint8_t** o_data_str, uint8_t** o_care_str, uint32_t* o_length, const CompressedScanData* i_rs4); /// Determine if an RS4 compressed scan string is all 0 /// /// \param[in] i_data A pointer to the CompressedScanData header + data to be /// /// \param[out] o_redundant Set to 1 if the RS4 string is the compressed form /// of a scan string that is all 0; Otherwise set to 0. /// /// \returns See \ref scan _compression_code int rs4_redundant(const CompressedScanData* i_data, int* o_redundant); /// Check for CMSK ring in RS4 /// /// \param[in] i_rs4 A pointer to the RS4 CompressedScanData [header + data] /// /// \returns 1 if CMSK ring found, 0 otherwise int rs4_is_cmsk(CompressedScanData* i_rs4); /// Embed CMSK ring into an RS4 ring /// /// \param[inout] io_rs4 A pointer to the CompressedScanData [header + data] /// /// \param[in] i_rs4_cmsk A pointer to the cmsk CompressedScanData header + data to be embedded /// /// \returns See \ref scan_compression_codes int rs4_embed_cmsk(CompressedScanData** io_rs4, CompressedScanData* i_rs4_cmsk); /// Extract Stump & CMSK rings from an RS4 ring /// /// \param[in] i_rs4 A pointer to the CompressedScanData [header + data] /// /// \param[inout] i_rs4_stump A pointer to the Stump CompressedScanData [header + data] /// /// \param[inout] i_rs4_cmsk A pointer to the Cmsk CompressedScanData [header + data] /// /// \returns See \ref scan_compression_codes int rs4_extract_cmsk(CompressedScanData* i_rs4, CompressedScanData** io_rs4_stump, CompressedScanData** io_rs4_cmsk); #endif // __ASSEMBLER__ /// \defgroup scan_compression_magic Scan Compression Magic Numbers /// /// @ { /// RS4 Magic #define RS4_MAGIC 0x5253 /* "RS" */ /// @} /// \defgroup scan_compression_version_type version and type accessors /// /// @{ /// The current version of the CompressedScanData structure /// /// This constant is required to be a #define to guarantee consistency between /// the header format and compiled code. #define RS4_VERSION 3 /// Scan data types #define RS4_SCAN_DATA_TYPE_CMSK 1 #define RS4_SCAN_DATA_TYPE_NON_CMSK 0 /// @} /// \defgroup scan_compression_codes Scan Compression Return Codes /// /// @{ /// Normal return code #define SCAN_COMPRESSION_OK (uint8_t)0 /// The (de)compression algorithm could not allocate enough memory for the /// (de)compression. #define SCAN_COMPRESSION_NO_MEMORY (uint8_t)1 /// Magic number mismatch on scan decompression #define SCAN_DECOMPRESSION_MAGIC_ERROR (uint8_t)2 /// Decompression size error /// /// Decompression produced a string of a size different than indicated in the /// header, indicating either a bug or data corruption. Note that the entire /// application should be considered corrupted if this error occurs since it /// may not be discovered until after the decompression buffer is /// overrun. This error may also be returned by rs4_redundant() in the event /// of inconsistencies in the compressed string. #define SCAN_DECOMPRESSION_SIZE_ERROR (uint8_t)3 /// A buffer would overflow /// /// Either the caller-supplied memory buffer to _rs4_decompress() was too /// small to contain the decompressed string, or a caller-supplied buffer to /// _rs4_compress() was not large enough to hold the worst-case compressed /// string. #define SCAN_COMPRESSION_BUFFER_OVERFLOW (uint8_t)4 /// Inconsistent input data /// /// 1 in data is masked by 0 in care mask #define SCAN_COMPRESSION_INPUT_ERROR 5 /// Invalid transition in state machine #define SCAN_COMPRESSION_STATE_ERROR 6 /// wrong compression version #define SCAN_COMPRESSION_VERSION_ERROR 7 /// @} #endif // __P9_SCAN_COMPRESSION_H__ <|endoftext|>
<commit_before>/* DaiMysha GameDeV Tools * Light System * * * * * * This is meant to be used with the SFML graphic library */ #ifndef HEADER_DMGDVT_LIGHTSYSTEM #define HEADER_DMGDVT_LIGHTSYSTEM #include <list> #include <SFML/Graphics.hpp> #include "Light.hpp" namespace DMGDVT { namespace LS { class LightSystem { public: LightSystem(); ~LightSystem(); void addLight(Light* l, bool dynamic = false); //empties the lights void reset(); void render(const sf::View& screen, sf::RenderTarget& target); void render(const sf::IntRect& screen, sf::RenderTarget& target); void drawAABB(const sf::View& screen, sf::RenderTarget& target); void drawAABB(const sf::IntRect& screen, sf::RenderTarget& target); private: std::list<Light*> _lights; sf::RenderStates _multiplyState; sf::Shader _lightAttenuationShader; }; } } #endif // HEADER_DMGDVT_LIGHTSYSTEM <commit_msg>Removed copy constructor in LightSystem<commit_after>/* DaiMysha GameDeV Tools * Light System * * * * * * This is meant to be used with the SFML graphic library */ #ifndef HEADER_DMGDVT_LIGHTSYSTEM #define HEADER_DMGDVT_LIGHTSYSTEM #include <list> #include <SFML/Graphics.hpp> #include "Light.hpp" namespace DMGDVT { namespace LS { class LightSystem { public: LightSystem(); LightSystem(const LightSystem& ls) = delete; //doesn't make sense to copy an existing light system ~LightSystem(); void addLight(Light* l, bool dynamic = false); //empties the lights void reset(); void render(const sf::View& screen, sf::RenderTarget& target); void render(const sf::IntRect& screen, sf::RenderTarget& target); void drawAABB(const sf::View& screen, sf::RenderTarget& target); void drawAABB(const sf::IntRect& screen, sf::RenderTarget& target); private: std::list<Light*> _lights; sf::RenderStates _multiplyState; sf::Shader _lightAttenuationShader; }; } } #endif // HEADER_DMGDVT_LIGHTSYSTEM <|endoftext|>
<commit_before>/************************************************************************* Name: Isabell Jansson, Jonathan Bosson, Ronja Grosz File name: Viewport.cpp Viewport is used as a OpenGL controller. Viewport is responsible for managing all openGL related activities. *************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <iostream> #include <vector> #include <sstream> #include <iomanip> #include <string> #include <FreeImage.h> #include "../particle/SPH.h" #include "../render/Viewport.h" #include "../util/uVect.h" //#include "../util/AVIGenerator.h" #include "Shader.h" #define OUTPUT_FILE_PATH "frames/frame" const int PARTICLE_COUNT = 10000; //This variable dictates how many particles will be in the simulation std::string ZeroPadNumber(int num) { std::ostringstream ss; ss << std::setw(6) << std::setfill('0') << num; std::string result = ss.str(); if (result.length() > 4) { result.erase(0, result.length() - 4); } return result; } using namespace std; Viewport::Viewport() { phi = 0.0f; theta = PI / 4.0f; rad = 1.5f; zoomFactor = PI; newTime = deltaTime = currTime = 0.0f; fps = 0.0; timeSinceStart = new timer(); } Viewport::~Viewport(){} /* showFPS() - Calculate and report frames per second (updated once per second) in the window title bar */ void Viewport::displayFPS(GLFWwindow *window) { static double t0 = 0.0; static int frames = 0; double frametime = 0.0; static char titlestring[200]; double t; // Get current time t = glfwGetTime(); // Gets number of seconds since glfwInit() // If one second has passed, or if this is the very first frame if ((t - t0) > 1.0 || frames == 0) { fps = (double)frames / (t - t0); if (frames > 0) frametime = 1000.0 * (t - t0) / frames; sprintf(titlestring, "SPH, %.2f ms/frame (%.1f FPS)", frametime, fps); glfwSetWindowTitle(window, titlestring); // printf("Speed: %.1f FPS\n", fps); t0 = t; frames = 0; } frames++; //return fps; } void Viewport::init(void) //enable texture, lighting, shading. { //GL calls glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); // with? } void Viewport::initWorld() { Viewport::hydro = new SPH(PARTICLE_COUNT); //this is the object that will manage all of the particles Viewport::hydro->setTimer(timeSinceStart); //I'm setting a timer to bind the particles to real time regardless of the coputer that they are run on } void Viewport::setupPerspective(GLFWwindow *window, GLfloat *P) //just in case some one wants to resize the window { glfwGetWindowSize(window, &width, &height); P[0] = P[5] * height / width; glViewport(0, 0, width, height); } // Control the camera with the arrow keys. Hold left control button and UP/DOWN for zoom void Viewport::controlView(GLFWwindow *window) { newTime = glfwGetTime(); deltaTime = newTime - currTime; currTime = newTime; if (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) || glfwGetKey(window, GLFW_KEY_LEFT_CONTROL)) { if (glfwGetKey(window, GLFW_KEY_UP)) { if (rad > 0.0f) rad -= deltaTime*zoomFactor; } else if (glfwGetKey(window, GLFW_KEY_DOWN)) { rad += deltaTime*zoomFactor; } } else { if (glfwGetKey(window, GLFW_KEY_UP)) { theta += deltaTime*PI / 2.0; // Rotate 90 degrees per second if (theta >= PI / 2.0) theta = PI / 2.0; // Clamp at 90 } else if (glfwGetKey(window, GLFW_KEY_DOWN)) { theta -= deltaTime*PI / 2.0; // Rotate 90 degrees per second if (theta < 0.1f) theta = 0.1f; // Clamp at -90 } } if (glfwGetKey(window, GLFW_KEY_RIGHT)) { phi -= deltaTime*PI / 2.0; // Rotate 90 degrees per second (pi/2) phi = fmod(phi, PI*2.0); // Wrap around at 360 degrees (2*pi) if (phi < 0.0) phi += PI*2.0; // If phi<0, then fmod(phi,2*pi)<0 } else if (glfwGetKey(window, GLFW_KEY_LEFT)) { phi += deltaTime*PI / 2.0; // Rotate 90 degrees per second (pi/2) phi = fmod(phi, PI*2.0); } } int Viewport::start(int argc, char** argv) //initialize glut and set all of the call backs { GLfloat I[16] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; GLfloat P[16] = { 2.42f, 0.0f, 0.0f, 0.0f, 0.0f, 2.42f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, -0.2f, 0.0f }; GLint locationP; GLint locationMV; GLint locationLight; GLint locationCamera; glm::mat4 viewMatrix; glm::vec4 light; glm::vec4 cam; double deltaTime; double timeSinceAction = glfwGetTime(); bool record = false; // start GLEW extension handler if (!glfwInit()) { fprintf(stderr, "ERROR: could not start GLFW3\n"); return 1; } glfwDefaultWindowHints(); #ifdef __APPLE__ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif //create GLFW window and select context GLFWwindow* window = glfwCreateWindow(640, 480, "Fluid Simulation", NULL, NULL); if (!window) { fprintf(stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent(window); //start GLEW extension handler glewExperimental = GL_TRUE; glewInit(); // get version info const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string const GLubyte* version = glGetString(GL_VERSION); // version as a string printf("Renderer: %s\n", renderer); printf("OpenGL version supported %s\n", version); initWorld(); Shader phongShader; phongShader.createShader("glsl/vertexshader.glsl", "glsl/fragmentshader.glsl"); //link variables to shader locationMV = glGetUniformLocation(phongShader.programID, "MV"); locationP = glGetUniformLocation(phongShader.programID, "P"); //locationLight = glGetUniformLocation(phongShader.programID, "lightPos"); //locationCamera = glGetUniformLocation(phongShader.programID, "camPos"); int success = 0; int frameCount = 0; unsigned char* imageData = (unsigned char *)malloc((int)(640 * 480 * (3) + 1)); // Let's get started! while (!glfwWindowShouldClose(window)) { glfwPollEvents(); //GL calls init(); displayFPS(window); glUseProgram(phongShader.programID); glUniformMatrix4fv(locationP, 1, GL_FALSE, P); setupPerspective(window, P); controlView(window); cameraPosition = glm::vec3(0.0f, 0.0f, rad); deltaTime = glfwGetTime() - timeSinceAction; if (glfwGetKey(window, GLFW_KEY_R) && deltaTime > 0.5) { record = !record; if (record) std::cout << "Starting to record.." << std::endl; else std::cout << "Recorded " << deltaTime << " seconds (" << fps << "fps) Approximately " << 0.032*fps*deltaTime << " MB\n"; timeSinceAction = glfwGetTime(); } // I is the normal Identity matrix viewMatrix = glm::make_mat4(I); // Translate a bit down and backwards viewMatrix = viewMatrix * glm::translate(-cameraPosition); // Rotate with theta around X viewMatrix = viewMatrix * glm::rotate(theta, glm::vec3(1.0f, 0.0f, 0.0f)); // Rotate with phi around Y viewMatrix = viewMatrix * glm::rotate(phi, glm::vec3(0.0f, 1.0f, 0.0f)); //convert viewMatrix to float glUniformMatrix4fv(locationMV, 1, GL_FALSE, glm::value_ptr(viewMatrix)); /* light = glm::vec4(0.0, 5.0, 0.0, 1.0); cam = glm::vec4(0.0, 0.0, 0.0, 1.0); li = glm::inverse(viewMatrix)*light; cam = glm::inverse(viewMatrix)*cam; // send in light and camera location to glsl (not done in shaders yet) glUniform3fv(locationL, 1, glm::value_ptr(light)); glUniform3fv(locationCa, 1, glm::value_ptr(cam)); */ success = hydro->display(PARTICLE_COUNT); // Save the frame if (record) { stringstream ss; ss << OUTPUT_FILE_PATH << ZeroPadNumber(++frameCount) << ".png"; string fileName = ss.str(); // Make the BYTE array, factor of 3 because it's RBG. BYTE* pixels = new BYTE[ 3 * width * height]; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); // Convert to FreeImage format & save to file FIBITMAP* image = FreeImage_ConvertFromRawBits(pixels, width, height, 3 * width, 24, 0x0000FF, 0xFF0000, 0x00FF00, false); FreeImage_Save(FIF_PNG, image, fileName.c_str(), 0); // Free resources FreeImage_Unload(image); delete [] pixels; } glfwSwapBuffers(window); //swap the buffer } glfwTerminate(); free(imageData); return 0; } <commit_msg>Fixed output info of record-function<commit_after>/************************************************************************* Name: Isabell Jansson, Jonathan Bosson, Ronja Grosz File name: Viewport.cpp Viewport is used as a OpenGL controller. Viewport is responsible for managing all openGL related activities. *************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <iostream> #include <vector> #include <sstream> #include <iomanip> #include <string> #include <FreeImage.h> #include "../particle/SPH.h" #include "../render/Viewport.h" #include "../util/uVect.h" //#include "../util/AVIGenerator.h" #include "Shader.h" #define OUTPUT_FILE_PATH "frames/frame" const int PARTICLE_COUNT = 10000; //This variable dictates how many particles will be in the simulation std::string ZeroPadNumber(int num) { std::ostringstream ss; ss << std::setw(6) << std::setfill('0') << num; std::string result = ss.str(); if (result.length() > 4) { result.erase(0, result.length() - 4); } return result; } using namespace std; Viewport::Viewport() { phi = 0.0f; theta = PI / 4.0f; rad = 1.5f; zoomFactor = PI; newTime = deltaTime = currTime = 0.0f; fps = 0.0; timeSinceStart = new timer(); } Viewport::~Viewport(){} /* showFPS() - Calculate and report frames per second (updated once per second) in the window title bar */ void Viewport::displayFPS(GLFWwindow *window) { static double t0 = 0.0; static int frames = 0; double frametime = 0.0; static char titlestring[200]; double t; // Get current time t = glfwGetTime(); // Gets number of seconds since glfwInit() // If one second has passed, or if this is the very first frame if ((t - t0) > 1.0 || frames == 0) { fps = (double)frames / (t - t0); if (frames > 0) frametime = 1000.0 * (t - t0) / frames; sprintf(titlestring, "SPH, %.2f ms/frame (%.1f FPS)", frametime, fps); glfwSetWindowTitle(window, titlestring); // printf("Speed: %.1f FPS\n", fps); t0 = t; frames = 0; } frames++; //return fps; } void Viewport::init(void) //enable texture, lighting, shading. { //GL calls glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); // with? } void Viewport::initWorld() { Viewport::hydro = new SPH(PARTICLE_COUNT); //this is the object that will manage all of the particles Viewport::hydro->setTimer(timeSinceStart); //I'm setting a timer to bind the particles to real time regardless of the coputer that they are run on } void Viewport::setupPerspective(GLFWwindow *window, GLfloat *P) //just in case some one wants to resize the window { glfwGetWindowSize(window, &width, &height); P[0] = P[5] * height / width; glViewport(0, 0, width, height); } // Control the camera with the arrow keys. Hold left control button and UP/DOWN for zoom void Viewport::controlView(GLFWwindow *window) { newTime = glfwGetTime(); deltaTime = newTime - currTime; currTime = newTime; if (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) || glfwGetKey(window, GLFW_KEY_LEFT_CONTROL)) { if (glfwGetKey(window, GLFW_KEY_UP)) { if (rad > 0.0f) rad -= deltaTime*zoomFactor; } else if (glfwGetKey(window, GLFW_KEY_DOWN)) { rad += deltaTime*zoomFactor; } } else { if (glfwGetKey(window, GLFW_KEY_UP)) { theta += deltaTime*PI / 2.0; // Rotate 90 degrees per second if (theta >= PI / 2.0) theta = PI / 2.0; // Clamp at 90 } else if (glfwGetKey(window, GLFW_KEY_DOWN)) { theta -= deltaTime*PI / 2.0; // Rotate 90 degrees per second if (theta < 0.1f) theta = 0.1f; // Clamp at -90 } } if (glfwGetKey(window, GLFW_KEY_RIGHT)) { phi -= deltaTime*PI / 2.0; // Rotate 90 degrees per second (pi/2) phi = fmod(phi, PI*2.0); // Wrap around at 360 degrees (2*pi) if (phi < 0.0) phi += PI*2.0; // If phi<0, then fmod(phi,2*pi)<0 } else if (glfwGetKey(window, GLFW_KEY_LEFT)) { phi += deltaTime*PI / 2.0; // Rotate 90 degrees per second (pi/2) phi = fmod(phi, PI*2.0); } } int Viewport::start(int argc, char** argv) //initialize glut and set all of the call backs { GLfloat I[16] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; GLfloat P[16] = { 2.42f, 0.0f, 0.0f, 0.0f, 0.0f, 2.42f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, -0.2f, 0.0f }; GLint locationP; GLint locationMV; GLint locationLight; GLint locationCamera; glm::mat4 viewMatrix; glm::vec4 light; glm::vec4 cam; double deltaTime; double timeSinceAction = glfwGetTime(); bool record = false; // start GLEW extension handler if (!glfwInit()) { fprintf(stderr, "ERROR: could not start GLFW3\n"); return 1; } glfwDefaultWindowHints(); #ifdef __APPLE__ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif //create GLFW window and select context GLFWwindow* window = glfwCreateWindow(640, 480, "Fluid Simulation", NULL, NULL); if (!window) { fprintf(stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent(window); //start GLEW extension handler glewExperimental = GL_TRUE; glewInit(); // get version info const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string const GLubyte* version = glGetString(GL_VERSION); // version as a string printf("Renderer: %s\n", renderer); printf("OpenGL version supported %s\n", version); initWorld(); Shader phongShader; phongShader.createShader("glsl/vertexshader.glsl", "glsl/fragmentshader.glsl"); //link variables to shader locationMV = glGetUniformLocation(phongShader.programID, "MV"); locationP = glGetUniformLocation(phongShader.programID, "P"); //locationLight = glGetUniformLocation(phongShader.programID, "lightPos"); //locationCamera = glGetUniformLocation(phongShader.programID, "camPos"); int success = 0; int frameCount = 0; // Let's get started! while (!glfwWindowShouldClose(window)) { glfwPollEvents(); //GL calls init(); displayFPS(window); glUseProgram(phongShader.programID); glUniformMatrix4fv(locationP, 1, GL_FALSE, P); setupPerspective(window, P); controlView(window); cameraPosition = glm::vec3(0.0f, 0.0f, rad); deltaTime = glfwGetTime() - timeSinceAction; if (glfwGetKey(window, GLFW_KEY_R) && deltaTime > 0.5) { record = !record; if (record) std::cout << "Starting to record.." << std::endl; else std::cout << "Recorded " << deltaTime << " seconds (" << frameCount/deltaTime << "fps) Approximately " << ((double)width*height/10000000)*frameCount << " MB\n"; timeSinceAction = glfwGetTime(); } // I is the normal Identity matrix viewMatrix = glm::make_mat4(I); // Translate a bit down and backwards viewMatrix = viewMatrix * glm::translate(-cameraPosition); // Rotate with theta around X viewMatrix = viewMatrix * glm::rotate(theta, glm::vec3(1.0f, 0.0f, 0.0f)); // Rotate with phi around Y viewMatrix = viewMatrix * glm::rotate(phi, glm::vec3(0.0f, 1.0f, 0.0f)); //convert viewMatrix to float glUniformMatrix4fv(locationMV, 1, GL_FALSE, glm::value_ptr(viewMatrix)); /* light = glm::vec4(0.0, 5.0, 0.0, 1.0); cam = glm::vec4(0.0, 0.0, 0.0, 1.0); li = glm::inverse(viewMatrix)*light; cam = glm::inverse(viewMatrix)*cam; // send in light and camera location to glsl (not done in shaders yet) glUniform3fv(locationL, 1, glm::value_ptr(light)); glUniform3fv(locationCa, 1, glm::value_ptr(cam)); */ success = hydro->display(PARTICLE_COUNT); // Save the frame if (record) { frameCount++; stringstream ss; ss << OUTPUT_FILE_PATH << ZeroPadNumber(frameCount) << ".png"; string fileName = ss.str(); // Make the BYTE array, factor of 3 because it's RBG. BYTE* pixels = new BYTE[ 3 * width * height]; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); // Convert to FreeImage format & save to file FIBITMAP* image = FreeImage_ConvertFromRawBits(pixels, width, height, 3 * width, 24, 0x0000FF, 0xFF0000, 0x00FF00, false); FreeImage_Save(FIF_PNG, image, fileName.c_str(), 0); // Free resources FreeImage_Unload(image); delete [] pixels; } glfwSwapBuffers(window); //swap the buffer } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012, Steinwurf ApS // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Steinwurf ApS nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <gtest/gtest.h> #include <sak/endian_buffer.hpp> #include <cstdlib> TEST(EndianBuffer, create_buffer) { const uint32_t size = 1024; std::vector<uint8_t> buffer; buffer.reserve(size); sak::endian_buffer endian_buffer(&buffer.front(), size); } template<class ValueType> void write_read_test() { const uint32_t elements = 1024; //no. of elements const uint32_t size = 1024*sizeof(ValueType); //size in bytes std::vector<uint8_t> buffer; buffer.reserve(size); sak::endian_buffer endian_buffer(&buffer.front(), size); uint8_t lowest_value = 0; uint8_t highest_value = std::numeric_limits<ValueType>::max(); for(uint32_t i = 0; i < elements; i++) { endian_buffer.write<ValueType>(highest_value); } for(uint32_t i = 0; i < elements; i++) { EXPECT_EQ(highest_value, endian_buffer.read<ValueType>()); } for(uint32_t i = 0; i < elements; i++) { endian_buffer.write<ValueType>(lowest_value); } for(uint32_t i = 0; i < elements; i++) { EXPECT_EQ(lowest_value, endian_buffer.read<ValueType>()); } std::vector<ValueType> values; values.reserve(elements); /* initialize random seed with the hardcoded seed */ srand(1337); for(uint32_t i = 0; i < elements; i++) { values[i] = rand() % (highest_value+1); endian_buffer.write<ValueType>(values[i]); } for(int32_t i = elements-1; i >= 0; --i) { std::cout << i << std::endl; EXPECT_EQ(values[i], endian_buffer.read<ValueType>()); } } TEST(EndianBuffer, read_write_u8) { write_read_test<uint8_t>(); } TEST(EndianBuffer, read_write_u16) { write_read_test<uint16_t>(); } TEST(EndianBuffer, read_write_u32) { write_read_test<uint32_t>(); } TEST(EndianBuffer, read_write_u64) { write_read_test<uint64_t>(); } TEST(EndianBuffer, various_read_write) { const uint32_t elements = 1024; const uint32_t size = 1024*sizeof(uint64_t); std::vector<uint8_t> buffer; buffer.reserve(size); sak::endian_buffer endian_buffer(&buffer.front(), size); std::vector<uint64_t> values(elements); /* initialize random with the hardcoded seed */ srand(1337); for(uint32_t i = 0; i < elements; i++) { switch(i % 4) { case 0: values[i] = rand() % std::numeric_limits<uint8_t>::max(); endian_buffer.write<uint8_t>(values[i]); break; case 1: values[i] = rand() % std::numeric_limits<uint16_t>::max(); endian_buffer.write<uint16_t>(values[i]); break; case 2: values[i] = rand() % std::numeric_limits<uint32_t>::max(); endian_buffer.write<uint32_t>(values[i]); break; case 3: values[i] = rand() % std::numeric_limits<uint64_t>::max(); endian_buffer.write<uint64_t>(values[i]); break; } } for(uint32_t i = elements-1; i > 0; i--) { switch(i % 4) { case 0: EXPECT_EQ(values[i], endian_buffer.read<uint8_t>()); break; case 1: EXPECT_EQ(values[i], endian_buffer.read<uint16_t>()); break; case 2: EXPECT_EQ(values[i], endian_buffer.read<uint32_t>()); break; case 3: EXPECT_EQ(values[i], endian_buffer.read<uint64_t>()); break; } } } <commit_msg>added hybrid version of the test, now we test with both pseudorandom and random data<commit_after>// Copyright (c) 2012, Steinwurf ApS // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Steinwurf ApS nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <gtest/gtest.h> #include <sak/endian_buffer.hpp> #include <cstdlib> TEST(EndianBuffer, create_buffer) { const uint32_t size = 1024; std::vector<uint8_t> buffer; buffer.reserve(size); sak::endian_buffer endian_buffer(&buffer.front(), size); } /// Test helper functions template<class ValueType> void write_read_test() { const uint32_t elements = 1024; ///no. of elements const uint32_t size = 1024*sizeof(ValueType); ///size in bytes std::vector<uint8_t> buffer; buffer.reserve(size); sak::endian_buffer endian_buffer(&buffer.front(), size); uint8_t lowest_value = 0; uint8_t highest_value = std::numeric_limits<ValueType>::max(); for(uint32_t i = 0; i < elements; i++) { endian_buffer.write<ValueType>(highest_value); } for(uint32_t i = 0; i < elements; i++) { EXPECT_EQ(highest_value, endian_buffer.read<ValueType>()); } for(uint32_t i = 0; i < elements; i++) { endian_buffer.write<ValueType>(lowest_value); } for(uint32_t i = 0; i < elements; i++) { EXPECT_EQ(lowest_value, endian_buffer.read<ValueType>()); } } template<class ValueType> void random_write_read_test(bool pseudorandom) { const uint32_t elements = 1024; /// no. of elements const uint32_t size = 1024*sizeof(ValueType); /// size in bytes std::vector<uint8_t> buffer; buffer.reserve(size); sak::endian_buffer endian_buffer(&buffer.front(), size); uint8_t highest_value = std::numeric_limits<ValueType>::max(); std::vector<ValueType> values; values.reserve(elements); if(pseudorandom) { srand(1337); } else { srand(static_cast<uint32_t>(time(0))); } for(uint32_t i = 0; i < elements; i++) { values[i] = rand() % (highest_value+1); endian_buffer.write<ValueType>(values[i]); } for(int32_t i = elements-1; i >= 0; --i) { std::cout << i << std::endl; EXPECT_EQ(values[i], endian_buffer.read<ValueType>()); } } void various_write_read_test(bool pseudorandom) { const uint32_t elements = 1024; const uint32_t size = 1024*sizeof(uint64_t); std::vector<uint8_t> buffer; buffer.reserve(size); sak::endian_buffer endian_buffer(&buffer.front(), size); std::vector<uint64_t> values(elements); if(pseudorandom) { srand(1337); } else { srand(static_cast<uint32_t>(time(0))); } for(uint32_t i = 0; i < elements; i++) { switch(i % 4) { case 0: values[i] = rand() % std::numeric_limits<uint8_t>::max(); endian_buffer.write<uint8_t>(values[i]); break; case 1: values[i] = rand() % std::numeric_limits<uint16_t>::max(); endian_buffer.write<uint16_t>(values[i]); break; case 2: values[i] = rand() % std::numeric_limits<uint32_t>::max(); endian_buffer.write<uint32_t>(values[i]); break; case 3: values[i] = rand() % std::numeric_limits<uint64_t>::max(); endian_buffer.write<uint64_t>(values[i]); break; } } for(uint32_t i = elements-1; i > 0; i--) { switch(i % 4) { case 0: EXPECT_EQ(values[i], endian_buffer.read<uint8_t>()); break; case 1: EXPECT_EQ(values[i], endian_buffer.read<uint16_t>()); break; case 2: EXPECT_EQ(values[i], endian_buffer.read<uint32_t>()); break; case 3: EXPECT_EQ(values[i], endian_buffer.read<uint64_t>()); break; } } } /// Write read tests TEST(EndianBuffer, read_write_u8) { write_read_test<uint8_t>(); } TEST(EndianBuffer, read_write_u16) { write_read_test<uint16_t>(); } TEST(EndianBuffer, read_write_u32) { write_read_test<uint32_t>(); } TEST(EndianBuffer, read_write_u64) { write_read_test<uint64_t>(); } /// Pseudorandom write read tests TEST(EndianBuffer, pseudorandom_read_write_u8) { random_write_read_test<uint8_t>(true); } TEST(EndianBuffer, pseudorandom_read_write_u16) { random_write_read_test<uint16_t>(true); } TEST(EndianBuffer, pseudorandom_read_write_u32) { random_write_read_test<uint32_t>(true); } TEST(EndianBuffer, pseudorandom_read_write_u64) { random_write_read_test<uint64_t>(true); } /// Random write read tests TEST(EndianBuffer, random_read_write_u8) { random_write_read_test<uint8_t>(false); } TEST(EndianBuffer, random_read_write_u16) { random_write_read_test<uint16_t>(false); } TEST(EndianBuffer, random_read_write_u32) { random_write_read_test<uint32_t>(false); } TEST(EndianBuffer, random_read_write_u64) { random_write_read_test<uint64_t>(false); } /// Various read writes TEST(EndianBuffer, pseudorandom_various_read_write) { various_write_read_test(true); } TEST(EndianBuffer, random_various_read_write) { various_write_read_test(false); } <|endoftext|>
<commit_before>#include <mandelbrot.h> #include <static_image.h> #include <math.h> #include <string.h> #include <stdio.h> #include <sys/time.h> int main(int argc, char **argv) { Image<int> output(100, 30); const char *code = " .:-~*={}&%#@"; const int iters = strlen(code) - 1; struct timeval t1, t2; gettimeofday(&t1, NULL); // Compute 100 different julia sets for (float t = 0; t < 100; t++) { float fx = cos(t/10.0f), fy = sin(t/10.0f); mandelbrot(-2.0f, 2.0f, -1.4f, 1.4f, fx, fy, iters, output.width(), output.height(), output); } gettimeofday(&t2, NULL); char buf[4096]; char *buf_ptr = buf; for (int y = 0; y < output.height(); y++) { for (int x = 0; x < output.width(); x++) { *buf_ptr++ = code[output(x, y)]; } *buf_ptr++ = '\n'; } *buf_ptr++ = 0; printf(buf); fflush(stdout); int64_t time = (t2.tv_usec - t1.tv_usec) / 1000; time += (t2.tv_sec - t1.tv_sec) * 1000; printf("Success (%d ms)!\n", time); return 0; } <commit_msg>Fix a couple warnings in test code. Both were unlikely to cause visible bugs, but it is a bit cleaner now.<commit_after>#include <mandelbrot.h> #include <static_image.h> #include <math.h> #include <string.h> #include <stdio.h> #include <sys/time.h> int main(int argc, char **argv) { Image<int> output(100, 30); const char *code = " .:-~*={}&%#@"; const int iters = strlen(code) - 1; struct timeval t1, t2; gettimeofday(&t1, NULL); // Compute 100 different julia sets for (float t = 0; t < 100; t++) { float fx = cos(t/10.0f), fy = sin(t/10.0f); mandelbrot(-2.0f, 2.0f, -1.4f, 1.4f, fx, fy, iters, output.width(), output.height(), output); } gettimeofday(&t2, NULL); char buf[4096]; char *buf_ptr = buf; for (int y = 0; y < output.height(); y++) { for (int x = 0; x < output.width(); x++) { *buf_ptr++ = code[output(x, y)]; } *buf_ptr++ = '\n'; } *buf_ptr++ = 0; printf("%s", buf); fflush(stdout); int64_t time = (t2.tv_usec - t1.tv_usec) / 1000; time += (t2.tv_sec - t1.tv_sec) * 1000; printf("Success (%lld ms)!\n", time); return 0; } <|endoftext|>
<commit_before>#include "nan.h" #include "buffer_offset_index.h" #include "point.h" using namespace v8; static Nan::Persistent<String> row_string; static Nan::Persistent<String> column_string; static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) { Local<Object> object; if (!maybe_object.ToLocal(&object)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_string))); Local<Integer> js_row; if (!maybe_row.ToLocal(&js_row)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_string))); Local<Integer> js_column; if (!maybe_column.ToLocal(&js_column)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } unsigned row, column; if (isfinite(js_row->NumberValue())) { row = static_cast<unsigned>(js_row->Int32Value()); } else { row = UINT_MAX; } if (isfinite(js_column->NumberValue())) { column = static_cast<unsigned>(js_column->Int32Value()); } else { column = UINT_MAX; } return Nan::Just(Point {row, column}); } class PointWrapper : public Nan::ObjectWrap { public: static void Init() { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Point").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(row_string), GetRow); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(column_string), GetColumn); constructor.Reset(constructor_template->GetFunction()); } static Local<Value> FromPoint(Point point) { Local<Object> result; if (Nan::New(constructor)->NewInstance(Nan::GetCurrentContext()).ToLocal(&result)) { (new PointWrapper(point))->Wrap(result); return result; } else { return Nan::Null(); } } private: PointWrapper(Point point) : point{point} {} static void New(const Nan::FunctionCallbackInfo<Value> &info) {} static void GetRow(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.row)); } static void GetColumn(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.column)); } static Nan::Persistent<v8::Function> constructor; Point point; }; Nan::Persistent<v8::Function> PointWrapper::constructor; class BufferOffsetIndexWrapper : public Nan::ObjectWrap { public: static void Init(Local<Object> exports, Local<Object> module) { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("BufferOffsetIndex").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); const auto &prototype_template = constructor_template->PrototypeTemplate(); prototype_template->Set(Nan::New<String>("splice").ToLocalChecked(), Nan::New<FunctionTemplate>(Splice)); prototype_template->Set(Nan::New<String>("positionForCharacterIndex").ToLocalChecked(), Nan::New<FunctionTemplate>(PositionForCharacterIndex)); prototype_template->Set(Nan::New<String>("characterIndexForPosition").ToLocalChecked(), Nan::New<FunctionTemplate>(CharacterIndexForPosition)); module->Set(Nan::New("exports").ToLocalChecked(), constructor_template->GetFunction()); } private: static void New(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndexWrapper *buffer_offset_index = new BufferOffsetIndexWrapper(); buffer_offset_index->Wrap(info.This()); } static void Splice(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndex &buffer_offset_index = Nan::ObjectWrap::Unwrap<BufferOffsetIndexWrapper>(info.This())->buffer_offset_index; auto start_row = info[0].As<Uint32>()->Value(); auto deleted_lines_count = info[1].As<Uint32>()->Value(); auto js_new_line_lengths = info[2].As<Array>(); auto new_line_lengths = std::vector<unsigned>(js_new_line_lengths->Length()); for (size_t i = 0; i < new_line_lengths.size(); i++) { new_line_lengths[i] = js_new_line_lengths->Get(i).As<Uint32>()->Value(); } buffer_offset_index.Splice(start_row, deleted_lines_count, new_line_lengths); } static void CharacterIndexForPosition(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndex &buffer_offset_index = Nan::ObjectWrap::Unwrap<BufferOffsetIndexWrapper>(info.This())->buffer_offset_index; auto position = PointFromJS(Nan::To<Object>(info[0])); if (position.IsJust()) { auto result = buffer_offset_index.CharacterIndexForPosition(position.FromJust()); info.GetReturnValue().Set(Nan::New(result)); } } static void PositionForCharacterIndex(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndex &buffer_offset_index = Nan::ObjectWrap::Unwrap<BufferOffsetIndexWrapper>(info.This())->buffer_offset_index; auto character_index = Nan::To<unsigned>(info[0]); if (character_index.IsJust()) { auto result = buffer_offset_index.PositionForCharacterIndex(character_index.FromJust()); info.GetReturnValue().Set(PointWrapper::FromPoint(result)); } } BufferOffsetIndex buffer_offset_index; }; void Init(Local<Object> exports, Local<Object> module) { row_string.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked())); column_string.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked())); PointWrapper::Init(); BufferOffsetIndexWrapper::Init(exports, module); } NODE_MODULE(atom_buffer_offset_index, Init) <commit_msg>Fix gcc errors<commit_after>#include "nan.h" #include "buffer_offset_index.h" #include "point.h" using namespace v8; static Nan::Persistent<String> row_string; static Nan::Persistent<String> column_string; static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) { Local<Object> object; if (!maybe_object.ToLocal(&object)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_string))); Local<Integer> js_row; if (!maybe_row.ToLocal(&js_row)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_string))); Local<Integer> js_column; if (!maybe_column.ToLocal(&js_column)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } unsigned row, column; if (std::isfinite(js_row->NumberValue())) { row = static_cast<unsigned>(js_row->Int32Value()); } else { row = UINT_MAX; } if (std::isfinite(js_column->NumberValue())) { column = static_cast<unsigned>(js_column->Int32Value()); } else { column = UINT_MAX; } return Nan::Just(Point {row, column}); } class PointWrapper : public Nan::ObjectWrap { public: static void Init() { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Point").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(row_string), GetRow); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(column_string), GetColumn); constructor.Reset(constructor_template->GetFunction()); } static Local<Value> FromPoint(Point point) { Local<Object> result; if (Nan::New(constructor)->NewInstance(Nan::GetCurrentContext()).ToLocal(&result)) { (new PointWrapper(point))->Wrap(result); return result; } else { return Nan::Null(); } } private: PointWrapper(Point point) : point{point} {} static void New(const Nan::FunctionCallbackInfo<Value> &info) {} static void GetRow(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.row)); } static void GetColumn(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.column)); } static Nan::Persistent<v8::Function> constructor; Point point; }; Nan::Persistent<v8::Function> PointWrapper::constructor; class BufferOffsetIndexWrapper : public Nan::ObjectWrap { public: static void Init(Local<Object> exports, Local<Object> module) { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("BufferOffsetIndex").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); const auto &prototype_template = constructor_template->PrototypeTemplate(); prototype_template->Set(Nan::New<String>("splice").ToLocalChecked(), Nan::New<FunctionTemplate>(Splice)); prototype_template->Set(Nan::New<String>("positionForCharacterIndex").ToLocalChecked(), Nan::New<FunctionTemplate>(PositionForCharacterIndex)); prototype_template->Set(Nan::New<String>("characterIndexForPosition").ToLocalChecked(), Nan::New<FunctionTemplate>(CharacterIndexForPosition)); module->Set(Nan::New("exports").ToLocalChecked(), constructor_template->GetFunction()); } private: static void New(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndexWrapper *buffer_offset_index = new BufferOffsetIndexWrapper(); buffer_offset_index->Wrap(info.This()); } static void Splice(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndex &buffer_offset_index = Nan::ObjectWrap::Unwrap<BufferOffsetIndexWrapper>(info.This())->buffer_offset_index; auto start_row = info[0].As<Uint32>()->Value(); auto deleted_lines_count = info[1].As<Uint32>()->Value(); auto js_new_line_lengths = info[2].As<Array>(); auto new_line_lengths = std::vector<unsigned>(js_new_line_lengths->Length()); for (size_t i = 0; i < new_line_lengths.size(); i++) { new_line_lengths[i] = js_new_line_lengths->Get(i).As<Uint32>()->Value(); } buffer_offset_index.Splice(start_row, deleted_lines_count, new_line_lengths); } static void CharacterIndexForPosition(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndex &buffer_offset_index = Nan::ObjectWrap::Unwrap<BufferOffsetIndexWrapper>(info.This())->buffer_offset_index; auto position = PointFromJS(Nan::To<Object>(info[0])); if (position.IsJust()) { auto result = buffer_offset_index.CharacterIndexForPosition(position.FromJust()); info.GetReturnValue().Set(Nan::New(result)); } } static void PositionForCharacterIndex(const Nan::FunctionCallbackInfo<Value> &info) { BufferOffsetIndex &buffer_offset_index = Nan::ObjectWrap::Unwrap<BufferOffsetIndexWrapper>(info.This())->buffer_offset_index; auto character_index = Nan::To<unsigned>(info[0]); if (character_index.IsJust()) { auto result = buffer_offset_index.PositionForCharacterIndex(character_index.FromJust()); info.GetReturnValue().Set(PointWrapper::FromPoint(result)); } } BufferOffsetIndex buffer_offset_index; }; void Init(Local<Object> exports, Local<Object> module) { row_string.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked())); column_string.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked())); PointWrapper::Init(); BufferOffsetIndexWrapper::Init(exports, module); } NODE_MODULE(atom_buffer_offset_index, Init) <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskAuto.cpp */ #include "FlightTaskOffboard.hpp" #include <mathlib/mathlib.h> #include <float.h> using namespace matrix; bool FlightTaskOffboard::updateInitialize() { bool ret = FlightTask::updateInitialize(); _sub_triplet_setpoint.update(); // require a valid triplet ret = ret && _sub_triplet_setpoint.get().current.valid; // require valid position / velocity in xy return ret && PX4_ISFINITE(_position(0)) && PX4_ISFINITE(_position(1)) && PX4_ISFINITE(_velocity(0)) && PX4_ISFINITE(_velocity(1)); } bool FlightTaskOffboard::activate(vehicle_local_position_setpoint_s last_setpoint) { bool ret = FlightTask::activate(last_setpoint); _position_setpoint = _position; _velocity_setpoint.setZero(); _position_lock.setAll(NAN); return ret; } bool FlightTaskOffboard::update() { // reset setpoint for every loop _resetSetpoints(); if (!_sub_triplet_setpoint.get().current.valid) { _setDefaultConstraints(); _position_setpoint = _position; return false; } // Yaw / Yaw-speed if (_sub_triplet_setpoint.get().current.yaw_valid) { // yaw control required _yaw_setpoint = _sub_triplet_setpoint.get().current.yaw; if (_sub_triplet_setpoint.get().current.yawspeed_valid) { // yawspeed is used as feedforward _yawspeed_setpoint = _sub_triplet_setpoint.get().current.yawspeed; } } else if (_sub_triplet_setpoint.get().current.yawspeed_valid) { // only yawspeed required _yawspeed_setpoint = _sub_triplet_setpoint.get().current.yawspeed; // set yaw setpoint to NAN since not used _yaw_setpoint = NAN; } // Loiter if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_LOITER) { // loiter just means that the vehicle should keep position if (!PX4_ISFINITE(_position_lock(0))) { _position_setpoint = _position_lock = _position; } else { _position_setpoint = _position_lock; } // don't have to continue return true; } else { _position_lock.setAll(NAN); } // Takeoff if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_TAKEOFF) { // just do takeoff to default altitude if (!PX4_ISFINITE(_position_lock(0))) { _position_setpoint = _position_lock = _position; _position_setpoint(2) = _position_lock(2) = _position(2) - _param_mis_takeoff_alt.get(); } else { _position_setpoint = _position_lock; } // don't have to continue return true; } else { _position_lock.setAll(NAN); } // Land if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_LAND) { // land with landing speed, but keep position in xy if (!PX4_ISFINITE(_position_lock(0))) { _position_setpoint = _position_lock = _position; _position_setpoint(2) = _position_lock(2) = NAN; _velocity_setpoint(2) = _param_mpc_land_speed.get(); } else { _position_setpoint = _position_lock; _velocity_setpoint(2) = _param_mpc_land_speed.get(); } // don't have to continue return true; } else { _position_lock.setAll(NAN); } // IDLE if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_IDLE) { _position_setpoint.setNaN(); // Don't require any position/velocity setpoints _velocity_setpoint.setNaN(); _acceleration_setpoint = Vector3f(0.f, 0.f, 100.f); // High downwards acceleration to make sure there's no thrust return true; } // Possible inputs: // 1. position setpoint // 2. position setpoint + velocity setpoint (velocity used as feedforward) // 3. velocity setpoint // 4. acceleration setpoint -> this will be mapped to normalized thrust setpoint because acceleration is not supported const bool position_ctrl_xy = _sub_triplet_setpoint.get().current.position_valid && _sub_vehicle_local_position.get().xy_valid; const bool position_ctrl_z = _sub_triplet_setpoint.get().current.alt_valid && _sub_vehicle_local_position.get().z_valid; const bool velocity_ctrl_xy = _sub_triplet_setpoint.get().current.velocity_valid && _sub_vehicle_local_position.get().v_xy_valid; const bool velocity_ctrl_z = _sub_triplet_setpoint.get().current.velocity_valid && _sub_vehicle_local_position.get().v_z_valid; const bool feedforward_ctrl_xy = position_ctrl_xy && velocity_ctrl_xy; const bool feedforward_ctrl_z = position_ctrl_z && velocity_ctrl_z; const bool acceleration_ctrl = _sub_triplet_setpoint.get().current.acceleration_valid; // if nothing is valid in xy, then exit offboard if (!(position_ctrl_xy || velocity_ctrl_xy || acceleration_ctrl)) { return false; } // if nothing is valid in z, then exit offboard if (!(position_ctrl_z || velocity_ctrl_z || acceleration_ctrl)) { return false; } // XY-direction if (feedforward_ctrl_xy) { _position_setpoint(0) = _sub_triplet_setpoint.get().current.x; _position_setpoint(1) = _sub_triplet_setpoint.get().current.y; _velocity_setpoint(0) = _sub_triplet_setpoint.get().current.vx; _velocity_setpoint(1) = _sub_triplet_setpoint.get().current.vy; } else if (position_ctrl_xy) { _position_setpoint(0) = _sub_triplet_setpoint.get().current.x; _position_setpoint(1) = _sub_triplet_setpoint.get().current.y; } else if (velocity_ctrl_xy) { if (_sub_triplet_setpoint.get().current.velocity_frame == position_setpoint_s::VELOCITY_FRAME_LOCAL_NED) { // in local frame: don't require any transformation _velocity_setpoint(0) = _sub_triplet_setpoint.get().current.vx; _velocity_setpoint(1) = _sub_triplet_setpoint.get().current.vy; } else if (_sub_triplet_setpoint.get().current.velocity_frame == position_setpoint_s::VELOCITY_FRAME_BODY_NED) { // in body frame: need to transorm first // Note, this transformation is wrong because body-xy is not neccessarily on the same plane as locale-xy _velocity_setpoint(0) = cosf(_yaw) * _sub_triplet_setpoint.get().current.vx - sinf( _yaw) * _sub_triplet_setpoint.get().current.vy; _velocity_setpoint(1) = sinf(_yaw) * _sub_triplet_setpoint.get().current.vx + cosf( _yaw) * _sub_triplet_setpoint.get().current.vy; } else { // no valid frame return false; } } // Z-direction if (feedforward_ctrl_z) { _position_setpoint(2) = _sub_triplet_setpoint.get().current.z; _velocity_setpoint(2) = _sub_triplet_setpoint.get().current.vz; } else if (position_ctrl_z) { _position_setpoint(2) = _sub_triplet_setpoint.get().current.z; } else if (velocity_ctrl_z) { _velocity_setpoint(2) = _sub_triplet_setpoint.get().current.vz; } // Acceleration // Note: this is not supported yet and will be mapped to normalized thrust directly. if (_sub_triplet_setpoint.get().current.acceleration_valid) { _acceleration_setpoint(0) = _sub_triplet_setpoint.get().current.a_x; _acceleration_setpoint(1) = _sub_triplet_setpoint.get().current.a_y; _acceleration_setpoint(2) = _sub_triplet_setpoint.get().current.a_z; } // use default conditions of upwards position or velocity to take off _constraints.want_takeoff = _checkTakeoff(); return true; } <commit_msg>FlightTaskOffboard: fix header comment<commit_after>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskOffboard.cpp */ #include "FlightTaskOffboard.hpp" #include <mathlib/mathlib.h> #include <float.h> using namespace matrix; bool FlightTaskOffboard::updateInitialize() { bool ret = FlightTask::updateInitialize(); _sub_triplet_setpoint.update(); // require a valid triplet ret = ret && _sub_triplet_setpoint.get().current.valid; // require valid position / velocity in xy return ret && PX4_ISFINITE(_position(0)) && PX4_ISFINITE(_position(1)) && PX4_ISFINITE(_velocity(0)) && PX4_ISFINITE(_velocity(1)); } bool FlightTaskOffboard::activate(vehicle_local_position_setpoint_s last_setpoint) { bool ret = FlightTask::activate(last_setpoint); _position_setpoint = _position; _velocity_setpoint.setZero(); _position_lock.setAll(NAN); return ret; } bool FlightTaskOffboard::update() { // reset setpoint for every loop _resetSetpoints(); if (!_sub_triplet_setpoint.get().current.valid) { _setDefaultConstraints(); _position_setpoint = _position; return false; } // Yaw / Yaw-speed if (_sub_triplet_setpoint.get().current.yaw_valid) { // yaw control required _yaw_setpoint = _sub_triplet_setpoint.get().current.yaw; if (_sub_triplet_setpoint.get().current.yawspeed_valid) { // yawspeed is used as feedforward _yawspeed_setpoint = _sub_triplet_setpoint.get().current.yawspeed; } } else if (_sub_triplet_setpoint.get().current.yawspeed_valid) { // only yawspeed required _yawspeed_setpoint = _sub_triplet_setpoint.get().current.yawspeed; // set yaw setpoint to NAN since not used _yaw_setpoint = NAN; } // Loiter if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_LOITER) { // loiter just means that the vehicle should keep position if (!PX4_ISFINITE(_position_lock(0))) { _position_setpoint = _position_lock = _position; } else { _position_setpoint = _position_lock; } // don't have to continue return true; } else { _position_lock.setAll(NAN); } // Takeoff if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_TAKEOFF) { // just do takeoff to default altitude if (!PX4_ISFINITE(_position_lock(0))) { _position_setpoint = _position_lock = _position; _position_setpoint(2) = _position_lock(2) = _position(2) - _param_mis_takeoff_alt.get(); } else { _position_setpoint = _position_lock; } // don't have to continue return true; } else { _position_lock.setAll(NAN); } // Land if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_LAND) { // land with landing speed, but keep position in xy if (!PX4_ISFINITE(_position_lock(0))) { _position_setpoint = _position_lock = _position; _position_setpoint(2) = _position_lock(2) = NAN; _velocity_setpoint(2) = _param_mpc_land_speed.get(); } else { _position_setpoint = _position_lock; _velocity_setpoint(2) = _param_mpc_land_speed.get(); } // don't have to continue return true; } else { _position_lock.setAll(NAN); } // IDLE if (_sub_triplet_setpoint.get().current.type == position_setpoint_s::SETPOINT_TYPE_IDLE) { _position_setpoint.setNaN(); // Don't require any position/velocity setpoints _velocity_setpoint.setNaN(); _acceleration_setpoint = Vector3f(0.f, 0.f, 100.f); // High downwards acceleration to make sure there's no thrust return true; } // Possible inputs: // 1. position setpoint // 2. position setpoint + velocity setpoint (velocity used as feedforward) // 3. velocity setpoint // 4. acceleration setpoint -> this will be mapped to normalized thrust setpoint because acceleration is not supported const bool position_ctrl_xy = _sub_triplet_setpoint.get().current.position_valid && _sub_vehicle_local_position.get().xy_valid; const bool position_ctrl_z = _sub_triplet_setpoint.get().current.alt_valid && _sub_vehicle_local_position.get().z_valid; const bool velocity_ctrl_xy = _sub_triplet_setpoint.get().current.velocity_valid && _sub_vehicle_local_position.get().v_xy_valid; const bool velocity_ctrl_z = _sub_triplet_setpoint.get().current.velocity_valid && _sub_vehicle_local_position.get().v_z_valid; const bool feedforward_ctrl_xy = position_ctrl_xy && velocity_ctrl_xy; const bool feedforward_ctrl_z = position_ctrl_z && velocity_ctrl_z; const bool acceleration_ctrl = _sub_triplet_setpoint.get().current.acceleration_valid; // if nothing is valid in xy, then exit offboard if (!(position_ctrl_xy || velocity_ctrl_xy || acceleration_ctrl)) { return false; } // if nothing is valid in z, then exit offboard if (!(position_ctrl_z || velocity_ctrl_z || acceleration_ctrl)) { return false; } // XY-direction if (feedforward_ctrl_xy) { _position_setpoint(0) = _sub_triplet_setpoint.get().current.x; _position_setpoint(1) = _sub_triplet_setpoint.get().current.y; _velocity_setpoint(0) = _sub_triplet_setpoint.get().current.vx; _velocity_setpoint(1) = _sub_triplet_setpoint.get().current.vy; } else if (position_ctrl_xy) { _position_setpoint(0) = _sub_triplet_setpoint.get().current.x; _position_setpoint(1) = _sub_triplet_setpoint.get().current.y; } else if (velocity_ctrl_xy) { if (_sub_triplet_setpoint.get().current.velocity_frame == position_setpoint_s::VELOCITY_FRAME_LOCAL_NED) { // in local frame: don't require any transformation _velocity_setpoint(0) = _sub_triplet_setpoint.get().current.vx; _velocity_setpoint(1) = _sub_triplet_setpoint.get().current.vy; } else if (_sub_triplet_setpoint.get().current.velocity_frame == position_setpoint_s::VELOCITY_FRAME_BODY_NED) { // in body frame: need to transorm first // Note, this transformation is wrong because body-xy is not neccessarily on the same plane as locale-xy _velocity_setpoint(0) = cosf(_yaw) * _sub_triplet_setpoint.get().current.vx - sinf( _yaw) * _sub_triplet_setpoint.get().current.vy; _velocity_setpoint(1) = sinf(_yaw) * _sub_triplet_setpoint.get().current.vx + cosf( _yaw) * _sub_triplet_setpoint.get().current.vy; } else { // no valid frame return false; } } // Z-direction if (feedforward_ctrl_z) { _position_setpoint(2) = _sub_triplet_setpoint.get().current.z; _velocity_setpoint(2) = _sub_triplet_setpoint.get().current.vz; } else if (position_ctrl_z) { _position_setpoint(2) = _sub_triplet_setpoint.get().current.z; } else if (velocity_ctrl_z) { _velocity_setpoint(2) = _sub_triplet_setpoint.get().current.vz; } // Acceleration // Note: this is not supported yet and will be mapped to normalized thrust directly. if (_sub_triplet_setpoint.get().current.acceleration_valid) { _acceleration_setpoint(0) = _sub_triplet_setpoint.get().current.a_x; _acceleration_setpoint(1) = _sub_triplet_setpoint.get().current.a_y; _acceleration_setpoint(2) = _sub_triplet_setpoint.get().current.a_z; } // use default conditions of upwards position or velocity to take off _constraints.want_takeoff = _checkTakeoff(); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Paul Pluzhnikov // // Allow dynamic symbol lookup in the kernel VDSO page. // // VDSOSupport -- a class representing kernel VDSO (if present). // #include "base/vdso_support.h" #ifdef HAVE_VDSO_SUPPORT // defined in vdso_support.h #include <fcntl.h> #include <stddef.h> // for ptrdiff_t #include "base/atomicops.h" // for MemoryBarrier #include "base/linux_syscall_support.h" #include "base/logging.h" #include "base/dynamic_annotations.h" #include "base/basictypes.h" // for COMPILE_ASSERT using base::subtle::MemoryBarrier; #ifndef AT_SYSINFO_EHDR #define AT_SYSINFO_EHDR 33 #endif namespace base { const void *VDSOSupport::vdso_base_ = ElfMemImage::kInvalidBase; VDSOSupport::VDSOSupport() // If vdso_base_ is still set to kInvalidBase, we got here // before VDSOSupport::Init has been called. Call it now. : image_(vdso_base_ == ElfMemImage::kInvalidBase ? Init() : vdso_base_) { } // NOTE: we can't use GoogleOnceInit() below, because we can be // called by tcmalloc, and none of the *once* stuff may be functional yet. // // In addition, we hope that the VDSOSupportHelper constructor // causes this code to run before there are any threads, and before // InitGoogle() has executed any chroot or setuid calls. // // Finally, even if there is a race here, it is harmless, because // the operation should be idempotent. const void *VDSOSupport::Init() { if (vdso_base_ == ElfMemImage::kInvalidBase) { // Valgrind zaps AT_SYSINFO_EHDR and friends from the auxv[] // on stack, and so glibc works as if VDSO was not present. // But going directly to kernel via /proc/self/auxv below bypasses // Valgrind zapping. So we check for Valgrind separately. if (RunningOnValgrind()) { vdso_base_ = NULL; return NULL; } int fd = open("/proc/self/auxv", O_RDONLY); if (fd == -1) { // Kernel too old to have a VDSO. vdso_base_ = NULL; return NULL; } ElfW(auxv_t) aux; while (read(fd, &aux, sizeof(aux)) == sizeof(aux)) { if (aux.a_type == AT_SYSINFO_EHDR) { COMPILE_ASSERT(sizeof(vdso_base_) == sizeof(aux.a_un.a_val), unexpected_sizeof_pointer_NE_sizeof_a_val); vdso_base_ = reinterpret_cast<void *>(aux.a_un.a_val); break; } } close(fd); if (vdso_base_ == ElfMemImage::kInvalidBase) { // Didn't find AT_SYSINFO_EHDR in auxv[]. vdso_base_ = NULL; } } return vdso_base_; } const void *VDSOSupport::SetBase(const void *base) { CHECK(base != ElfMemImage::kInvalidBase); const void *old_base = vdso_base_; vdso_base_ = base; image_.Init(base); return old_base; } bool VDSOSupport::LookupSymbol(const char *name, const char *version, int type, SymbolInfo *info) const { return image_.LookupSymbol(name, version, type, info); } bool VDSOSupport::LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const { return image_.LookupSymbolByAddress(address, info_out); } // We need to make sure VDSOSupport::Init() is called before // the main() runs, since it might do something like setuid or // chroot. If VDSOSupport // is used in any global constructor, this will happen, since // VDSOSupport's constructor calls Init. But if not, we need to // ensure it here, with a global constructor of our own. This // is an allowed exception to the normal rule against non-trivial // global constructors. static class VDSOInitHelper { public: VDSOInitHelper() { VDSOSupport::Init(); } } vdso_init_helper; } #endif // HAVE_VDSO_SUPPORT <commit_msg>Remove not needed header in vdso_support.cc.<commit_after>// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --- // Author: Paul Pluzhnikov // // Allow dynamic symbol lookup in the kernel VDSO page. // // VDSOSupport -- a class representing kernel VDSO (if present). // #include "base/vdso_support.h" #ifdef HAVE_VDSO_SUPPORT // defined in vdso_support.h #include <fcntl.h> #include <stddef.h> // for ptrdiff_t #include "base/atomicops.h" // for MemoryBarrier #include "base/logging.h" #include "base/dynamic_annotations.h" #include "base/basictypes.h" // for COMPILE_ASSERT using base::subtle::MemoryBarrier; #ifndef AT_SYSINFO_EHDR #define AT_SYSINFO_EHDR 33 #endif namespace base { const void *VDSOSupport::vdso_base_ = ElfMemImage::kInvalidBase; VDSOSupport::VDSOSupport() // If vdso_base_ is still set to kInvalidBase, we got here // before VDSOSupport::Init has been called. Call it now. : image_(vdso_base_ == ElfMemImage::kInvalidBase ? Init() : vdso_base_) { } // NOTE: we can't use GoogleOnceInit() below, because we can be // called by tcmalloc, and none of the *once* stuff may be functional yet. // // In addition, we hope that the VDSOSupportHelper constructor // causes this code to run before there are any threads, and before // InitGoogle() has executed any chroot or setuid calls. // // Finally, even if there is a race here, it is harmless, because // the operation should be idempotent. const void *VDSOSupport::Init() { if (vdso_base_ == ElfMemImage::kInvalidBase) { // Valgrind zaps AT_SYSINFO_EHDR and friends from the auxv[] // on stack, and so glibc works as if VDSO was not present. // But going directly to kernel via /proc/self/auxv below bypasses // Valgrind zapping. So we check for Valgrind separately. if (RunningOnValgrind()) { vdso_base_ = NULL; return NULL; } int fd = open("/proc/self/auxv", O_RDONLY); if (fd == -1) { // Kernel too old to have a VDSO. vdso_base_ = NULL; return NULL; } ElfW(auxv_t) aux; while (read(fd, &aux, sizeof(aux)) == sizeof(aux)) { if (aux.a_type == AT_SYSINFO_EHDR) { COMPILE_ASSERT(sizeof(vdso_base_) == sizeof(aux.a_un.a_val), unexpected_sizeof_pointer_NE_sizeof_a_val); vdso_base_ = reinterpret_cast<void *>(aux.a_un.a_val); break; } } close(fd); if (vdso_base_ == ElfMemImage::kInvalidBase) { // Didn't find AT_SYSINFO_EHDR in auxv[]. vdso_base_ = NULL; } } return vdso_base_; } const void *VDSOSupport::SetBase(const void *base) { CHECK(base != ElfMemImage::kInvalidBase); const void *old_base = vdso_base_; vdso_base_ = base; image_.Init(base); return old_base; } bool VDSOSupport::LookupSymbol(const char *name, const char *version, int type, SymbolInfo *info) const { return image_.LookupSymbol(name, version, type, info); } bool VDSOSupport::LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const { return image_.LookupSymbolByAddress(address, info_out); } // We need to make sure VDSOSupport::Init() is called before // the main() runs, since it might do something like setuid or // chroot. If VDSOSupport // is used in any global constructor, this will happen, since // VDSOSupport's constructor calls Init. But if not, we need to // ensure it here, with a global constructor of our own. This // is an allowed exception to the normal rule against non-trivial // global constructors. static class VDSOInitHelper { public: VDSOInitHelper() { VDSOSupport::Init(); } } vdso_init_helper; } #endif // HAVE_VDSO_SUPPORT <|endoftext|>
<commit_before>#ifndef COMPASS_RT_X86_GNU_CPUID_H_ #include "detail/ct/detect_compiler.hpp" #ifdef COMPASS_CT_COMP_GCC #define COMPASS_RT_X86_GNU_CPUID_H_ #include "detail/tags.hpp" #include "detail/definitions.hpp" #include "detail/rt/x86/cpuid_common.hpp" #include <array> #include <cstdint> namespace compass { namespace runtime { static std::array<std::uint32_t,4> cpuid(std::uint32_t level, std::uint32_t in_eax = 0, std::uint32_t in_ebx = 0, std::uint32_t in_ecx = 0, std::uint32_t in_edx = 0){ std::array<std::uint32_t,4> regs = {in_eax,in_ebx,in_ecx,in_edx}; int cpuid_rvalue = __get_cpuid(level, &regs[ct::eax], &regs[ct::ebx], &regs[ct::ecx], &regs[ct::edx] ); if(cpuid_rvalue < 1){ return {0,0,0,0}; } return regs; } }; }; #endif /* COMPASS_CT_COMP_GCC */ #endif /* COMPASS_CT_GNU_IMPL_H_ */ <commit_msg>changed used function (needs to be propagated to other compilers)<commit_after>#ifndef COMPASS_RT_X86_GNU_CPUID_H_ #include "detail/ct/detect_compiler.hpp" #ifdef COMPASS_CT_COMP_GCC #define COMPASS_RT_X86_GNU_CPUID_H_ #include "detail/tags.hpp" #include "detail/definitions.hpp" #include "detail/rt/x86/cpuid_common.hpp" #include <array> #include <cstdint> namespace compass { namespace runtime { static std::array<std::uint32_t,4> cpuid(std::uint32_t in_eax = 0, std::uint32_t in_ebx = 0, std::uint32_t in_ecx = 0, std::uint32_t in_edx = 0){ std::array<std::uint32_t,4> regs = {0,0,0,0}; int cpuid_rvalue = __get_cpuid_count(in_eax, in_ecx, &regs[ct::eax], &regs[ct::ebx], &regs[ct::ecx], &regs[ct::edx] ); if(cpuid_rvalue < 1){ return {0,0,0,0}; } return regs; } }; }; #endif /* COMPASS_CT_COMP_GCC */ #endif /* COMPASS_CT_GNU_IMPL_H_ */ <|endoftext|>
<commit_before>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Base header file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <cstdio> XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) #include "xercesc/util/PlatformUtils.hpp" #include "xercesc/parsers/XercesDOMParser.hpp" #include "xalanc/PlatformSupport/XalanMemoryManagerDefault.hpp" #include "xalanc/XercesParserLiaison/XercesParserLiaison.hpp" #include "xalanc/XercesParserLiaison/XercesDOMSupport.hpp" #include "xalanc/XalanTransformer/XalanTransformer.hpp" #include "xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp" // HARNESS HEADERS... #include "xalanc/Harness/XalanFileUtility.hpp" #include "xalanc/Harness/XalanDiagnosticMemoryManager.hpp" #include "xalanc/Harness/XalanXMLFileReporter.hpp" //#define XALAN_VQ_SPECIAL_TRACE #if defined(XALAN_VQ_SPECIAL_TRACE) #include "C:/Program Files/Rational/Quantify/pure.h" #endif // Just hoist everything... XALAN_CPP_NAMESPACE_USE // This is here for memory leak testing. #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif XALAN_USING_XERCES(MemoryManager) void setHelp(XalanFileUtility& h) { h.args.getHelpStream() << endl << "conf dir [-sub -out -gold -source (XST | XPL | DOM)]" << endl << endl << "dir (base directory for testcases)" << endl << "-sub dir (specific directory)" << endl << "-out dir (base directory for output)" << endl << "-gold dir (base directory for gold files)" << endl << "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)" << endl; } static const char* const excludeStylesheets[] = { // "output22.xsl", // Excluded because it outputs EBCDIC 0 }; inline bool checkForExclusion( const XalanDOMString& currentFile, MemoryManager& theMemoryManager) { for (size_t i = 0; excludeStylesheets[i] != 0; ++i) { if (currentFile == XalanDOMString(excludeStylesheets[i], theMemoryManager)) { return true; } } return false; } int parseWithTransformer( int sourceType, XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { const XalanParsedSource* parsedSource = 0; MemoryManagerType& mgr = h.getMemoryManager(); int theResult = 0; // Parse the XML source accordingly. // if (sourceType != 0 ) { theResult = xalan.parseSource(xmlInput, parsedSource, true); h.data.xmlFormat = XalanDOMString("XercesParserLiasion", mgr); } else { theResult = xalan.parseSource(xmlInput, parsedSource, false); h.data.xmlFormat = XalanDOMString("XalanSourceTree", mgr); } // If the source was parsed correctly then perform the transform else report the failure. // if (parsedSource == 0) { // Report the failure and be sure to increment fail count. // cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString tmp("Failed to parse source document. ", mgr); tmp.append(xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, tmp ); } else { theResult = xalan.transform(*parsedSource, styleSheet, output); xalan.destroyParsedSource(parsedSource); } return theResult; } int parseWithXerces( XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { XALAN_USING_XERCES(XercesDOMParser) XALAN_USING_XERCES(DOMDocument) MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); h.data.xmlFormat = XalanDOMString("Xerces_DOM", mgr); XercesDOMParser theParser; theParser.setDoValidation(true); theParser.setDoNamespaces(true); theParser.parse(xmlInput); DOMDocument* const theDOM = theParser.getDocument(); theDOM->normalize(); XercesDOMSupport theDOMSupport(mgr); XercesParserLiaison theParserLiaison(mgr); int theResult = 0; try { const XercesDOMWrapperParsedSource parsedSource( theDOM, theParserLiaison, theDOMSupport, XalanDOMString(xmlInput.getSystemId(), mgr), mgr); theResult = xalan.transform(parsedSource, styleSheet, output); } catch(...) { // Report the failure and be sure to increment fail count. // cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString resultString("Failed to parse source document. ", mgr); resultString.append( xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, resultString); } return theResult; } int runTests( int argc, char* argv[], MemoryManager& theMemoryManager) { int theResult = 0; try { XalanFileUtility h(theMemoryManager); // Set the program help string, then get the command line parameters. // setHelp(h); if (h.getParams(argc, argv, "CONF-RESULTS") == true) { XalanTransformer xalan(theMemoryManager); // Get drive designation for final analysis and generate Unique name for results log. // XalanDOMString drive(theMemoryManager); // This is used to get stylesheet for final analysis h.getDrive(drive); const XalanDOMString resultFilePrefix("conf", theMemoryManager); // This & UniqRunid used for log file name. XalanDOMString UniqRunid(theMemoryManager); h.generateUniqRunid(UniqRunid); XalanDOMString resultsFile(drive, theMemoryManager); resultsFile += h.args.output; resultsFile += resultFilePrefix; resultsFile += UniqRunid; resultsFile += XalanFileUtility::s_xmlSuffix; // Open results log, and do some initialization of result data. // XalanXMLFileReporter logFile(theMemoryManager, resultsFile); logFile.logTestFileInit("Conformance Testing:"); h.data.xmlFormat = XalanDOMString("NotSet", theMemoryManager); // Get the list of Directories that are below conf and iterate through them // // Flag indicates directory found. Used in conjunction with -sub cmd-line arg. bool foundDir = false; typedef XalanFileUtility::FileNameVectorType FileNameVectorType; FileNameVectorType dirs(theMemoryManager); h.getDirectoryNames(h.args.base, dirs); int theResult = 0; for(FileNameVectorType::size_type j = 0; j < dirs.size() && theResult == 0; ++j) { // Skip all but the specified directory if the -sub cmd-line option was used. // const XalanDOMString& currentDir = dirs[j]; if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true) { // Check that output directory is there. // XalanDOMString theOutputDir(theMemoryManager); theOutputDir = h.args.output; theOutputDir += currentDir; h.checkAndCreateDir(theOutputDir); // Indicate that directory was processed and get test files from the directory // foundDir = true; FileNameVectorType files(theMemoryManager); h.getTestFileNames(h.args.base, currentDir, true, files); // Log directory in results log and process it's files. // logFile.logTestCaseInit(currentDir); for(FileNameVectorType::size_type i = 0; i < files.size(); i++) { XalanXMLFileReporter::Hashtable attrs(theMemoryManager); const XalanDOMString& currentFile = files[i]; if (checkForExclusion(currentFile, theMemoryManager)) continue; h.data.testOrFile = currentFile; XalanDOMString theXSLFile( h.args.base, theMemoryManager); theXSLFile += currentDir; theXSLFile += XalanFileUtility::s_pathSep; theXSLFile += currentFile; // Check and see if the .xml file exists. If not skip this .xsl file and continue. bool fileStatus = true; XalanDOMString theXMLFile(theMemoryManager); h.generateFileName(theXSLFile, "xml", theXMLFile, &fileStatus); if (!fileStatus) continue; h.data.xmlFileURL = theXMLFile; h.data.xslFileURL = theXSLFile; XalanDOMString theGoldFile(h.args.gold, theMemoryManager); theGoldFile += currentDir; theGoldFile += XalanFileUtility::s_pathSep; theGoldFile += currentFile; h.generateFileName(theGoldFile, "out", theGoldFile); XalanDOMString outbase (h.args.output, theMemoryManager); outbase += currentDir; outbase += XalanFileUtility::s_pathSep; outbase += currentFile; XalanDOMString theOutputFile(theMemoryManager); h.generateFileName(outbase, "out", theOutputFile); const XSLTInputSource xslInputSource(theXSLFile, theMemoryManager); const XSLTInputSource xmlInputSource(theXMLFile, theMemoryManager); const XSLTResultTarget resultFile(theOutputFile, theMemoryManager); // Parsing(compile) the XSL stylesheet and report the results.. // const XalanCompiledStylesheet* compiledSS = 0; xalan.compileStylesheet(xslInputSource, compiledSS); if (compiledSS == 0 ) { // Report the failure and be sure to increment fail count. // CharVectorType theVector(theMemoryManager); TranscodeToLocalCodePage(currentFile, theVector); cout << "Failed to parse stylesheet for " << theVector << endl; h.data.fail += 1; XalanDOMString tmp("Failed to parse stylesheet. ", theMemoryManager); tmp += XalanDOMString(xalan.getLastError(), theMemoryManager); logFile.logErrorResult(currentFile, theMemoryManager); continue; } // Parse the Source XML based on input parameters, and then perform transform. // switch (h.args.source) { case 0: case 1: theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; case 2: theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; } // Check and report results... Then delete compiled stylesheet. // h.checkResults(theOutputFile, theGoldFile, logFile); xalan.destroyStylesheet(compiledSS); } logFile.logTestCaseClose("Done", "Pass"); } } // Check to see if -sub cmd-line directory was processed correctly. // if (!foundDir) { CharVectorType vect(theMemoryManager); TranscodeToLocalCodePage(h.args.sub, vect); cout << "Specified test directory: \"" << c_str(vect) << "\" not found" << endl; } else if (theResult != 0) { cout << "An unexpected tranformer error occurred. The error code is " << theResult << "\n" << "The error message is \"" << xalan.getLastError() << endl; } h.reportPassFail(logFile, UniqRunid); logFile.logTestFileClose("Conformance ", "Done"); logFile.close(); h.analyzeResults(xalan, resultsFile); } } catch(const XalanDiagnosticMemoryManager::LockException&) { cerr << "An attempt was made to allocate memory " "from a locked XalanDiagnosticMemoryManager " "instance!" << endl << endl; theResult = -1; } catch(...) { cerr << "Initialization of testing harness failed!" << endl << endl; } return theResult; } int main( int argc, char* argv[]) { #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif #if defined(XALAN_VQ_SPECIAL_TRACE) QuantifyStopRecordingData(); QuantifyClearData(); #endif int theResult = 0; try { XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XERCES(XMLUni) XalanMemoryManagerDefault theGlobalMemoryManager; XalanDiagnosticMemoryManager theDiagnosticMemoryManager(theGlobalMemoryManager); XalanMemoryManagerDefault theTestingMemoryManager; // Call the static initializers for xerces and xalan, and create a transformer // XMLPlatformUtils::Initialize( XMLUni::fgXercescDefaultLocale, 0, 0, &theDiagnosticMemoryManager, true); XalanTransformer::initialize(theDiagnosticMemoryManager); theDiagnosticMemoryManager.lock(); { theResult = runTests(argc, argv, theTestingMemoryManager); } theDiagnosticMemoryManager.unlock(); XalanTransformer::terminate(); XMLPlatformUtils::Terminate(); XalanTransformer::ICUCleanUp(); } catch(...) { cerr << "Initialization failed!" << endl << endl; theResult = -1; } return theResult; } <commit_msg>Modified to use new XalanDiagnosticMemoryManager constructor arguments.<commit_after>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Base header file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <cstdio> XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) #include "xercesc/util/PlatformUtils.hpp" #include "xercesc/parsers/XercesDOMParser.hpp" #include "xalanc/PlatformSupport/XalanMemoryManagerDefault.hpp" #include "xalanc/XercesParserLiaison/XercesParserLiaison.hpp" #include "xalanc/XercesParserLiaison/XercesDOMSupport.hpp" #include "xalanc/XalanTransformer/XalanTransformer.hpp" #include "xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp" // HARNESS HEADERS... #include "xalanc/Harness/XalanFileUtility.hpp" #include "xalanc/Harness/XalanDiagnosticMemoryManager.hpp" #include "xalanc/Harness/XalanXMLFileReporter.hpp" //#define XALAN_VQ_SPECIAL_TRACE #if defined(XALAN_VQ_SPECIAL_TRACE) #include "C:/Program Files/Rational/Quantify/pure.h" #endif // Just hoist everything... XALAN_CPP_NAMESPACE_USE // This is here for memory leak testing. #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif XALAN_USING_XERCES(MemoryManager) void setHelp(XalanFileUtility& h) { h.args.getHelpStream() << endl << "conf dir [-sub -out -gold -source (XST | XPL | DOM)]" << endl << endl << "dir (base directory for testcases)" << endl << "-sub dir (specific directory)" << endl << "-out dir (base directory for output)" << endl << "-gold dir (base directory for gold files)" << endl << "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)" << endl; } static const char* const excludeStylesheets[] = { // "output22.xsl", // Excluded because it outputs EBCDIC 0 }; inline bool checkForExclusion( const XalanDOMString& currentFile, MemoryManager& theMemoryManager) { for (size_t i = 0; excludeStylesheets[i] != 0; ++i) { if (currentFile == XalanDOMString(excludeStylesheets[i], theMemoryManager)) { return true; } } return false; } int parseWithTransformer( int sourceType, XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { const XalanParsedSource* parsedSource = 0; MemoryManagerType& mgr = h.getMemoryManager(); int theResult = 0; // Parse the XML source accordingly. // if (sourceType != 0 ) { theResult = xalan.parseSource(xmlInput, parsedSource, true); h.data.xmlFormat = XalanDOMString("XercesParserLiasion", mgr); } else { theResult = xalan.parseSource(xmlInput, parsedSource, false); h.data.xmlFormat = XalanDOMString("XalanSourceTree", mgr); } // If the source was parsed correctly then perform the transform else report the failure. // if (parsedSource == 0) { // Report the failure and be sure to increment fail count. // cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString tmp("Failed to parse source document. ", mgr); tmp.append(xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, tmp ); } else { theResult = xalan.transform(*parsedSource, styleSheet, output); xalan.destroyParsedSource(parsedSource); } return theResult; } int parseWithXerces( XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { XALAN_USING_XERCES(XercesDOMParser) XALAN_USING_XERCES(DOMDocument) MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); h.data.xmlFormat = XalanDOMString("Xerces_DOM", mgr); XercesDOMParser theParser; theParser.setDoValidation(true); theParser.setDoNamespaces(true); theParser.parse(xmlInput); DOMDocument* const theDOM = theParser.getDocument(); theDOM->normalize(); XercesDOMSupport theDOMSupport(mgr); XercesParserLiaison theParserLiaison(mgr); int theResult = 0; try { const XercesDOMWrapperParsedSource parsedSource( theDOM, theParserLiaison, theDOMSupport, XalanDOMString(xmlInput.getSystemId(), mgr), mgr); theResult = xalan.transform(parsedSource, styleSheet, output); } catch(...) { // Report the failure and be sure to increment fail count. // cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString resultString("Failed to parse source document. ", mgr); resultString.append( xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, resultString); } return theResult; } int runTests( int argc, char* argv[], MemoryManager& theMemoryManager) { int theResult = 0; try { XalanFileUtility h(theMemoryManager); // Set the program help string, then get the command line parameters. // setHelp(h); if (h.getParams(argc, argv, "CONF-RESULTS") == true) { XalanTransformer xalan(theMemoryManager); // Get drive designation for final analysis and generate Unique name for results log. // XalanDOMString drive(theMemoryManager); // This is used to get stylesheet for final analysis h.getDrive(drive); const XalanDOMString resultFilePrefix("conf", theMemoryManager); // This & UniqRunid used for log file name. XalanDOMString UniqRunid(theMemoryManager); h.generateUniqRunid(UniqRunid); XalanDOMString resultsFile(drive, theMemoryManager); resultsFile += h.args.output; resultsFile += resultFilePrefix; resultsFile += UniqRunid; resultsFile += XalanFileUtility::s_xmlSuffix; // Open results log, and do some initialization of result data. // XalanXMLFileReporter logFile(theMemoryManager, resultsFile); logFile.logTestFileInit("Conformance Testing:"); h.data.xmlFormat = XalanDOMString("NotSet", theMemoryManager); // Get the list of Directories that are below conf and iterate through them // // Flag indicates directory found. Used in conjunction with -sub cmd-line arg. bool foundDir = false; typedef XalanFileUtility::FileNameVectorType FileNameVectorType; FileNameVectorType dirs(theMemoryManager); h.getDirectoryNames(h.args.base, dirs); int theResult = 0; for(FileNameVectorType::size_type j = 0; j < dirs.size() && theResult == 0; ++j) { // Skip all but the specified directory if the -sub cmd-line option was used. // const XalanDOMString& currentDir = dirs[j]; if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true) { // Check that output directory is there. // XalanDOMString theOutputDir(theMemoryManager); theOutputDir = h.args.output; theOutputDir += currentDir; h.checkAndCreateDir(theOutputDir); // Indicate that directory was processed and get test files from the directory // foundDir = true; FileNameVectorType files(theMemoryManager); h.getTestFileNames(h.args.base, currentDir, true, files); // Log directory in results log and process it's files. // logFile.logTestCaseInit(currentDir); for(FileNameVectorType::size_type i = 0; i < files.size(); i++) { XalanXMLFileReporter::Hashtable attrs(theMemoryManager); const XalanDOMString& currentFile = files[i]; if (checkForExclusion(currentFile, theMemoryManager)) continue; h.data.testOrFile = currentFile; XalanDOMString theXSLFile( h.args.base, theMemoryManager); theXSLFile += currentDir; theXSLFile += XalanFileUtility::s_pathSep; theXSLFile += currentFile; // Check and see if the .xml file exists. If not skip this .xsl file and continue. bool fileStatus = true; XalanDOMString theXMLFile(theMemoryManager); h.generateFileName(theXSLFile, "xml", theXMLFile, &fileStatus); if (!fileStatus) continue; h.data.xmlFileURL = theXMLFile; h.data.xslFileURL = theXSLFile; XalanDOMString theGoldFile(h.args.gold, theMemoryManager); theGoldFile += currentDir; theGoldFile += XalanFileUtility::s_pathSep; theGoldFile += currentFile; h.generateFileName(theGoldFile, "out", theGoldFile); XalanDOMString outbase (h.args.output, theMemoryManager); outbase += currentDir; outbase += XalanFileUtility::s_pathSep; outbase += currentFile; XalanDOMString theOutputFile(theMemoryManager); h.generateFileName(outbase, "out", theOutputFile); const XSLTInputSource xslInputSource(theXSLFile, theMemoryManager); const XSLTInputSource xmlInputSource(theXMLFile, theMemoryManager); const XSLTResultTarget resultFile(theOutputFile, theMemoryManager); // Parsing(compile) the XSL stylesheet and report the results.. // const XalanCompiledStylesheet* compiledSS = 0; xalan.compileStylesheet(xslInputSource, compiledSS); if (compiledSS == 0 ) { // Report the failure and be sure to increment fail count. // CharVectorType theVector(theMemoryManager); TranscodeToLocalCodePage(currentFile, theVector); cout << "Failed to parse stylesheet for " << theVector << endl; h.data.fail += 1; XalanDOMString tmp("Failed to parse stylesheet. ", theMemoryManager); tmp += XalanDOMString(xalan.getLastError(), theMemoryManager); logFile.logErrorResult(currentFile, theMemoryManager); continue; } // Parse the Source XML based on input parameters, and then perform transform. // switch (h.args.source) { case 0: case 1: theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; case 2: theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; } // Check and report results... Then delete compiled stylesheet. // h.checkResults(theOutputFile, theGoldFile, logFile); xalan.destroyStylesheet(compiledSS); } logFile.logTestCaseClose("Done", "Pass"); } } // Check to see if -sub cmd-line directory was processed correctly. // if (!foundDir) { CharVectorType vect(theMemoryManager); TranscodeToLocalCodePage(h.args.sub, vect); cout << "Specified test directory: \"" << c_str(vect) << "\" not found" << endl; } else if (theResult != 0) { cout << "An unexpected tranformer error occurred. The error code is " << theResult << "\n" << "The error message is \"" << xalan.getLastError() << endl; } h.reportPassFail(logFile, UniqRunid); logFile.logTestFileClose("Conformance ", "Done"); logFile.close(); h.analyzeResults(xalan, resultsFile); } } catch(const XalanDiagnosticMemoryManager::LockException&) { cerr << "An attempt was made to allocate memory " "from a locked XalanDiagnosticMemoryManager " "instance!" << endl << endl; theResult = -1; } catch(...) { cerr << "Initialization of testing harness failed!" << endl << endl; } return theResult; } int main( int argc, char* argv[]) { #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif #if defined(XALAN_VQ_SPECIAL_TRACE) QuantifyStopRecordingData(); QuantifyClearData(); #endif int theResult = 0; try { XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XERCES(XMLUni) XalanMemoryManagerDefault theGlobalMemoryManager; XalanDiagnosticMemoryManager theDiagnosticMemoryManager(theGlobalMemoryManager, true, &cerr); XalanMemoryManagerDefault theTestingMemoryManager; // Call the static initializers for xerces and xalan, and create a transformer // XMLPlatformUtils::Initialize( XMLUni::fgXercescDefaultLocale, 0, 0, &theDiagnosticMemoryManager, true); XalanTransformer::initialize(theDiagnosticMemoryManager); theDiagnosticMemoryManager.lock(); { theResult = runTests(argc, argv, theTestingMemoryManager); } theDiagnosticMemoryManager.unlock(); XalanTransformer::terminate(); XMLPlatformUtils::Terminate(); XalanTransformer::ICUCleanUp(); } catch(...) { cerr << "Initialization failed!" << endl << endl; theResult = -1; } return theResult; } <|endoftext|>
<commit_before>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Base header file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <cstdio> XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xalanc/XercesParserLiaison/XercesParserLiaison.hpp> #include <xalanc/XercesParserLiaison/XercesDOMSupport.hpp> #include <xalanc/XalanTransformer/XalanTransformer.hpp> #include <xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp> // HARNESS HEADERS... #include "xalanc/Harness/XalanXMLFileReporter.hpp" #include "xalanc/Harness/XalanFileUtility.hpp" //#define XALAN_VQ_SPECIAL_TRACE #if defined(XALAN_VQ_SPECIAL_TRACE) #include "C:/Program Files/Rational/Quantify/pure.h" #endif // Just hoist everything... XALAN_CPP_NAMESPACE_USE // This is here for memory leak testing. #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif void setHelp(XalanFileUtility& h) { h.args.getHelpStream() << endl << "conf dir [-sub -out -gold -source (XST | XPL | DOM)]" << endl << endl << "dir (base directory for testcases)" << endl << "-sub dir (specific directory)" << endl << "-out dir (base directory for output)" << endl << "-gold dir (base directory for gold files)" << endl << "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)" << endl; } static const char* const excludeStylesheets[] = { // "output22.xsl", // Excluded because it outputs EBCDIC 0 }; inline bool checkForExclusion(const XalanDOMString& currentFile) { for (size_t i = 0; excludeStylesheets[i] != 0; ++i) { if (equals(currentFile, excludeStylesheets[i])) { return true; } } return false; } int parseWithTransformer( int sourceType, XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { const XalanParsedSource* parsedSource = 0; int theResult = 0; // Parse the XML source accordingly. // if (sourceType != 0 ) { theResult = xalan.parseSource(xmlInput, parsedSource, true); h.data.xmlFormat = XalanDOMString("XercesParserLiasion"); } else { theResult = xalan.parseSource(xmlInput, parsedSource, false); h.data.xmlFormat = XalanDOMString("XalanSourceTree"); } // If the source was parsed correctly then perform the transform else report the failure. // if (parsedSource == 0) { // Report the failure and be sure to increment fail count. // cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to parse source document. ") + xalan.getLastError()); } else { theResult = xalan.transform(*parsedSource, styleSheet, output); xalan.destroyParsedSource(parsedSource); } return theResult; } int parseWithXerces( XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { XALAN_USING_XERCES(XercesDOMParser) XALAN_USING_XERCES(DOMDocument) h.data.xmlFormat = XalanDOMString("Xerces_DOM"); XercesDOMParser theParser; theParser.setDoValidation(true); theParser.setDoNamespaces(true); theParser.parse(xmlInput); DOMDocument* const theDOM = theParser.getDocument(); theDOM->normalize(); XercesDOMSupport theDOMSupport; XercesParserLiaison theParserLiaison; int theResult = 0; try { const XercesDOMWrapperParsedSource parsedSource( theDOM, theParserLiaison, theDOMSupport, XalanDOMString(xmlInput.getSystemId())); theResult = xalan.transform(parsedSource, styleSheet, output); } catch(...) { // Report the failure and be sure to increment fail count. // cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to parse source document. ") + xalan.getLastError()); } return theResult; } int runTests( int argc, char* argv[]) { int theResult = 0; try { XalanFileUtility h; // Set the program help string, then get the command line parameters. // setHelp(h); if (h.getParams(argc, argv, "CONF-RESULTS") == true) { XalanTransformer xalan; // Get drive designation for final analysis and generate Unique name for results log. // const XalanDOMString drive(h.getDrive()); // This is used to get stylesheet for final analysis const XalanDOMString resultFilePrefix("conf"); // This & UniqRunid used for log file name. const XalanDOMString UniqRunid = h.generateUniqRunid(); const XalanDOMString resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + XalanFileUtility::s_xmlSuffix); // Open results log, and do some initialization of result data. // XalanXMLFileReporter logFile(resultsFile); logFile.logTestFileInit("Conformance Testing:"); h.data.xmlFormat = XalanDOMString("NotSet"); // Get the list of Directories that are below conf and iterate through them // // Flag indicates directory found. Used in conjunction with -sub cmd-line arg. bool foundDir = false; typedef XalanFileUtility::FileNameVectorType FileNameVectorType; const FileNameVectorType dirs = h.getDirectoryNames(h.args.base); int theResult = 0; for(FileNameVectorType::size_type j = 0; j < dirs.size() && theResult == 0; ++j) { // Skip all but the specified directory if the -sub cmd-line option was used. // const XalanDOMString& currentDir = dirs[j]; if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true) { // Check that output directory is there. // const XalanDOMString theOutputDir = h.args.output + currentDir; h.checkAndCreateDir(theOutputDir); // Indicate that directory was processed and get test files from the directory // foundDir = true; const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true); // Log directory in results log and process it's files. // logFile.logTestCaseInit(currentDir); for(FileNameVectorType::size_type i = 0; i < files.size(); i++) { XalanXMLFileReporter::Hashtable attrs; const XalanDOMString& currentFile = files[i]; if (checkForExclusion(currentFile)) continue; h.data.testOrFile = currentFile; const XalanDOMString theXSLFile = h.args.base + currentDir + XalanFileUtility::s_pathSep + currentFile; // Check and see if the .xml file exists. If not skip this .xsl file and continue. bool fileStatus = true; const XalanDOMString theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus); if (!fileStatus) continue; h.data.xmlFileURL = theXMLFile; h.data.xslFileURL = theXSLFile; XalanDOMString theGoldFile = h.args.gold + currentDir + XalanFileUtility::s_pathSep + currentFile; theGoldFile = h.generateFileName(theGoldFile, "out"); const XalanDOMString outbase = h.args.output + currentDir + XalanFileUtility::s_pathSep + currentFile; const XalanDOMString theOutputFile = h.generateFileName(outbase, "out"); const XSLTInputSource xslInputSource(theXSLFile); const XSLTInputSource xmlInputSource(theXMLFile); const XSLTResultTarget resultFile(theOutputFile); // Parsing(compile) the XSL stylesheet and report the results.. // const XalanCompiledStylesheet* compiledSS = 0; xalan.compileStylesheet(xslInputSource, compiledSS); if (compiledSS == 0 ) { // Report the failure and be sure to increment fail count. // cout << "Failed to parse stylesheet for " << currentFile << endl; h.data.fail += 1; logFile.logErrorResult(currentFile, XalanDOMString("Failed to parse stylesheet. ") + xalan.getLastError()); continue; } // Parse the Source XML based on input parameters, and then perform transform. // switch (h.args.source) { case 0: case 1: theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; case 2: theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; } // Check and report results... Then delete compiled stylesheet. // h.checkResults(theOutputFile, theGoldFile, logFile); xalan.destroyStylesheet(compiledSS); } logFile.logTestCaseClose("Done", "Pass"); } } // Check to see if -sub cmd-line directory was processed correctly. // if (!foundDir) { cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl; } else if (theResult != 0) { cout << "An unexpected tranformer error occurred. The error code is " << theResult << "\n" << "The error message is \"" << xalan.getLastError() << endl; } h.reportPassFail(logFile, UniqRunid); logFile.logTestFileClose("Conformance ", "Done"); logFile.close(); h.analyzeResults(xalan, resultsFile); } } catch(...) { cerr << "Initialization of testing harness failed!" << endl << endl; } return theResult; } int main( int argc, char* argv[]) { #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif #if defined(XALAN_VQ_SPECIAL_TRACE) QuantifyStopRecordingData(); QuantifyClearData(); #endif int theResult = 0; try { XALAN_USING_XERCES(XMLPlatformUtils) // Call the static initializers for xerces and xalan, and create a transformer // XMLPlatformUtils::Initialize(); XalanTransformer::initialize(); theResult = runTests(argc, argv); XalanTransformer::terminate(); XMLPlatformUtils::Terminate(); XalanTransformer::ICUCleanUp(); } catch(...) { cerr << "Initialization failed!" << endl << endl; theResult = -1; } return theResult; } <commit_msg>Porting conf for usage of the memory manager<commit_after>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Base header file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <cstdio> XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xalanc/XercesParserLiaison/XercesParserLiaison.hpp> #include <xalanc/XercesParserLiaison/XercesDOMSupport.hpp> #include <xalanc/XalanTransformer/XalanTransformer.hpp> #include <xalanc/XalanTransformer/XercesDOMWrapperParsedSource.hpp> // HARNESS HEADERS... #include "xalanc/Harness/XalanXMLFileReporter.hpp" #include "xalanc/Harness/XalanFileUtility.hpp" //#define XALAN_VQ_SPECIAL_TRACE #if defined(XALAN_VQ_SPECIAL_TRACE) #include "C:/Program Files/Rational/Quantify/pure.h" #endif // Just hoist everything... XALAN_CPP_NAMESPACE_USE // This is here for memory leak testing. #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif void setHelp(XalanFileUtility& h) { h.args.getHelpStream() << endl << "conf dir [-sub -out -gold -source (XST | XPL | DOM)]" << endl << endl << "dir (base directory for testcases)" << endl << "-sub dir (specific directory)" << endl << "-out dir (base directory for output)" << endl << "-gold dir (base directory for gold files)" << endl << "-src type (parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)" << endl; } static const char* const excludeStylesheets[] = { // "output22.xsl", // Excluded because it outputs EBCDIC 0 }; inline bool checkForExclusion(const XalanDOMString& currentFile) { MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); for (size_t i = 0; excludeStylesheets[i] != 0; ++i) { if (equals(currentFile, XalanDOMString(excludeStylesheets[i], mgr))) { return true; } } return false; } int parseWithTransformer( int sourceType, XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { const XalanParsedSource* parsedSource = 0; MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); int theResult = 0; // Parse the XML source accordingly. // if (sourceType != 0 ) { theResult = xalan.parseSource(xmlInput, parsedSource, true); h.data.xmlFormat = XalanDOMString("XercesParserLiasion", mgr); } else { theResult = xalan.parseSource(xmlInput, parsedSource, false); h.data.xmlFormat = XalanDOMString("XalanSourceTree", mgr); } // If the source was parsed correctly then perform the transform else report the failure. // if (parsedSource == 0) { // Report the failure and be sure to increment fail count. // cout << "ParseWTransformer - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString tmp("Failed to parse source document. ", mgr); tmp.append(xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, tmp ); } else { theResult = xalan.transform(*parsedSource, styleSheet, output); xalan.destroyParsedSource(parsedSource); } return theResult; } int parseWithXerces( XalanTransformer& xalan, const XSLTInputSource& xmlInput, const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget& output, XalanXMLFileReporter& logFile, XalanFileUtility& h) { XALAN_USING_XERCES(XercesDOMParser) XALAN_USING_XERCES(DOMDocument) MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); h.data.xmlFormat = XalanDOMString("Xerces_DOM", mgr); XercesDOMParser theParser; theParser.setDoValidation(true); theParser.setDoNamespaces(true); theParser.parse(xmlInput); DOMDocument* const theDOM = theParser.getDocument(); theDOM->normalize(); XercesDOMSupport theDOMSupport(mgr); XercesParserLiaison theParserLiaison(mgr); int theResult = 0; try { const XercesDOMWrapperParsedSource parsedSource( mgr, theDOM, theParserLiaison, theDOMSupport, XalanDOMString(xmlInput.getSystemId(), mgr)); theResult = xalan.transform(parsedSource, styleSheet, output); } catch(...) { // Report the failure and be sure to increment fail count. // cout << "parseWXerces - Failed to parse source document for " << h.data.testOrFile << endl; ++h.data.fail; XalanDOMString resultString("Failed to parse source document. ", mgr); resultString.append( xalan.getLastError()); logFile.logErrorResult(h.data.testOrFile, resultString); } return theResult; } int runTests( int argc, char* argv[]) { int theResult = 0; MemoryManagerType& mgr = XalanMemMgrs::getDefaultXercesMemMgr(); try { XalanFileUtility h(mgr); // Set the program help string, then get the command line parameters. // setHelp(h); if (h.getParams(argc, argv, "CONF-RESULTS") == true) { XalanTransformer xalan; // Get drive designation for final analysis and generate Unique name for results log. // XalanDOMString drive( mgr); // This is used to get stylesheet for final analysis h.getDrive(drive); const XalanDOMString resultFilePrefix("conf", mgr); // This & UniqRunid used for log file name. XalanDOMString UniqRunid( mgr); h.generateUniqRunid(UniqRunid); XalanDOMString resultsFile(drive, mgr); resultsFile += h.args.output; resultsFile += resultFilePrefix; resultsFile += UniqRunid; resultsFile += XalanFileUtility::s_xmlSuffix; // Open results log, and do some initialization of result data. // XalanXMLFileReporter logFile(mgr, resultsFile); logFile.logTestFileInit("Conformance Testing:"); h.data.xmlFormat = XalanDOMString("NotSet", mgr); // Get the list of Directories that are below conf and iterate through them // // Flag indicates directory found. Used in conjunction with -sub cmd-line arg. bool foundDir = false; typedef XalanFileUtility::FileNameVectorType FileNameVectorType; FileNameVectorType dirs(mgr); h.getDirectoryNames(h.args.base, dirs); int theResult = 0; for(FileNameVectorType::size_type j = 0; j < dirs.size() && theResult == 0; ++j) { // Skip all but the specified directory if the -sub cmd-line option was used. // const XalanDOMString& currentDir = dirs[j]; if (length(h.args.sub) == 0 || equals(currentDir, h.args.sub) == true) { // Check that output directory is there. // XalanDOMString theOutputDir(mgr); theOutputDir = h.args.output; theOutputDir += currentDir; h.checkAndCreateDir(theOutputDir); // Indicate that directory was processed and get test files from the directory // foundDir = true; FileNameVectorType files(mgr); h.getTestFileNames(h.args.base, currentDir, true, files); // Log directory in results log and process it's files. // logFile.logTestCaseInit(currentDir); for(FileNameVectorType::size_type i = 0; i < files.size(); i++) { XalanXMLFileReporter::Hashtable attrs(mgr); const XalanDOMString& currentFile = files[i]; if (checkForExclusion(currentFile)) continue; h.data.testOrFile = currentFile; XalanDOMString theXSLFile( h.args.base, mgr); theXSLFile += currentDir; theXSLFile += XalanFileUtility::s_pathSep; theXSLFile += currentFile; // Check and see if the .xml file exists. If not skip this .xsl file and continue. bool fileStatus = true; XalanDOMString theXMLFile(mgr); h.generateFileName(theXSLFile, "xml", theXMLFile, &fileStatus); if (!fileStatus) continue; h.data.xmlFileURL = theXMLFile; h.data.xslFileURL = theXSLFile; XalanDOMString theGoldFile(h.args.gold, mgr); theGoldFile += currentDir; theGoldFile += XalanFileUtility::s_pathSep; theGoldFile += currentFile; h.generateFileName(theGoldFile, "out", theGoldFile); XalanDOMString outbase (h.args.output, mgr); outbase += currentDir; outbase += XalanFileUtility::s_pathSep; outbase += currentFile; XalanDOMString theOutputFile(mgr); h.generateFileName(outbase, "out", theOutputFile); const XSLTInputSource xslInputSource(theXSLFile, mgr); const XSLTInputSource xmlInputSource(theXMLFile, mgr); const XSLTResultTarget resultFile(theOutputFile, mgr); // Parsing(compile) the XSL stylesheet and report the results.. // const XalanCompiledStylesheet* compiledSS = 0; xalan.compileStylesheet(xslInputSource, compiledSS); if (compiledSS == 0 ) { // Report the failure and be sure to increment fail count. // cout << "Failed to parse stylesheet for " << currentFile << endl; h.data.fail += 1; XalanDOMString tmp("Failed to parse stylesheet. ", mgr); tmp += XalanDOMString(xalan.getLastError(), mgr); logFile.logErrorResult(currentFile, mgr); continue; } // Parse the Source XML based on input parameters, and then perform transform. // switch (h.args.source) { case 0: case 1: theResult = parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; case 2: theResult = parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile, h); break; } // Check and report results... Then delete compiled stylesheet. // h.checkResults(theOutputFile, theGoldFile, logFile); xalan.destroyStylesheet(compiledSS); } logFile.logTestCaseClose("Done", "Pass"); } } // Check to see if -sub cmd-line directory was processed correctly. // if (!foundDir) { CharVectorType vect(mgr); TranscodeToLocalCodePage(h.args.sub, vect); cout << "Specified test directory: \"" << c_str(vect) << "\" not found" << endl; } else if (theResult != 0) { cout << "An unexpected tranformer error occurred. The error code is " << theResult << "\n" << "The error message is \"" << xalan.getLastError() << endl; } h.reportPassFail(logFile, UniqRunid); logFile.logTestFileClose("Conformance ", "Done"); logFile.close(); h.analyzeResults(xalan, resultsFile); } } catch(...) { cerr << "Initialization of testing harness failed!" << endl << endl; } return theResult; } int main( int argc, char* argv[]) { #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif #if defined(XALAN_VQ_SPECIAL_TRACE) QuantifyStopRecordingData(); QuantifyClearData(); #endif int theResult = 0; try { XALAN_USING_XERCES(XMLPlatformUtils) // Call the static initializers for xerces and xalan, and create a transformer // XMLPlatformUtils::Initialize(); XalanTransformer::initialize(); theResult = runTests(argc, argv); XalanTransformer::terminate(); XMLPlatformUtils::Terminate(); XalanTransformer::ICUCleanUp(); } catch(...) { cerr << "Initialization failed!" << endl << endl; theResult = -1; } return theResult; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <mitkPointSet.h> #include <mitkTestingMacros.h> #include <vtkPolyData.h> #include <vtkPoints.h> #include <mitkPointLocator.h> #include <vtkPointLocator.h> #include <cstdlib> vtkFloatingPointType GenerateRandomNumber( const vtkFloatingPointType& min = 0.0, const vtkFloatingPointType& max = 100.0 ) { return ( ( ( vtkFloatingPointType ) ( std::rand( ) ) ) / ( ( vtkFloatingPointType ) ( RAND_MAX ) ) ) * ( max - min) + min; } void GenerateRandomPoint( vtkFloatingPointType& x, vtkFloatingPointType& y, vtkFloatingPointType& z, const vtkFloatingPointType& min = 0.0, const vtkFloatingPointType& max = 100.0 ) { x = GenerateRandomNumber(min, max); y = GenerateRandomNumber(min, max); z = GenerateRandomNumber(min, max); } int mitkPointLocatorTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkPointLocator"); std::srand( 1 ); unsigned int num_points = 10000; // Create PointSet with randomly defined point MITK_TEST_OUTPUT(<< "Creating random point set of 10000 points "); vtkPoints* points = vtkPoints::New(); for (unsigned int i = 0; i < num_points ; ++i ) { points->InsertPoint(i, GenerateRandomNumber(), GenerateRandomNumber(), GenerateRandomNumber()); } vtkPolyData* pointSet = vtkPolyData::New(); pointSet->SetPoints( points ); points->Delete(); MITK_TEST_CONDITION_REQUIRED((unsigned) pointSet->GetNumberOfPoints()== num_points,"Test number of points in vtkPointSet"); // feed the point set into a vtk point locator MITK_TEST_OUTPUT(<< "Building vtkPointLocator "); vtkPointLocator* vtkPointLoc = vtkPointLocator::New(); vtkPointLoc->SetDataSet( pointSet ); vtkPointLoc->BuildLocator(); MITK_TEST_OUTPUT(<< "[PASSED]"); // feed the point set into the mitk point locator MITK_TEST_OUTPUT(<< "Building mitkPointLocator "); mitk::PointLocator::Pointer mitkPointLocatorInitializedByVtkPointSet = mitk::PointLocator::New(); mitk::PointLocator::Pointer mitkPointLocatorInitializedByMITKPointSet = mitk::PointLocator::New(); mitk::PointLocator::Pointer mitkPointLocatorInitializedByITKPointSet = mitk::PointLocator::New(); MITK_TEST_CONDITION_REQUIRED(mitkPointLocatorInitializedByVtkPointSet.IsNotNull(), "Test whether mitkPointLocator is not null"); mitk::PointSet::Pointer mitkPointSet = mitk::PointSet::New(); mitk::PointLocator::ITKPointSet::Pointer itkPointSet = mitk::PointLocator::ITKPointSet::New(); for ( int i=0; i<pointSet->GetNumberOfPoints();i++ ) { mitk::Point3D pnt; pnt[0] = pointSet->GetPoint( i )[0]; pnt[1] = pointSet->GetPoint( i )[1]; pnt[2] = pointSet->GetPoint( i )[2]; mitkPointSet->InsertPoint(i, pnt ); mitk::PointLocator::ITKPointSet::PointType itkPoint; itkPoint[0] = pointSet->GetPoint( i )[0]; itkPoint[1] = pointSet->GetPoint( i )[1]; itkPoint[2] = pointSet->GetPoint( i )[2]; itkPointSet->SetPoint(i,itkPoint); } MITK_TEST_OUTPUT(<< "Setting random point set "); mitkPointLocatorInitializedByVtkPointSet->SetPoints( pointSet ); mitkPointLocatorInitializedByMITKPointSet->SetPoints( mitkPointSet ); mitkPointLocatorInitializedByITKPointSet->SetPoints( itkPointSet ); MITK_TEST_OUTPUT(<< "[PASSED]"); MITK_TEST_OUTPUT(<< "Testing 1000 random points "); // generate N random points and calculate the closest // points with both the vtk and mitk pointlocator. // verify, that the point ids are the same. vtkFloatingPointType p[3], x, y, z; mitk::PointSet::PointType pointType; for ( unsigned int i = 0 ; i < 1000 ; ++i ) { GenerateRandomPoint( x, y, z ); p[0] = x; p[1] = y; p[2] = z; pointType[0] = p[0]; pointType[1] = p[1]; pointType[2] = p[2]; int closestPointReference = vtkPointLoc->FindClosestPoint(p); // ground truth vtkPointLocator int closestPointVTK1 = mitkPointLocatorInitializedByVtkPointSet->FindClosestPoint(p); int closestPointVTK2 = mitkPointLocatorInitializedByVtkPointSet->FindClosestPoint(x, y, z); int closestPointVTK3 = mitkPointLocatorInitializedByVtkPointSet->FindClosestPoint(pointType); int closestPointMITK1 = mitkPointLocatorInitializedByMITKPointSet->FindClosestPoint(p); int closestPointMITK2 = mitkPointLocatorInitializedByMITKPointSet->FindClosestPoint(x, y, z); int closestPointMITK3 = mitkPointLocatorInitializedByMITKPointSet->FindClosestPoint(pointType); int closestPointITK1 = mitkPointLocatorInitializedByITKPointSet->FindClosestPoint(p); int closestPointITK2 = mitkPointLocatorInitializedByITKPointSet->FindClosestPoint(x, y, z); int closestPointITK3 = mitkPointLocatorInitializedByITKPointSet->FindClosestPoint(pointType); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointVTK1,"Test FindClosestPoint() using a point array with a PointLocator initialized with a vtkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointVTK2,"Test FindClosestPoint() using single coordinates with a PointLocator initialized with a vtkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointVTK3,"Test FindClosestPoint() using an mitk::PointSet with a PointLocator initialized with a vtkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointMITK1,"Test FindClosestPoint() using a point array with a PointLocator initialized with a mitk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointMITK2,"Test FindClosestPoint() using single coordinates with a PointLocator initialized with a mitk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointMITK3,"Test FindClosestPoint() using an mitk::PointSet with a PointLocator initialized with a mitk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointITK1,"Test FindClosestPoint() using a point array with a PointLocator initialized with a itk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointITK2,"Test FindClosestPoint() using single coordinates with a PointLocator initialized with a itk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointITK3,"Test FindClosestPoint() using an mitk::PointSet with a PointLocator initialized with a itk::PointSet"); //Test GetMinimalDistance // Get closest point //double* closestPoint = vtkPointLoc->GetPoints()->GetPoint(closestPointReference); double* closestPoint = pointSet->GetPoint(closestPointReference); mitk::PointSet::PointType cP; cP[0] = closestPoint[0]; cP[1] = closestPoint[1]; cP[2] = closestPoint[2]; mitk::PointLocator::DistanceType minimalDistanceReference = cP.SquaredEuclideanDistanceTo(pointType); //mitk::PointLocator::DistanceType minimalDistanceReference = // (x-closestPoint[0])*(x-closestPoint[0])+(y-closestPoint[1])*(y-closestPoint[1])+(z-closestPoint[2])*(z-closestPoint[2]); mitk::PointLocator::DistanceType minimalDistanceVtk = mitkPointLocatorInitializedByVtkPointSet->GetMinimalDistance(pointType); mitk::PointLocator::DistanceType minimalDistanceItk = mitkPointLocatorInitializedByITKPointSet->GetMinimalDistance(pointType); mitk::PointLocator::DistanceType minimalDistanceMITK = mitkPointLocatorInitializedByMITKPointSet->GetMinimalDistance(pointType); MITK_INFO << minimalDistanceReference; MITK_INFO << minimalDistanceVtk; MITK_INFO << minimalDistanceItk; MITK_INFO << minimalDistanceMITK; MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceVtk), "Test GetMinimalDistance() using a PointLocator initialized with a vtkPointSet" ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceItk), "Test GetMinimalDistance() using a PointLocator initialized with a itkPointSet" ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceMITK), "Test GetMinimalDistance() using a PointLocator initialized with a MITKPointSet" ); //MITK_TEST_CONDITION_REQUIRED((fabs(minimalDistanceReference-minimalDistanceVtk)<0.0001), "Test GetMinimalDistance() using a PointLocator initialized with a vtkPointSet" ); //MITK_TEST_CONDITION_REQUIRED((fabs(minimalDistanceReference-minimalDistanceItk)<0.0001), "Test GetMinimalDistance() using a PointLocator initialized with a itkPointSet" ); //MITK_TEST_CONDITION_REQUIRED((fabs(minimalDistanceReference-minimalDistanceMITK)<0.0001), "Test GetMinimalDistance() using a PointLocator initialized with a MITKPointSet" ); } vtkPointLoc->Delete(); pointSet->Delete(); MITK_TEST_END(); } <commit_msg>Added test case for FindClosestPointAndDistance.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <mitkPointSet.h> #include <mitkTestingMacros.h> #include <vtkPolyData.h> #include <vtkPoints.h> #include <mitkPointLocator.h> #include <vtkPointLocator.h> #include <cstdlib> vtkFloatingPointType GenerateRandomNumber( const vtkFloatingPointType& min = 0.0, const vtkFloatingPointType& max = 100.0 ) { return ( ( ( vtkFloatingPointType ) ( std::rand( ) ) ) / ( ( vtkFloatingPointType ) ( RAND_MAX ) ) ) * ( max - min) + min; } void GenerateRandomPoint( vtkFloatingPointType& x, vtkFloatingPointType& y, vtkFloatingPointType& z, const vtkFloatingPointType& min = 0.0, const vtkFloatingPointType& max = 100.0 ) { x = GenerateRandomNumber(min, max); y = GenerateRandomNumber(min, max); z = GenerateRandomNumber(min, max); } int mitkPointLocatorTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("mitkPointLocator"); std::srand( 1 ); unsigned int num_points = 10000; // Create PointSet with randomly defined point MITK_TEST_OUTPUT(<< "Creating random point set of 10000 points "); vtkPoints* points = vtkPoints::New(); for (unsigned int i = 0; i < num_points ; ++i ) { points->InsertPoint(i, GenerateRandomNumber(), GenerateRandomNumber(), GenerateRandomNumber()); } vtkPolyData* pointSet = vtkPolyData::New(); pointSet->SetPoints( points ); points->Delete(); MITK_TEST_CONDITION_REQUIRED((unsigned) pointSet->GetNumberOfPoints()== num_points,"Test number of points in vtkPointSet"); // feed the point set into a vtk point locator MITK_TEST_OUTPUT(<< "Building vtkPointLocator "); vtkPointLocator* vtkPointLoc = vtkPointLocator::New(); vtkPointLoc->SetDataSet( pointSet ); vtkPointLoc->BuildLocator(); MITK_TEST_OUTPUT(<< "[PASSED]"); // feed the point set into the mitk point locator MITK_TEST_OUTPUT(<< "Building mitkPointLocator "); mitk::PointLocator::Pointer mitkPointLocatorInitializedByVtkPointSet = mitk::PointLocator::New(); mitk::PointLocator::Pointer mitkPointLocatorInitializedByMITKPointSet = mitk::PointLocator::New(); mitk::PointLocator::Pointer mitkPointLocatorInitializedByITKPointSet = mitk::PointLocator::New(); MITK_TEST_CONDITION_REQUIRED(mitkPointLocatorInitializedByVtkPointSet.IsNotNull(), "Test whether mitkPointLocator is not null"); mitk::PointSet::Pointer mitkPointSet = mitk::PointSet::New(); mitk::PointLocator::ITKPointSet::Pointer itkPointSet = mitk::PointLocator::ITKPointSet::New(); for ( int i=0; i<pointSet->GetNumberOfPoints();i++ ) { mitk::Point3D pnt; pnt[0] = pointSet->GetPoint( i )[0]; pnt[1] = pointSet->GetPoint( i )[1]; pnt[2] = pointSet->GetPoint( i )[2]; mitkPointSet->InsertPoint(i, pnt ); mitk::PointLocator::ITKPointSet::PointType itkPoint; itkPoint[0] = pointSet->GetPoint( i )[0]; itkPoint[1] = pointSet->GetPoint( i )[1]; itkPoint[2] = pointSet->GetPoint( i )[2]; itkPointSet->SetPoint(i,itkPoint); } MITK_TEST_OUTPUT(<< "Setting random point set "); mitkPointLocatorInitializedByVtkPointSet->SetPoints( pointSet ); mitkPointLocatorInitializedByMITKPointSet->SetPoints( mitkPointSet ); mitkPointLocatorInitializedByITKPointSet->SetPoints( itkPointSet ); MITK_TEST_OUTPUT(<< "[PASSED]"); MITK_TEST_OUTPUT(<< "Testing 1000 random points "); // generate N random points and calculate the closest // points with both the vtk and mitk pointlocator. // verify, that the point ids are the same. vtkFloatingPointType p[3], x, y, z; mitk::PointSet::PointType pointType; for ( unsigned int i = 0 ; i < 100 ; ++i ) { GenerateRandomPoint( x, y, z ); p[0] = x; p[1] = y; p[2] = z; pointType[0] = p[0]; pointType[1] = p[1]; pointType[2] = p[2]; int closestPointReference = vtkPointLoc->FindClosestPoint(p); // ground truth vtkPointLocator int closestPointVTK1 = mitkPointLocatorInitializedByVtkPointSet->FindClosestPoint(p); int closestPointVTK2 = mitkPointLocatorInitializedByVtkPointSet->FindClosestPoint(x, y, z); int closestPointVTK3 = mitkPointLocatorInitializedByVtkPointSet->FindClosestPoint(pointType); int closestPointMITK1 = mitkPointLocatorInitializedByMITKPointSet->FindClosestPoint(p); int closestPointMITK2 = mitkPointLocatorInitializedByMITKPointSet->FindClosestPoint(x, y, z); int closestPointMITK3 = mitkPointLocatorInitializedByMITKPointSet->FindClosestPoint(pointType); int closestPointITK1 = mitkPointLocatorInitializedByITKPointSet->FindClosestPoint(p); int closestPointITK2 = mitkPointLocatorInitializedByITKPointSet->FindClosestPoint(x, y, z); int closestPointITK3 = mitkPointLocatorInitializedByITKPointSet->FindClosestPoint(pointType); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointVTK1,"Test FindClosestPoint() using a point array with a PointLocator initialized with a vtkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointVTK2,"Test FindClosestPoint() using single coordinates with a PointLocator initialized with a vtkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointVTK3,"Test FindClosestPoint() using an mitk::PointSet with a PointLocator initialized with a vtkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointMITK1,"Test FindClosestPoint() using a point array with a PointLocator initialized with a mitk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointMITK2,"Test FindClosestPoint() using single coordinates with a PointLocator initialized with a mitk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointMITK3,"Test FindClosestPoint() using an mitk::PointSet with a PointLocator initialized with a mitk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointITK1,"Test FindClosestPoint() using a point array with a PointLocator initialized with a itk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointITK2,"Test FindClosestPoint() using single coordinates with a PointLocator initialized with a itk::PointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointITK3,"Test FindClosestPoint() using an mitk::PointSet with a PointLocator initialized with a itk::PointSet"); //Test GetMinimalDistance // Get closest point //double* closestPoint = vtkPointLoc->GetPoints()->GetPoint(closestPointReference); double* closestPoint = pointSet->GetPoint(closestPointReference); mitk::PointSet::PointType cP; cP[0] = closestPoint[0]; cP[1] = closestPoint[1]; cP[2] = closestPoint[2]; mitk::PointLocator::DistanceType minimalDistanceReference = cP.SquaredEuclideanDistanceTo(pointType); //mitk::PointLocator::DistanceType minimalDistanceReference = // (x-closestPoint[0])*(x-closestPoint[0])+(y-closestPoint[1])*(y-closestPoint[1])+(z-closestPoint[2])*(z-closestPoint[2]); mitk::PointLocator::DistanceType minimalDistanceVtk = mitkPointLocatorInitializedByVtkPointSet->GetMinimalDistance(pointType); mitk::PointLocator::DistanceType minimalDistanceItk = mitkPointLocatorInitializedByITKPointSet->GetMinimalDistance(pointType); mitk::PointLocator::DistanceType minimalDistanceMITK = mitkPointLocatorInitializedByMITKPointSet->GetMinimalDistance(pointType); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceVtk), "Test GetMinimalDistance() using a PointLocator initialized with a vtkPointSet" ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceItk), "Test GetMinimalDistance() using a PointLocator initialized with a itkPointSet" ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceMITK), "Test GetMinimalDistance() using a PointLocator initialized with a MITKPointSet" ); int closestPointCombinedVtk; mitk::PointLocator::DistanceType minimalDistanceCombinedVtk; mitkPointLocatorInitializedByVtkPointSet->FindClosestPointAndDistance(pointType,&closestPointCombinedVtk,&minimalDistanceCombinedVtk); int closestPointCombinedITK; mitk::PointLocator::DistanceType minimalDistanceCombinedITK; mitkPointLocatorInitializedByITKPointSet->FindClosestPointAndDistance(pointType,&closestPointCombinedITK,&minimalDistanceCombinedITK); int closestPointCombinedMITK; mitk::PointLocator::DistanceType minimalDistanceCombinedMITK; mitkPointLocatorInitializedByMITKPointSet->FindClosestPointAndDistance(pointType,&closestPointCombinedMITK,&minimalDistanceCombinedMITK); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceCombinedVtk), "Test distance returned by FindClosestPointAndDistance() using a PointLocator initialized with a vtkPointSet" ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceCombinedITK), "Test distance returned by FindClosestPointAndDistance() using a PointLocator initialized with a itkPointSet" ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(minimalDistanceReference,minimalDistanceCombinedMITK), "Test distance returned by FindClosestPointAndDistance() using a PointLocator initialized with a MITKPointSet" ); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointCombinedVtk,"Test closest point returned by FindClosestPointAndDistance() using a point array with a PointLocator initialized with a vtkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointCombinedITK,"Test closest point returned by FindClosestPointAndDistance() using a point array with a PointLocator initialized with a itkPointSet"); MITK_TEST_CONDITION_REQUIRED(closestPointReference==closestPointCombinedMITK,"Test closest point returned by FindClosestPointAndDistance() using a point array with a PointLocator initialized with a MITKPointSet"); } vtkPointLoc->Delete(); pointSet->Delete(); MITK_TEST_END(); } <|endoftext|>
<commit_before>#pragma once #include <memory> #include <vector> #include <boost/thread/tss.hpp> #include <boost/thread/shared_mutex.hpp> #include "blackhole/attribute.hpp" #include "blackhole/config.hpp" #include "blackhole/detail/config/atomic.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/detail/config/nullptr.hpp" #include "blackhole/detail/thread/lock.hpp" #include "blackhole/detail/util/unique.hpp" #include "blackhole/error/handler.hpp" #include "blackhole/forwards.hpp" #include "blackhole/filter.hpp" #include "blackhole/frontend.hpp" #include "blackhole/keyword/message.hpp" #include "blackhole/keyword/severity.hpp" #include "blackhole/keyword/thread.hpp" #include "blackhole/keyword/timestamp.hpp" #include "blackhole/keyword/tracebit.hpp" #include "blackhole/keyword/process.hpp" #include "blackhole/logger/feature/scoped.hpp" namespace blackhole { namespace policy { namespace threading { struct null_mutex_t { BLACKHOLE_ALWAYS_INLINE void lock() {} BLACKHOLE_ALWAYS_INLINE bool try_lock() { return true; } BLACKHOLE_ALWAYS_INLINE void unlock() {} }; struct null_t { typedef null_mutex_t rw_mutex_type; typedef std::lock_guard<null_mutex_t> reader_lock_type; typedef std::lock_guard<null_mutex_t> writer_lock_type; }; struct rw_lock_t { typedef boost::shared_mutex rw_mutex_type; typedef boost::shared_lock<rw_mutex_type> reader_lock_type; typedef boost::unique_lock<rw_mutex_type> writer_lock_type; }; } // namespace threading } // namespace policy class base_logger_t {}; template<class T, class ThreadPolicy, class... FilterArgs> class composite_logger_t : public base_logger_t { friend class scoped_attributes_concept_t; public: typedef T mixed_type; typedef ThreadPolicy thread_policy; typedef std::function<bool(const attribute::combined_view_t&, const FilterArgs&...)> filter_type; typedef typename thread_policy::rw_mutex_type rw_mutex_type; typedef typename thread_policy::reader_lock_type reader_lock_type; typedef typename thread_policy::writer_lock_type writer_lock_type; typedef feature::scoped_t scoped_type; private: feature::scoped_t scoped; struct { std::atomic<bool> enabled; filter_type filter; log::exception_handler_t exception; std::vector<std::unique_ptr<base_frontend_t>> frontends; struct { mutable rw_mutex_type open; mutable rw_mutex_type push; } lock; } d; public: composite_logger_t(filter_type filter) { d.enabled = true; d.exception = log::default_exception_handler_t(); d.filter = std::move(filter); } composite_logger_t(composite_logger_t&& other) { *this = std::move(other); } composite_logger_t& operator=(composite_logger_t&& other) { other.d.enabled = d.enabled.exchange(other.d.enabled); auto lock = detail::thread::multi_lock(d.lock.open, d.lock.push, other.d.lock.open, other.d.lock.push); using std::swap; swap(d.filter, other.d.filter); swap(d.frontends, other.d.frontends); scoped.swap(other.scoped); return *this; } bool enabled() const { return d.enabled; } void enabled(bool enable) { d.enabled.store(enable); } void set_filter(filter_type filter) { writer_lock_type lock(d.lock.open); d.filter = std::move(filter); } void add_frontend(std::unique_ptr<base_frontend_t> frontend) { writer_lock_type lock(d.lock.push); d.frontends.push_back(std::move(frontend)); } void set_exception_handler(log::exception_handler_t handler) { writer_lock_type lock(d.lock.push); d.exception = handler; } record_t open_record(FilterArgs... args) const { return open_record(attribute::set_t(), std::forward<FilterArgs>(args)...); } record_t open_record(attribute::pair_t pair, FilterArgs... args) const { return open_record(attribute::set_t({ pair }), std::forward<FilterArgs>(args)...); } record_t open_record(attribute::set_t external, FilterArgs... args) const { if (!enabled()) { return record_t::invalid(); } reader_lock_type lock(d.lock.open); if (!d.filter(scoped.view(external), args...)) { return record_t::invalid(); } attribute::set_t internal; populate(internal); static_cast<const mixed_type&>(*this).populate_additional(internal, args...); external.reserve(BLACKHOLE_EXTERNAL_SET_RESERVED_SIZE); scoped.merge(external); return record_t(std::move(internal), std::move(external)); } void push(record_t&& record) const { reader_lock_type lock(d.lock.push); for (auto it = d.frontends.begin(); it != d.frontends.end(); ++it) { try { (*it)->handle(record); } catch (...) { d.exception(); } } } private: void populate(attribute::set_t& internal) const { internal.reserve(BLACKHOLE_INTERNAL_SET_RESERVED_SIZE); #ifdef BLACKHOLE_HAS_ATTRIBUTE_PID internal.emplace_back(keyword::pid() = keyword::init::pid()); #endif #ifdef BLACKHOLE_HAS_ATTRIBUTE_TID internal.emplace_back(keyword::tid() = keyword::init::tid()); #endif #ifdef BLACKHOLE_HAS_ATTRIBUTE_LWP internal.emplace_back(keyword::lwp() = keyword::init::lwp()); #endif internal.emplace_back(keyword::timestamp() = keyword::init::timestamp()); } }; class logger_base_t : public composite_logger_t<logger_base_t, policy::threading::rw_lock_t> { friend class composite_logger_t<logger_base_t, policy::threading::rw_lock_t>; typedef composite_logger_t<logger_base_t, policy::threading::rw_lock_t> base_type; public: logger_base_t() : base_type(&filter::none) {} #ifdef BLACKHOLE_HAS_GCC44 logger_base_t(logger_base_t&& other) : base_type(std::move(other)) {} logger_base_t& operator=(logger_base_t&& other) { base_type::operator=(std::move(other)); return *this; } #endif private: void populate_additional(attribute::set_t&) const {} }; template<typename Level> class verbose_logger_t : public composite_logger_t<verbose_logger_t<Level>, policy::threading::rw_lock_t, Level> { friend class composite_logger_t<verbose_logger_t<Level>, policy::threading::rw_lock_t, Level>; typedef composite_logger_t<verbose_logger_t<Level>, policy::threading::rw_lock_t, Level> base_type; public: typedef Level level_type; typedef typename aux::underlying_type<level_type>::type underlying_type; private: std::atomic<underlying_type> level; public: verbose_logger_t(level_type level) : base_type(default_filter { level }), level(static_cast<underlying_type>(level)) {} verbose_logger_t(verbose_logger_t&& other) : base_type(std::move(other)), level(other.level.load()) {} verbose_logger_t& operator=(verbose_logger_t&& other) { base_type::operator=(std::move(other)); level.store(other.level); return *this; } level_type verbosity() const { return static_cast<level_type>(level.load()); } void set_filter(level_type level) { base_type::set_filter(default_filter { level }); this->level.store(level); } void set_filter(level_type level, typename base_type::filter_type filter) { base_type::set_filter(std::move(filter)); this->level.store(level); } record_t open_record(level_type level, attribute::set_t external = attribute::set_t()) const { return base_type::open_record(std::move(external), level); } private: void populate_additional(attribute::set_t& internal, level_type level) const { internal.emplace_back(keyword::severity<level_type>() = level); } struct default_filter { const level_type threshold; inline bool operator()(const attribute::combined_view_t&, level_type level) const { typedef typename aux::underlying_type<level_type>::type underlying_type; return static_cast<underlying_type>(level) >= static_cast<underlying_type>(threshold); } }; }; } // namespace blackhole <commit_msg>[Evolution] Refactoring filter policy.<commit_after>#pragma once #include <memory> #include <vector> #include <boost/thread/tss.hpp> #include <boost/thread/shared_mutex.hpp> #include "blackhole/attribute.hpp" #include "blackhole/config.hpp" #include "blackhole/detail/config/atomic.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/detail/config/nullptr.hpp" #include "blackhole/detail/thread/lock.hpp" #include "blackhole/detail/util/unique.hpp" #include "blackhole/error/handler.hpp" #include "blackhole/forwards.hpp" #include "blackhole/filter.hpp" #include "blackhole/frontend.hpp" #include "blackhole/keyword/message.hpp" #include "blackhole/keyword/severity.hpp" #include "blackhole/keyword/thread.hpp" #include "blackhole/keyword/timestamp.hpp" #include "blackhole/keyword/tracebit.hpp" #include "blackhole/keyword/process.hpp" #include "blackhole/logger/feature/scoped.hpp" namespace blackhole { namespace policy { namespace threading { struct null_mutex_t { BLACKHOLE_ALWAYS_INLINE void lock() {} BLACKHOLE_ALWAYS_INLINE bool try_lock() { return true; } BLACKHOLE_ALWAYS_INLINE void unlock() {} }; struct null_t { typedef null_mutex_t rw_mutex_type; typedef std::lock_guard<null_mutex_t> reader_lock_type; typedef std::lock_guard<null_mutex_t> writer_lock_type; }; struct rw_lock_t { typedef boost::shared_mutex rw_mutex_type; typedef boost::shared_lock<rw_mutex_type> reader_lock_type; typedef boost::unique_lock<rw_mutex_type> writer_lock_type; }; } // namespace threading template<class T, typename... Args> class filter_t { typedef T polulator_type; public: typedef std::function<bool(const attribute::combined_view_t&, const Args&...)> function_type; public: BLACKHOLE_ALWAYS_INLINE static inline bool filter(const function_type& fn, const attribute::combined_view_t& view, const Args&... args) { return fn(view, args...); } BLACKHOLE_ALWAYS_INLINE static inline void populate_with(attribute::set_t& internal, const Args&... args) { polulator_type::insert(internal, args...); } }; template<> class filter_t<void> { public: typedef std::function<bool(const attribute::combined_view_t&)> function_type; public: BLACKHOLE_ALWAYS_INLINE static inline bool filter(const function_type& fn, const attribute::combined_view_t& view) { return fn(view); } BLACKHOLE_ALWAYS_INLINE static inline void populate_with(attribute::set_t&) {} }; } // namespace policy class base_logger_t {}; template<class ThreadPolicy, class FilterPolicy> class composite_logger_t : public base_logger_t { friend class scoped_attributes_concept_t; public: typedef ThreadPolicy thread_policy; typedef FilterPolicy filter_policy; typedef typename filter_policy::function_type filter_type; typedef typename thread_policy::rw_mutex_type rw_mutex_type; typedef typename thread_policy::reader_lock_type reader_lock_type; typedef typename thread_policy::writer_lock_type writer_lock_type; typedef feature::scoped_t scoped_type; private: feature::scoped_t scoped; struct { std::atomic<bool> enabled; filter_type filter; log::exception_handler_t exception; std::vector<std::unique_ptr<base_frontend_t>> frontends; struct { mutable rw_mutex_type open; mutable rw_mutex_type push; } lock; } d; public: composite_logger_t(filter_type filter) { d.enabled = true; d.exception = log::default_exception_handler_t(); d.filter = std::move(filter); } composite_logger_t(composite_logger_t&& other) { *this = std::move(other); } composite_logger_t& operator=(composite_logger_t&& other) { other.d.enabled = d.enabled.exchange(other.d.enabled); auto lock = detail::thread::multi_lock(d.lock.open, d.lock.push, other.d.lock.open, other.d.lock.push); using std::swap; swap(d.filter, other.d.filter); swap(d.frontends, other.d.frontends); scoped.swap(other.scoped); return *this; } bool enabled() const { return d.enabled; } void enabled(bool enable) { d.enabled.store(enable); } void set_filter(filter_type filter) { writer_lock_type lock(d.lock.open); d.filter = std::move(filter); } void add_frontend(std::unique_ptr<base_frontend_t> frontend) { writer_lock_type lock(d.lock.push); d.frontends.push_back(std::move(frontend)); } void set_exception_handler(log::exception_handler_t handler) { writer_lock_type lock(d.lock.push); d.exception = handler; } template<typename... Args> record_t open_record(Args&&... args) const { return open_record(attribute::set_t(), std::forward<Args>(args)...); } template<typename... Args> record_t open_record(attribute::pair_t pair, Args&&... args) const { return open_record(attribute::set_t({ pair }), std::forward<Args>(args)...); } template<typename... Args> record_t open_record(attribute::set_t external, Args&&... args) const { if (!enabled()) { return record_t::invalid(); } reader_lock_type lock(d.lock.open); if (!filter_policy::filter(d.filter, scoped.view(external), args...)) { return record_t::invalid(); } attribute::set_t internal; populate(internal); filter_policy::populate_with(internal, args...); external.reserve(BLACKHOLE_EXTERNAL_SET_RESERVED_SIZE); scoped.merge(external); return record_t(std::move(internal), std::move(external)); } void push(record_t&& record) const { reader_lock_type lock(d.lock.push); for (auto it = d.frontends.begin(); it != d.frontends.end(); ++it) { try { (*it)->handle(record); } catch (...) { d.exception(); } } } private: void populate(attribute::set_t& internal) const { internal.reserve(BLACKHOLE_INTERNAL_SET_RESERVED_SIZE); #ifdef BLACKHOLE_HAS_ATTRIBUTE_PID internal.emplace_back(keyword::pid() = keyword::init::pid()); #endif #ifdef BLACKHOLE_HAS_ATTRIBUTE_TID internal.emplace_back(keyword::tid() = keyword::init::tid()); #endif #ifdef BLACKHOLE_HAS_ATTRIBUTE_LWP internal.emplace_back(keyword::lwp() = keyword::init::lwp()); #endif internal.emplace_back(keyword::timestamp() = keyword::init::timestamp()); } }; class logger_base_t : public composite_logger_t< policy::threading::rw_lock_t, policy::filter_t<void> > { friend class composite_logger_t<policy::threading::rw_lock_t, policy::filter_t<void>>; typedef composite_logger_t<policy::threading::rw_lock_t, policy::filter_t<void>> base_type; public: logger_base_t() : base_type(&filter::none) {} #ifdef BLACKHOLE_HAS_GCC44 logger_base_t(logger_base_t&& other) : base_type(std::move(other)) {} logger_base_t& operator=(logger_base_t&& other) { base_type::operator=(std::move(other)); return *this; } #endif }; template<typename Level> struct verbose_polulator_t { typedef Level level_type; BLACKHOLE_ALWAYS_INLINE static inline void insert(attribute::set_t& internal, level_type level) { internal.emplace_back(keyword::severity<level_type>() = level); } }; template<typename Level> class verbose_logger_t : public composite_logger_t< policy::threading::rw_lock_t, policy::filter_t<verbose_polulator_t<Level>, Level> > { friend class composite_logger_t< policy::threading::rw_lock_t, policy::filter_t<verbose_polulator_t<Level>, Level> >; typedef composite_logger_t< policy::threading::rw_lock_t, policy::filter_t<verbose_polulator_t<Level>, Level> > base_type; public: typedef Level level_type; typedef typename aux::underlying_type<level_type>::type underlying_type; private: std::atomic<underlying_type> level; public: verbose_logger_t(level_type level) : base_type(default_filter { level }), level(static_cast<underlying_type>(level)) {} verbose_logger_t(verbose_logger_t&& other) : base_type(std::move(other)), level(other.level.load()) {} verbose_logger_t& operator=(verbose_logger_t&& other) { base_type::operator=(std::move(other)); level.store(other.level); return *this; } level_type verbosity() const { return static_cast<level_type>(level.load()); } void set_filter(level_type level) { base_type::set_filter(default_filter { level }); this->level.store(level); } void set_filter(level_type level, typename base_type::filter_type filter) { base_type::set_filter(std::move(filter)); this->level.store(level); } record_t open_record(level_type level, attribute::set_t external = attribute::set_t()) const { return base_type::open_record(std::move(external), level); } private: struct default_filter { const level_type threshold; inline bool operator()(const attribute::combined_view_t&, level_type level) const { typedef typename aux::underlying_type<level_type>::type underlying_type; return static_cast<underlying_type>(level) >= static_cast<underlying_type>(threshold); } }; }; } // namespace blackhole <|endoftext|>
<commit_before>#pragma once #include <memory> #include <vector> #include <boost/thread/tss.hpp> #include "blackhole/attribute.hpp" #include "blackhole/detail/config/atomic.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/detail/config/nullptr.hpp" #include "error/handler.hpp" #include "filter.hpp" #include "frontend.hpp" #include "keyword.hpp" #include "keyword/message.hpp" #include "keyword/severity.hpp" #include "keyword/thread.hpp" #include "keyword/timestamp.hpp" #include "keyword/tracebit.hpp" #include "utils/unique.hpp" #include "blackhole/config.hpp" namespace blackhole { class scoped_attributes_concept_t; template <typename Level> struct logger_verbosity_traits { typedef Level level_type; static bool passed(level_type logger_verbosity, level_type record_verbosity) { typedef typename aux::underlying_type<Level>::type underlying_type; return static_cast<underlying_type>(record_verbosity) >= static_cast<underlying_type>(logger_verbosity); } }; class logger_base_t { protected: typedef boost::shared_mutex rw_mutex_type; typedef boost::shared_lock<rw_mutex_type> reader_lock_type; typedef boost::unique_lock<rw_mutex_type> writer_lock_type; struct state_t { std::atomic<bool> enabled; std::atomic<bool> tracked; filter_t filter; struct attrbutes_t { attribute::set_t global; boost::thread_specific_ptr<scoped_attributes_concept_t> scoped; attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) : scoped(deleter) {} } attributes; std::vector<std::unique_ptr<base_frontend_t>> frontends; log::exception_handler_t exception; struct { mutable rw_mutex_type open; mutable rw_mutex_type push; } lock; state_t(); }; state_t state; friend class scoped_attributes_concept_t; friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT; public: logger_base_t(); //! @compat GCC4.4 //! Blaming GCC4.4 - it needs explicit move constructor definition, //! because it cannot define default move constructor for derived class. logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT; logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT; bool enabled() const; void enabled(bool enable); bool tracked() const; void tracked(bool enable); void set_filter(filter_t&& filter); void add_attribute(const attribute::pair_t& attribute); void add_frontend(std::unique_ptr<base_frontend_t> frontend); void set_exception_handler(log::exception_handler_t&& handler); record_t open_record() const; record_t open_record(attribute::pair_t attribute) const; record_t open_record(attribute::set_t attributes) const; void push(record_t&& record) const; private: attribute::set_t get_event_attributes() const; attribute::set_t get_thread_attributes() const; }; //!@todo: Develop ImmutableLogger class, which provides almost immutable //! internal state (filter, exception handler, frontends). //! This class won't require any synchronization mechanizm. /// Concept form scoped attributes holder. /*! * @note: It's not movable to avoid moving to another thread. */ class scoped_attributes_concept_t { BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t); logger_base_t *m_logger; scoped_attributes_concept_t *m_previous; friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT; public: scoped_attributes_concept_t(logger_base_t& log); virtual ~scoped_attributes_concept_t(); virtual const attribute::set_t& attributes() const = 0; protected: bool has_parent() const; const scoped_attributes_concept_t& parent() const; }; template<typename Level> class verbose_logger_t : public logger_base_t { public: typedef Level level_type; private: level_type level; public: verbose_logger_t() : logger_base_t(), level(static_cast<level_type>(0)) {} //! @compat: GCC4.4 //! GCC 4.4 doesn't create default copy/move constructor for derived //! classes. It's a bug. verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT : logger_base_t(std::move(other)), level(static_cast<level_type>(0)) {} verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT { logger_base_t::operator=(std::move(other)); level = other.level; return *this; } // Explicit import other overloaded methods. using logger_base_t::open_record; /*! * Gets the current upper verbosity bound. */ level_type verbosity() const { return level; } /*! * Sets the upper verbosity bound. * Every log event with a verbosity less than `level` will be dropped. * @param[in] level - Upper verbosity value. */ void verbosity(level_type level) { this->level = level; } /*! @todo: Documentation is @deprecated. * Tries to open log record with specific verbosity level. * Internally this method compares desired verbosity level with the upper * one. Can return invalid log record if some conditions are not met. * @param[in] level - Desired verbosity level. * @return valid or invalid `record_t` object. * @todo: Shitcode. Need to fix. */ record_t open_record(level_type level, attribute::set_t local = attribute::set_t()) const { typedef logger_verbosity_traits<level_type> verbosity_traits; const bool passed = verbosity_traits::passed(this->level, level); bool trace = false; if (!passed) { auto it = local.find(keyword::tracebit().name()); if (it != local.end()) { trace = boost::get<keyword::tag::tracebit_t::type>(it->second.value); } else { reader_lock_type lock(state.lock.open); if (state.attributes.scoped.get()) { const auto& scoped = state.attributes.scoped->attributes(); auto scoped_it = scoped.find(keyword::tracebit().name()); if (scoped_it != scoped.end()) { trace = boost::get<keyword::tag::tracebit_t::type>( scoped_it->second.value ); } } } } if (passed || trace) { local.insert(keyword::severity<Level>() = level); return logger_base_t::open_record(std::move(local)); } return record_t(); } }; } // namespace blackhole #if defined(BLACKHOLE_HEADER_ONLY) #include "blackhole/logger.ipp" #endif <commit_msg>[Documentation] Synchronize.<commit_after>#pragma once #include <memory> #include <vector> #include <boost/thread/tss.hpp> #include "blackhole/attribute.hpp" #include "blackhole/detail/config/atomic.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/detail/config/nullptr.hpp" #include "error/handler.hpp" #include "filter.hpp" #include "frontend.hpp" #include "keyword.hpp" #include "keyword/message.hpp" #include "keyword/severity.hpp" #include "keyword/thread.hpp" #include "keyword/timestamp.hpp" #include "keyword/tracebit.hpp" #include "utils/unique.hpp" #include "blackhole/config.hpp" namespace blackhole { class scoped_attributes_concept_t; template <typename Level> struct logger_verbosity_traits { typedef Level level_type; static bool passed(level_type logger_verbosity, level_type record_verbosity) { typedef typename aux::underlying_type<Level>::type underlying_type; return static_cast<underlying_type>(record_verbosity) >= static_cast<underlying_type>(logger_verbosity); } }; class logger_base_t { protected: typedef boost::shared_mutex rw_mutex_type; typedef boost::shared_lock<rw_mutex_type> reader_lock_type; typedef boost::unique_lock<rw_mutex_type> writer_lock_type; struct state_t { std::atomic<bool> enabled; std::atomic<bool> tracked; filter_t filter; struct attrbutes_t { attribute::set_t global; boost::thread_specific_ptr<scoped_attributes_concept_t> scoped; attrbutes_t(void(*deleter)(scoped_attributes_concept_t*)) : scoped(deleter) {} } attributes; std::vector<std::unique_ptr<base_frontend_t>> frontends; log::exception_handler_t exception; struct { mutable rw_mutex_type open; mutable rw_mutex_type push; } lock; state_t(); }; state_t state; friend class scoped_attributes_concept_t; friend void swap(logger_base_t& lhs, logger_base_t& rhs) BLACKHOLE_NOEXCEPT; public: logger_base_t(); //! @compat GCC4.4 //! Blaming GCC4.4 - it needs explicit move constructor definition, //! because it cannot define default move constructor for derived class. logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT; logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT; bool enabled() const; void enabled(bool enable); bool tracked() const; void tracked(bool enable); void set_filter(filter_t&& filter); void add_attribute(const attribute::pair_t& attribute); void add_frontend(std::unique_ptr<base_frontend_t> frontend); void set_exception_handler(log::exception_handler_t&& handler); record_t open_record() const; record_t open_record(attribute::pair_t attribute) const; record_t open_record(attribute::set_t attributes) const; void push(record_t&& record) const; private: attribute::set_t get_event_attributes() const; attribute::set_t get_thread_attributes() const; }; //!@todo: Develop ImmutableLogger class, which provides almost immutable //! internal state (filter, exception handler, frontends). //! This class won't require any synchronization mechanizm. /// Concept form scoped attributes holder. /*! * @note: It's not movable to avoid moving to another thread. */ class scoped_attributes_concept_t { BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t); logger_base_t *m_logger; scoped_attributes_concept_t *m_previous; friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT; public: scoped_attributes_concept_t(logger_base_t& log); virtual ~scoped_attributes_concept_t(); virtual const attribute::set_t& attributes() const = 0; protected: bool has_parent() const; const scoped_attributes_concept_t& parent() const; }; template<typename Level> class verbose_logger_t : public logger_base_t { public: typedef Level level_type; private: level_type level; public: verbose_logger_t() : logger_base_t(), level(static_cast<level_type>(0)) {} //! @compat: GCC4.4 //! GCC 4.4 doesn't create default copy/move constructor for derived //! classes. It's a bug. verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT : logger_base_t(std::move(other)), level(static_cast<level_type>(0)) {} verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT { logger_base_t::operator=(std::move(other)); level = other.level; return *this; } // Explicit import other overloaded methods. using logger_base_t::open_record; /*! * Gets the current upper verbosity bound. */ level_type verbosity() const { return level; } /*! * Sets the upper verbosity bound. * Every log event with a verbosity less than `level` will be dropped. * @param[in] level - Upper verbosity value. */ void verbosity(level_type level) { this->level = level; } /*! * Tries to open log record with specific verbosity level. * * Internally this method compares desired verbosity level with the upper * one and checks for tracebit attribute (temporary until filter redesign). * Can return invalid log record if some conditions are not met. * @param[in] level - Desired verbosity level. * @return valid or invalid `record_t` object. * @todo: Shitcode. Need to fix. */ record_t open_record(level_type level, attribute::set_t local = attribute::set_t()) const { typedef logger_verbosity_traits<level_type> verbosity_traits; const bool passed = verbosity_traits::passed(this->level, level); bool trace = false; if (!passed) { auto it = local.find(keyword::tracebit().name()); if (it != local.end()) { trace = boost::get<keyword::tag::tracebit_t::type>(it->second.value); } else { reader_lock_type lock(state.lock.open); if (state.attributes.scoped.get()) { const auto& scoped = state.attributes.scoped->attributes(); auto scoped_it = scoped.find(keyword::tracebit().name()); if (scoped_it != scoped.end()) { trace = boost::get<keyword::tag::tracebit_t::type>( scoped_it->second.value ); } } } } if (passed || trace) { local.insert(keyword::severity<Level>() = level); return logger_base_t::open_record(std::move(local)); } return record_t(); } }; } // namespace blackhole #if defined(BLACKHOLE_HEADER_ONLY) #include "blackhole/logger.ipp" #endif <|endoftext|>
<commit_before>/* board_wire.cpp - Arduino-XC HAL API implementation of Wire/I2C peripheral Copyright (c) 2016 Ravendyne Inc. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "board/board_wire.h" #include "ring_buffer.h" #include "board/variant.h" #include "lib/Wire.h" #include "chip.h" #include "i2cm_13xx.h" WireClass Wire = WireClass((void*)LPC_I2C, NULL); void WIRE_ISR_HANDLER(void) { Wire.onService(); } void Board_I2C_Master_Init(void *pI2C) { // LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; // Init_I2C_PinMux(); /* Initialize I2C * - enable I2C clock via SYSAHBCLKCTRL * - resets I2C peripheral via clocking I2C pin in PRESETCTRL */ Chip_I2CM_Init(LPC_I2C); /* * Sets SCLH and SCLL based on PCLK (which is same as core clock) * and given speed */ Chip_I2CM_SetBusSpeed(LPC_I2C, SPEED_100KHZ); /* * Clears SI, STO, STA and AA bits * via CONCLR */ Chip_I2CM_ResetControl(LPC_I2C); /* * clears I2EN bit via CONCLR * Chip_I2CM_SendStart() will set I2EN bit */ Chip_I2CM_Disable(LPC_I2C); /* * Enable I2C interrupt for interrupt based I2C state handling */ // NVIC_EnableIRQ(I2C0_IRQn); } void Board_I2C_Slave_Init(void *pI2C, uint8_t address) { // LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; // TODO } void Board_I2C_Set_Bus_Speed(void *pI2C, uint32_t frequency) { // LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; Chip_I2CM_SetBusSpeed(LPC_I2C, frequency); } /* Returns: 0:success 1:data too long to fit in transmit buffer 2:received NACK on transmit of address 3:received NACK on transmit of data 4:other error */ uint32_t Board_I2C_Master_Read_Blocking(void *pI2C, uint8_t address, uint8_t *rxBuffer, uint16_t size) { LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; I2CM_XFER_T xfer; xfer.slaveAddr = address; xfer.rxSz = size; xfer.rxBuff = rxBuffer; xfer.txSz = 0; xfer.txBuff = NULL; // returns: xfer->status != I2CM_STATUS_BUSY; // Chip_I2CM_XferBlocking(LPC_I2C, &xfer); Chip_I2CM_XferBlocking(lpcI2C, &xfer); Serial.println(xfer.status); return 0; } uint32_t Board_I2C_Master_Write_Blocking(void *pI2C, uint8_t address, uint8_t *txBuffer, uint16_t size) { LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; I2CM_XFER_T xfer; xfer.slaveAddr = address; xfer.rxSz = 0; xfer.rxBuff = NULL; xfer.txSz = size; xfer.txBuff = txBuffer; // returns: xfer->status != I2CM_STATUS_BUSY; Chip_I2CM_XferBlocking(lpcI2C, &xfer); return 0; } <commit_msg>I2C is initialized with 10kHz speed which works much better when using jumper wires for prototyping.<commit_after>/* board_wire.cpp - Arduino-XC HAL API implementation of Wire/I2C peripheral Copyright (c) 2016 Ravendyne Inc. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "board/board_wire.h" #include "ring_buffer.h" #include "board/variant.h" #include "lib/Wire.h" #include "chip.h" #include "i2cm_13xx.h" WireClass Wire = WireClass((void*)LPC_I2C, NULL); void WIRE_ISR_HANDLER(void) { Wire.onService(); } void Board_I2C_Master_Init(void *pI2C) { // LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; // Init_I2C_PinMux(); /* Initialize I2C * - enable I2C clock via SYSAHBCLKCTRL * - resets I2C peripheral via clocking I2C pin in PRESETCTRL */ Chip_I2CM_Init(LPC_I2C); /* * Sets SCLH and SCLL based on PCLK (which is same as core clock) * and given speed */ Chip_I2CM_SetBusSpeed(LPC_I2C, SPEED_10KHZ); /* * Clears SI, STO, STA and AA bits * via CONCLR */ Chip_I2CM_ResetControl(LPC_I2C); /* * clears I2EN bit via CONCLR * Chip_I2CM_SendStart() will set I2EN bit */ Chip_I2CM_Disable(LPC_I2C); /* * Enable I2C interrupt for interrupt based I2C state handling */ // NVIC_EnableIRQ(I2C0_IRQn); } void Board_I2C_Slave_Init(void *pI2C, uint8_t address) { // LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; // TODO } void Board_I2C_Set_Bus_Speed(void *pI2C, uint32_t frequency) { // LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; Chip_I2CM_SetBusSpeed(LPC_I2C, frequency); } /* Returns: 0:success 1:data too long to fit in transmit buffer 2:received NACK on transmit of address 3:received NACK on transmit of data 4:other error */ uint32_t Board_I2C_Master_Read_Blocking(void *pI2C, uint8_t address, uint8_t *rxBuffer, uint16_t size) { LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; I2CM_XFER_T xfer; xfer.slaveAddr = address; xfer.rxSz = size; xfer.rxBuff = rxBuffer; xfer.txSz = 0; xfer.txBuff = NULL; // returns: xfer->status != I2CM_STATUS_BUSY; // Chip_I2CM_XferBlocking(LPC_I2C, &xfer); Chip_I2CM_XferBlocking(lpcI2C, &xfer); // Serial.println(xfer.status); return 0; } uint32_t Board_I2C_Master_Write_Blocking(void *pI2C, uint8_t address, uint8_t *txBuffer, uint16_t size) { LPC_I2C_T *lpcI2C = (LPC_I2C_T *)pI2C; I2CM_XFER_T xfer; xfer.slaveAddr = address; xfer.rxSz = 0; xfer.rxBuff = NULL; xfer.txSz = size; xfer.txBuff = txBuffer; // returns: xfer->status != I2CM_STATUS_BUSY; Chip_I2CM_XferBlocking(lpcI2C, &xfer); return 0; } <|endoftext|>
<commit_before>// The local APIC manages internal (non-I/O) interrupts. // See Chapter 8 & Appendix C of Intel processor manual volume 3. #include "types.h" #include "amd64.h" #include "kernel.hh" #include "traps.h" #include "bits.hh" #include "cpu.hh" #include "apic.hh" #include "kstream.hh" static console_stream verbose(true); // Local APIC registers, divided by 4 for use as uint[] indices. #define ID (0x0020/4) // ID #define VER (0x0030/4) // Version #define TPR (0x0080/4) // Task Priority #define EOI (0x00B0/4) // EOI #define SVR (0x00F0/4) // Spurious Interrupt Vector #define ENABLE 0x00000100 // Unit Enable #define ESR (0x0280/4) // Error Status #define ICRLO (0x0300/4) // Interrupt Command #define INIT 0x00000500 // INIT/RESET #define STARTUP 0x00000600 // Startup IPI #define DELIVS 0x00001000 // Delivery status #define ASSERT 0x00004000 // Assert interrupt (vs deassert) #define DEASSERT 0x00000000 #define LEVEL 0x00008000 // Level triggered #define BCAST 0x00080000 // Send to all APICs, including self. #define FIXED 0x00000000 #define ICRHI (0x0310/4) // Interrupt Command [63:32] #define TIMER (0x0320/4) // Local Vector Table 0 (TIMER) #define X1 0x0000000B // divide counts by 1 #define PERIODIC 0x00020000 // Periodic #define PCINT (0x0340/4) // Performance Counter LVT #define LINT0 (0x0350/4) // Local Vector Table 1 (LINT0) #define LINT1 (0x0360/4) // Local Vector Table 2 (LINT1) #define ERROR (0x0370/4) // Local Vector Table 3 (ERROR) #define MASKED 0x00010000 // Interrupt masked #define MT_NMI 0x00000400 // NMI message type #define MT_FIX 0x00000000 // Fixed message type #define TICR (0x0380/4) // Timer Initial Count #define TCCR (0x0390/4) // Timer Current Count #define TDCR (0x03E0/4) // Timer Divide Configuration #define IO_RTC 0x70 static volatile u32 *xapic; static u64 xapichz; class xapic_lapic : public abstract_lapic { public: void init(); void cpu_init(); hwid_t id(); void eoi(); void send_ipi(struct cpu *c, int ino); void mask_pc(bool mask); void start_ap(struct cpu *c, u32 addr); }; static void xapicw(u32 index, u32 value) { xapic[index] = value; xapic[ID]; // wait for write to finish, by reading } static u32 xapicr(u32 off) { return xapic[off]; } static int xapicwait() { int i = 100000; while ((xapicr(ICRLO) & DELIVS) != 0) { nop_pause(); i--; if (i == 0) { cprintf("xapicwait: wedged?\n"); return -1; } } return 0; } void xapic_lapic::init() { u64 apic_base = readmsr(MSR_APIC_BAR); // Sanity check if (!(apic_base & APIC_BAR_XAPIC_EN)) panic("xapic_lapic::init xAPIC not enabled"); xapic = (u32*)p2v(apic_base & ~0xffful); } void xapic_lapic::cpu_init() { u64 count; verbose.println("xapic: Initializing LAPIC (CPU ", myid(), ")"); // Enable local APIC, do not suppress EOI broadcast, set spurious // interrupt vector. xapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS)); if (xapichz == 0) { // Measure the TICR frequency xapicw(TDCR, X1); xapicw(TICR, 0xffffffff); u64 ccr0 = xapicr(TCCR); microdelay(10 * 1000); // 1/100th of a second u64 ccr1 = xapicr(TCCR); xapichz = 100 * (ccr0 - ccr1); } count = (QUANTUM*xapichz) / 1000; if (count > 0xffffffff) panic("initxapic: QUANTUM too large"); // The timer repeatedly counts down at bus frequency // from xapic[TICR] and then issues an interrupt. xapicw(TDCR, X1); xapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER)); xapicw(TICR, count); // Disable logical interrupt lines. xapicw(LINT0, MASKED); xapicw(LINT1, MASKED); // Disable performance counter overflow interrupts // on machines that provide that interrupt entry. if(((xapic[VER]>>16) & 0xFF) >= 4) mask_pc(false); // Map error interrupt to IRQ_ERROR. xapicw(ERROR, T_IRQ0 + IRQ_ERROR); // Clear error status register (requires back-to-back writes). xapicw(ESR, 0); xapicw(ESR, 0); // Ack any outstanding interrupts. xapicw(EOI, 0); // Send an Init Level De-Assert to synchronise arbitration ID's. xapicw(ICRHI, 0); xapicw(ICRLO, BCAST | INIT | LEVEL); while(xapic[ICRLO] & DELIVS) ; // Enable interrupts on the APIC (but not on the processor). xapicw(TPR, 0); } void xapic_lapic::mask_pc(bool mask) { xapicw(PCINT, mask ? MASKED : MT_NMI); } hwid_t xapic_lapic::id() { if (readrflags() & FL_IF) { cli(); panic("xapic_lapic::id() called from %p with interrupts enabled\n", __builtin_return_address(0)); } return HWID(xapic[ID]>>24); } // Acknowledge interrupt. void xapic_lapic::eoi() { xapicw(EOI, 0); } // Send IPI void xapic_lapic::send_ipi(struct cpu *c, int ino) { xapicw(ICRHI, c->hwid.num << 24); xapicw(ICRLO, FIXED | DEASSERT | ino); if (xapicwait() < 0) panic("xapic_lapic::send_ipi: xapicwait failure"); } // Start additional processor running bootstrap code at addr. // See Appendix B of MultiProcessor Specification. void xapic_lapic::start_ap(struct cpu *c, u32 addr) { int i; // "Universal startup algorithm." // Send INIT (level-triggered) interrupt to reset other CPU. xapicw(ICRHI, c->hwid.num<<24); xapicw(ICRLO, INIT | LEVEL | ASSERT); xapicwait(); microdelay(10000); xapicw(ICRLO, INIT | LEVEL); xapicwait(); microdelay(10000); // should be 10ms, but too slow in Bochs! // Send startup IPI (twice!) to enter bootstrap code. // Regular hardware is supposed to only accept a STARTUP // when it is in the halted state due to an INIT. So the second // should be ignored, but it is part of the official Intel algorithm. // Bochs complains about the second one. Too bad for Bochs. for(i = 0; i < 2; i++){ xapicw(ICRHI, c->hwid.num<<24); xapicw(ICRLO, STARTUP | (addr>>12)); microdelay(200); } } bool initlapic_xapic(void) { u32 edx; cpuid(CPUID_FEATURES, nullptr, nullptr, nullptr, &edx); if (!(edx & FEATURE_EDX_APIC)) return false; verbose.println("xapic: Using xAPIC LAPIC"); static xapic_lapic apic; apic.init(); lapic = &apic; return true; } <commit_msg>xapic: Make sure send_ipi is atomic<commit_after>// The local APIC manages internal (non-I/O) interrupts. // See Chapter 8 & Appendix C of Intel processor manual volume 3. #include "types.h" #include "amd64.h" #include "kernel.hh" #include "traps.h" #include "bits.hh" #include "cpu.hh" #include "apic.hh" #include "kstream.hh" static console_stream verbose(true); // Local APIC registers, divided by 4 for use as uint[] indices. #define ID (0x0020/4) // ID #define VER (0x0030/4) // Version #define TPR (0x0080/4) // Task Priority #define EOI (0x00B0/4) // EOI #define SVR (0x00F0/4) // Spurious Interrupt Vector #define ENABLE 0x00000100 // Unit Enable #define ESR (0x0280/4) // Error Status #define ICRLO (0x0300/4) // Interrupt Command #define INIT 0x00000500 // INIT/RESET #define STARTUP 0x00000600 // Startup IPI #define DELIVS 0x00001000 // Delivery status #define ASSERT 0x00004000 // Assert interrupt (vs deassert) #define DEASSERT 0x00000000 #define LEVEL 0x00008000 // Level triggered #define BCAST 0x00080000 // Send to all APICs, including self. #define FIXED 0x00000000 #define ICRHI (0x0310/4) // Interrupt Command [63:32] #define TIMER (0x0320/4) // Local Vector Table 0 (TIMER) #define X1 0x0000000B // divide counts by 1 #define PERIODIC 0x00020000 // Periodic #define PCINT (0x0340/4) // Performance Counter LVT #define LINT0 (0x0350/4) // Local Vector Table 1 (LINT0) #define LINT1 (0x0360/4) // Local Vector Table 2 (LINT1) #define ERROR (0x0370/4) // Local Vector Table 3 (ERROR) #define MASKED 0x00010000 // Interrupt masked #define MT_NMI 0x00000400 // NMI message type #define MT_FIX 0x00000000 // Fixed message type #define TICR (0x0380/4) // Timer Initial Count #define TCCR (0x0390/4) // Timer Current Count #define TDCR (0x03E0/4) // Timer Divide Configuration #define IO_RTC 0x70 static volatile u32 *xapic; static u64 xapichz; class xapic_lapic : public abstract_lapic { public: void init(); void cpu_init(); hwid_t id(); void eoi(); void send_ipi(struct cpu *c, int ino); void mask_pc(bool mask); void start_ap(struct cpu *c, u32 addr); }; static void xapicw(u32 index, u32 value) { xapic[index] = value; xapic[ID]; // wait for write to finish, by reading } static u32 xapicr(u32 off) { return xapic[off]; } static int xapicwait() { int i = 100000; while ((xapicr(ICRLO) & DELIVS) != 0) { nop_pause(); i--; if (i == 0) { cprintf("xapicwait: wedged?\n"); return -1; } } return 0; } void xapic_lapic::init() { u64 apic_base = readmsr(MSR_APIC_BAR); // Sanity check if (!(apic_base & APIC_BAR_XAPIC_EN)) panic("xapic_lapic::init xAPIC not enabled"); xapic = (u32*)p2v(apic_base & ~0xffful); } void xapic_lapic::cpu_init() { u64 count; verbose.println("xapic: Initializing LAPIC (CPU ", myid(), ")"); // Enable local APIC, do not suppress EOI broadcast, set spurious // interrupt vector. xapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS)); if (xapichz == 0) { // Measure the TICR frequency xapicw(TDCR, X1); xapicw(TICR, 0xffffffff); u64 ccr0 = xapicr(TCCR); microdelay(10 * 1000); // 1/100th of a second u64 ccr1 = xapicr(TCCR); xapichz = 100 * (ccr0 - ccr1); } count = (QUANTUM*xapichz) / 1000; if (count > 0xffffffff) panic("initxapic: QUANTUM too large"); // The timer repeatedly counts down at bus frequency // from xapic[TICR] and then issues an interrupt. xapicw(TDCR, X1); xapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER)); xapicw(TICR, count); // Disable logical interrupt lines. xapicw(LINT0, MASKED); xapicw(LINT1, MASKED); // Disable performance counter overflow interrupts // on machines that provide that interrupt entry. if(((xapic[VER]>>16) & 0xFF) >= 4) mask_pc(false); // Map error interrupt to IRQ_ERROR. xapicw(ERROR, T_IRQ0 + IRQ_ERROR); // Clear error status register (requires back-to-back writes). xapicw(ESR, 0); xapicw(ESR, 0); // Ack any outstanding interrupts. xapicw(EOI, 0); // Send an Init Level De-Assert to synchronise arbitration ID's. xapicw(ICRHI, 0); xapicw(ICRLO, BCAST | INIT | LEVEL); while(xapic[ICRLO] & DELIVS) ; // Enable interrupts on the APIC (but not on the processor). xapicw(TPR, 0); } void xapic_lapic::mask_pc(bool mask) { xapicw(PCINT, mask ? MASKED : MT_NMI); } hwid_t xapic_lapic::id() { if (readrflags() & FL_IF) { cli(); panic("xapic_lapic::id() called from %p with interrupts enabled\n", __builtin_return_address(0)); } return HWID(xapic[ID]>>24); } // Acknowledge interrupt. void xapic_lapic::eoi() { xapicw(EOI, 0); } // Send IPI void xapic_lapic::send_ipi(struct cpu *c, int ino) { pushcli(); xapicw(ICRHI, c->hwid.num << 24); xapicw(ICRLO, FIXED | DEASSERT | ino); if (xapicwait() < 0) panic("xapic_lapic::send_ipi: xapicwait failure"); popcli(); } // Start additional processor running bootstrap code at addr. // See Appendix B of MultiProcessor Specification. void xapic_lapic::start_ap(struct cpu *c, u32 addr) { int i; // "Universal startup algorithm." // Send INIT (level-triggered) interrupt to reset other CPU. xapicw(ICRHI, c->hwid.num<<24); xapicw(ICRLO, INIT | LEVEL | ASSERT); xapicwait(); microdelay(10000); xapicw(ICRLO, INIT | LEVEL); xapicwait(); microdelay(10000); // should be 10ms, but too slow in Bochs! // Send startup IPI (twice!) to enter bootstrap code. // Regular hardware is supposed to only accept a STARTUP // when it is in the halted state due to an INIT. So the second // should be ignored, but it is part of the official Intel algorithm. // Bochs complains about the second one. Too bad for Bochs. for(i = 0; i < 2; i++){ xapicw(ICRHI, c->hwid.num<<24); xapicw(ICRLO, STARTUP | (addr>>12)); microdelay(200); } } bool initlapic_xapic(void) { u32 edx; cpuid(CPUID_FEATURES, nullptr, nullptr, nullptr, &edx); if (!(edx & FEATURE_EDX_APIC)) return false; verbose.println("xapic: Using xAPIC LAPIC"); static xapic_lapic apic; apic.init(); lapic = &apic; return true; } <|endoftext|>
<commit_before>#include "warnings-disable.h" WARNINGS_DISABLE #include <QtTest/QtTest> #include <QSettings> #include "ui_setupdialog.h" WARNINGS_ENABLE #include "../qtest-platform.h" #include "utils.h" #include <TSettings.h> #include "setupdialog.h" //! Compares all the keys in two QSettings files. static bool compareSettings(QSettings *settings, QSettings *target) { // On OSX, QSettings returns a bunch of values for the system // itself (e.g., "com/apple/trackpad/enableSecondaryClick", // NSNavRecentPlaces"). To avoid this, we only examine the // groups that are present in the target config file. for(int g = 0; g < target->childGroups().length(); g++) { QString group = target->childGroups().at(g); settings->beginGroup(group); target->beginGroup(group); // Check length of key list QStringList settings_keys = settings->allKeys(); if(settings_keys.length() != target->allKeys().length()) { qDebug() << "compareSettings: number of keys does not match!" << settings_keys.length() << target->allKeys().length(); return false; } // Check each key's value for(int i = 0; i < settings_keys.length(); i++) { QString key = settings_keys.at(i); // Skip over keys that will be different if((group == "tarsnap") && (key == "machine")) continue; #ifdef Q_OS_OSX if((group == "tarsnap") && (key == "cache")) continue; if((group == "app") && (key == "app_data")) continue; #endif // Skip over key(s) that can plausibly be different if((group == "tarsnap") && (key == "path")) continue; // Compare values if(settings->value(key) != target->value(key)) { qDebug() << "compareSettings: values do not match!" << key << settings->value(key) << target->value(key); return false; } } settings->endGroup(); target->endGroup(); } return true; } class TestSetupWizard : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void cancel_install(); void normal_install(); void skip_install(); void cli(); void version_too_low(); private: void helper_almost_normal_install(SetupDialog *setupWizard); }; void TestSetupWizard::initTestCase() { QCoreApplication::setOrganizationName(TEST_NAME); IF_NOT_VISUAL { // Use a custom message handler to filter out unwanted messages orig_message_handler = qInstallMessageHandler(offscreenMessageOutput); } } void TestSetupWizard::cleanupTestCase() { TSettings::destroy(); } void TestSetupWizard::cancel_install() { TARSNAP_CLI_OR_SKIP; SetupDialog *setupWizard = new SetupDialog(); // Almost complete a normal install helper_almost_normal_install(setupWizard); // Close before we actually finish QTest::keyEvent(QTest::Click, setupWizard, Qt::Key_Escape); VISUAL_WAIT; // Clean up delete setupWizard; // Check that we wiped the Tarsnap-related settings TSettings settings; QSettings *q = settings.getQSettings(); q->beginGroup("tarsnap"); QVERIFY(q->allKeys().length() == 0); q->beginGroup("app"); QVERIFY(q->allKeys().length() == 0); } void TestSetupWizard::helper_almost_normal_install(SetupDialog *setupWizard) { Ui::SetupDialog *ui = setupWizard->_ui; QSignalSpy sig_cli(setupWizard, SIGNAL(tarsnapVersionRequested())); QSignalSpy sig_register(setupWizard, SIGNAL(registerMachineRequested(QString, bool))); VISUAL_INIT(setupWizard); // Page 1 QVERIFY(setupWizard->pageTitle() == "Setup wizard"); setupWizard->next(); VISUAL_WAIT; // Page 2 QVERIFY(setupWizard->pageTitle() == "Command-line utilities"); QVERIFY(sig_cli.count() == 1); // Fake the CLI detection and checking setupWizard->tarsnapVersionResponse(TaskStatus::Completed, "X.Y.Z"); QVERIFY(ui->cliValidationLabel->text().contains("Tarsnap CLI version")); setupWizard->next(); VISUAL_WAIT; // Page 3 QVERIFY(setupWizard->pageTitle() == "Register with server"); // Pretend that we already have a key setupWizard->useExistingKeyfile(); ui->useExistingKeyfileButton->setChecked(true); ui->machineKeyCombo->setCurrentText("fake.key"); ui->nextButton->setEnabled(true); setupWizard->next(); // Check results of registration QVERIFY(sig_register.count() == 1); setupWizard->registerMachineResponse(TaskStatus::Completed, ""); VISUAL_WAIT; // Page 4 QVERIFY(setupWizard->pageTitle() == "Setup complete!"); VISUAL_WAIT; } void TestSetupWizard::normal_install() { TARSNAP_CLI_OR_SKIP; SetupDialog *setupWizard = new SetupDialog(); // Almost complete a normal install helper_almost_normal_install(setupWizard); // Finish the install setupWizard->next(); VISUAL_WAIT; // Check resulting init file. The first can be in any format (for now). TSettings settings; QSettings target("after-normal-install.conf", QSettings::IniFormat); QVERIFY(compareSettings(settings.getQSettings(), &target)); // Clean up delete setupWizard; } void TestSetupWizard::skip_install() { TARSNAP_CLI_OR_SKIP; SetupDialog * setupWizard = new SetupDialog(); Ui::SetupDialog *ui = setupWizard->_ui; // Almost complete a normal install helper_almost_normal_install(setupWizard); // Now go back to the beginning and skip the install setupWizard->back(); setupWizard->back(); setupWizard->back(); VISUAL_WAIT; QTest::mouseClick(ui->backButton, Qt::LeftButton); VISUAL_WAIT; // Check resulting init file. TSettings settings; QSettings target("after-skip-install.conf", QSettings::IniFormat); QVERIFY(compareSettings(settings.getQSettings(), &target)); // Clean up delete setupWizard; } void TestSetupWizard::cli() { SetupDialog * setupWizard = new SetupDialog(); Ui::SetupDialog *ui = setupWizard->_ui; QSignalSpy sig_cli(setupWizard, SIGNAL(tarsnapVersionRequested())); VISUAL_INIT(setupWizard); // Advance to CLI page and expand advanced options setupWizard->next(); QVERIFY(setupWizard->pageTitle() == "Command-line utilities"); ui->cliAdvancedButton->click(); VISUAL_WAIT; // App data directory SET_TEXT_WITH_SIGNAL(ui->appDataPathLineEdit, "fake-dir"); QVERIFY(ui->cliValidationLabel->text() == "Invalid App data directory set."); VISUAL_WAIT; SET_TEXT_WITH_SIGNAL(ui->appDataPathLineEdit, "/tmp"); // Cache directory SET_TEXT_WITH_SIGNAL(ui->tarsnapCacheLineEdit, "fake-dir"); QVERIFY(ui->cliValidationLabel->text() == "Invalid Tarsnap cache directory set."); VISUAL_WAIT; SET_TEXT_WITH_SIGNAL(ui->tarsnapCacheLineEdit, "/tmp"); // Tarsnap CLI directory SET_TEXT_WITH_SIGNAL(ui->tarsnapPathLineEdit, "fake-dir"); QVERIFY(ui->cliValidationLabel->text().contains( "Tarsnap utilities not found.")); VISUAL_WAIT; SET_TEXT_WITH_SIGNAL(ui->tarsnapPathLineEdit, "/tmp"); // Fake detecting the binaries setupWizard->tarsnapVersionResponse(TaskStatus::Completed, "X.Y.Z"); QVERIFY(ui->cliValidationLabel->text().contains("Tarsnap CLI version")); VISUAL_WAIT; delete setupWizard; } void TestSetupWizard::version_too_low() { SetupDialog * setupWizard = new SetupDialog(); Ui::SetupDialog *ui = setupWizard->_ui; VISUAL_INIT(setupWizard); // Advance to CLI page setupWizard->next(); QVERIFY(setupWizard->pageTitle() == "Command-line utilities"); VISUAL_WAIT; // Fake detecting the binaries with a too-low version number setupWizard->tarsnapVersionResponse(TaskStatus::VersionTooLow, "1.0.1"); QVERIFY(ui->cliValidationLabel->text().contains("too low")); QVERIFY(ui->nextButton->isEnabled() == false); // With platform=offscreen, ->isVisible() always returns false. // Instead, check the negation of ->isHidden() QVERIFY(ui->cliAdvancedWidget->isHidden() == false); VISUAL_WAIT; delete setupWizard; } QTEST_MAIN(TestSetupWizard) #include "test-setupwizard.moc" <commit_msg>tests/setupwizard: move cancel_install later<commit_after>#include "warnings-disable.h" WARNINGS_DISABLE #include <QtTest/QtTest> #include <QSettings> #include "ui_setupdialog.h" WARNINGS_ENABLE #include "../qtest-platform.h" #include "utils.h" #include <TSettings.h> #include "setupdialog.h" //! Compares all the keys in two QSettings files. static bool compareSettings(QSettings *settings, QSettings *target) { // On OSX, QSettings returns a bunch of values for the system // itself (e.g., "com/apple/trackpad/enableSecondaryClick", // NSNavRecentPlaces"). To avoid this, we only examine the // groups that are present in the target config file. for(int g = 0; g < target->childGroups().length(); g++) { QString group = target->childGroups().at(g); settings->beginGroup(group); target->beginGroup(group); // Check length of key list QStringList settings_keys = settings->allKeys(); if(settings_keys.length() != target->allKeys().length()) { qDebug() << "compareSettings: number of keys does not match!" << settings_keys.length() << target->allKeys().length(); return false; } // Check each key's value for(int i = 0; i < settings_keys.length(); i++) { QString key = settings_keys.at(i); // Skip over keys that will be different if((group == "tarsnap") && (key == "machine")) continue; #ifdef Q_OS_OSX if((group == "tarsnap") && (key == "cache")) continue; if((group == "app") && (key == "app_data")) continue; #endif // Skip over key(s) that can plausibly be different if((group == "tarsnap") && (key == "path")) continue; // Compare values if(settings->value(key) != target->value(key)) { qDebug() << "compareSettings: values do not match!" << key << settings->value(key) << target->value(key); return false; } } settings->endGroup(); target->endGroup(); } return true; } class TestSetupWizard : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void normal_install(); void cancel_install(); void skip_install(); void cli(); void version_too_low(); private: void helper_almost_normal_install(SetupDialog *setupWizard); }; void TestSetupWizard::initTestCase() { QCoreApplication::setOrganizationName(TEST_NAME); IF_NOT_VISUAL { // Use a custom message handler to filter out unwanted messages orig_message_handler = qInstallMessageHandler(offscreenMessageOutput); } } void TestSetupWizard::cleanupTestCase() { TSettings::destroy(); } void TestSetupWizard::helper_almost_normal_install(SetupDialog *setupWizard) { Ui::SetupDialog *ui = setupWizard->_ui; QSignalSpy sig_cli(setupWizard, SIGNAL(tarsnapVersionRequested())); QSignalSpy sig_register(setupWizard, SIGNAL(registerMachineRequested(QString, bool))); VISUAL_INIT(setupWizard); // Page 1 QVERIFY(setupWizard->pageTitle() == "Setup wizard"); setupWizard->next(); VISUAL_WAIT; // Page 2 QVERIFY(setupWizard->pageTitle() == "Command-line utilities"); QVERIFY(sig_cli.count() == 1); // Fake the CLI detection and checking setupWizard->tarsnapVersionResponse(TaskStatus::Completed, "X.Y.Z"); QVERIFY(ui->cliValidationLabel->text().contains("Tarsnap CLI version")); setupWizard->next(); VISUAL_WAIT; // Page 3 QVERIFY(setupWizard->pageTitle() == "Register with server"); // Pretend that we already have a key setupWizard->useExistingKeyfile(); ui->useExistingKeyfileButton->setChecked(true); ui->machineKeyCombo->setCurrentText("fake.key"); ui->nextButton->setEnabled(true); setupWizard->next(); // Check results of registration QVERIFY(sig_register.count() == 1); setupWizard->registerMachineResponse(TaskStatus::Completed, ""); VISUAL_WAIT; // Page 4 QVERIFY(setupWizard->pageTitle() == "Setup complete!"); VISUAL_WAIT; } void TestSetupWizard::normal_install() { TARSNAP_CLI_OR_SKIP; SetupDialog *setupWizard = new SetupDialog(); // Almost complete a normal install helper_almost_normal_install(setupWizard); // Finish the install setupWizard->next(); VISUAL_WAIT; // Check resulting init file. The first can be in any format (for now). TSettings settings; QSettings target("after-normal-install.conf", QSettings::IniFormat); QVERIFY(compareSettings(settings.getQSettings(), &target)); // Clean up delete setupWizard; } void TestSetupWizard::cancel_install() { TARSNAP_CLI_OR_SKIP; SetupDialog *setupWizard = new SetupDialog(); // Almost complete a normal install helper_almost_normal_install(setupWizard); // Close before we actually finish QTest::keyEvent(QTest::Click, setupWizard, Qt::Key_Escape); VISUAL_WAIT; // Clean up delete setupWizard; // Check that we wiped the Tarsnap-related settings TSettings settings; QSettings *q = settings.getQSettings(); q->beginGroup("tarsnap"); QVERIFY(q->allKeys().length() == 0); q->beginGroup("app"); QVERIFY(q->allKeys().length() == 0); } void TestSetupWizard::skip_install() { TARSNAP_CLI_OR_SKIP; SetupDialog * setupWizard = new SetupDialog(); Ui::SetupDialog *ui = setupWizard->_ui; // Almost complete a normal install helper_almost_normal_install(setupWizard); // Now go back to the beginning and skip the install setupWizard->back(); setupWizard->back(); setupWizard->back(); VISUAL_WAIT; QTest::mouseClick(ui->backButton, Qt::LeftButton); VISUAL_WAIT; // Check resulting init file. TSettings settings; QSettings target("after-skip-install.conf", QSettings::IniFormat); QVERIFY(compareSettings(settings.getQSettings(), &target)); // Clean up delete setupWizard; } void TestSetupWizard::cli() { SetupDialog * setupWizard = new SetupDialog(); Ui::SetupDialog *ui = setupWizard->_ui; QSignalSpy sig_cli(setupWizard, SIGNAL(tarsnapVersionRequested())); VISUAL_INIT(setupWizard); // Advance to CLI page and expand advanced options setupWizard->next(); QVERIFY(setupWizard->pageTitle() == "Command-line utilities"); ui->cliAdvancedButton->click(); VISUAL_WAIT; // App data directory SET_TEXT_WITH_SIGNAL(ui->appDataPathLineEdit, "fake-dir"); QVERIFY(ui->cliValidationLabel->text() == "Invalid App data directory set."); VISUAL_WAIT; SET_TEXT_WITH_SIGNAL(ui->appDataPathLineEdit, "/tmp"); // Cache directory SET_TEXT_WITH_SIGNAL(ui->tarsnapCacheLineEdit, "fake-dir"); QVERIFY(ui->cliValidationLabel->text() == "Invalid Tarsnap cache directory set."); VISUAL_WAIT; SET_TEXT_WITH_SIGNAL(ui->tarsnapCacheLineEdit, "/tmp"); // Tarsnap CLI directory SET_TEXT_WITH_SIGNAL(ui->tarsnapPathLineEdit, "fake-dir"); QVERIFY(ui->cliValidationLabel->text().contains( "Tarsnap utilities not found.")); VISUAL_WAIT; SET_TEXT_WITH_SIGNAL(ui->tarsnapPathLineEdit, "/tmp"); // Fake detecting the binaries setupWizard->tarsnapVersionResponse(TaskStatus::Completed, "X.Y.Z"); QVERIFY(ui->cliValidationLabel->text().contains("Tarsnap CLI version")); VISUAL_WAIT; delete setupWizard; } void TestSetupWizard::version_too_low() { SetupDialog * setupWizard = new SetupDialog(); Ui::SetupDialog *ui = setupWizard->_ui; VISUAL_INIT(setupWizard); // Advance to CLI page setupWizard->next(); QVERIFY(setupWizard->pageTitle() == "Command-line utilities"); VISUAL_WAIT; // Fake detecting the binaries with a too-low version number setupWizard->tarsnapVersionResponse(TaskStatus::VersionTooLow, "1.0.1"); QVERIFY(ui->cliValidationLabel->text().contains("too low")); QVERIFY(ui->nextButton->isEnabled() == false); // With platform=offscreen, ->isVisible() always returns false. // Instead, check the negation of ->isHidden() QVERIFY(ui->cliAdvancedWidget->isHidden() == false); VISUAL_WAIT; delete setupWizard; } QTEST_MAIN(TestSetupWizard) #include "test-setupwizard.moc" <|endoftext|>
<commit_before> #include "btree/modify_oper.hpp" #include "utils.hpp" #include <boost/shared_ptr.hpp> #include "buffer_cache/buf_lock.hpp" #include "buffer_cache/co_functions.hpp" #include "btree/leaf_node.hpp" #include "btree/internal_node.hpp" #include "buffer_cache/co_functions.hpp" #include "slice.hpp" // TODO: consider B#/B* trees to improve space efficiency // TODO: perhaps allow memory reclamation due to oversplitting? We can // be smart and only use a limited amount of ram for incomplete nodes // (doing this efficiently very tricky for high insert // workloads). Also, if the serializer is log-structured, we can write // only a small part of each node. // TODO: change rwi_write to rwi_intent followed by rwi_upgrade where // relevant. void insert_root(block_id_t root_id, buf_lock_t& sb_buf) { rassert(sb_buf.is_acquired()); sb_buf->set_data(const_cast<block_id_t *>(&ptr_cast<btree_superblock_t>(sb_buf->get_data_read())->root_block), &root_id, sizeof(root_id)); sb_buf.release(); } // Split the node if necessary. If the node is a leaf_node, provide the new // value that will be inserted; if it's an internal node, provide NULL (we // split internal nodes proactively). void check_and_handle_split(transaction_t& txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, btree_value_t *new_value, block_size_t block_size) { txn.assert_thread(); const node_t *node = ptr_cast<node_t>(buf->get_data_read()); // If the node isn't full, we don't need to split, so we're done. if (node::is_leaf(node)) { // This should only be called when update_needed. rassert(new_value); if (!leaf::is_full(txn.get_cache()->get_block_size(), ptr_cast<leaf_node_t>(node), key, new_value)) return; } else { rassert(!new_value); if (!internal_node::is_full(ptr_cast<internal_node_t>(node))) return; } // Allocate a new node to split into, and some temporary memory to keep // track of the median key in the split; then actually split. buf_lock_t rbuf; rbuf.allocate(&txn); btree_key_buffer_t median_buffer; btree_key_t *median = median_buffer.key(); node::split(block_size, *buf.buf(), *rbuf.buf(), median); // Insert the key that sets the two nodes apart into the parent. if (!last_buf.is_acquired()) { // We're splitting what was previously the root, so create a new root to use as the parent. last_buf.allocate(&txn); internal_node::init(block_size, *last_buf.buf()); insert_root(last_buf->get_block_id(), sb_buf); } bool success __attribute__((unused)) = internal_node::insert(block_size, *last_buf.buf(), median, buf->get_block_id(), rbuf->get_block_id()); rassert(success, "could not insert internal btree node"); // We've split the node; now figure out where the key goes and release the other buf (since we're done with it). if (0 >= sized_strcmp(key->contents, key->size, median->contents, median->size)) { // The key goes in the old buf (the left one). // Do nothing. } else { // The key goes in the new buf (the right one). buf.swap(rbuf); } } // Merge or level the node if necessary. void check_and_handle_underfull(transaction_t& txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, block_size_t block_size) { const node_t *node = ptr_cast<node_t>(buf->get_data_read()); if (last_buf.is_acquired() && node::is_underfull(block_size, node)) { // The root node is never underfull. const internal_node_t *parent_node = ptr_cast<internal_node_t>(last_buf->get_data_read()); // Acquire a sibling to merge or level with. block_id_t sib_node_id; int nodecmp_node_with_sib = internal_node::sibling(parent_node, key, &sib_node_id); // Now decide whether to merge or level. buf_lock_t sib_buf(&txn, sib_node_id, rwi_write); const node_t *sib_node = ptr_cast<node_t>(sib_buf->get_data_read()); #ifndef NDEBUG node::validate(block_size, sib_node); #endif if (node::is_mergable(block_size, node, sib_node, parent_node)) { // Merge. // This is the key that we remove. btree_key_buffer_t key_to_remove_buffer; btree_key_t *key_to_remove = key_to_remove_buffer.key(); if (nodecmp_node_with_sib < 0) { // Nodes must be passed to merge in ascending order. node::merge(block_size, node, *sib_buf.buf(), key_to_remove, parent_node); buf->mark_deleted(); buf.swap(sib_buf); } else { node::merge(block_size, sib_node, *buf.buf(), key_to_remove, parent_node); sib_buf->mark_deleted(); } sib_buf.release(); if (!internal_node::is_singleton(parent_node)) { internal_node::remove(block_size, *last_buf.buf(), key_to_remove); } else { // The parent has only 1 key after the merge (which means that // it's the root and our node is its only child). Insert our // node as the new root. last_buf->mark_deleted(); insert_root(buf->get_block_id(), sb_buf); } } else { // Level btree_key_buffer_t key_to_replace_buffer, replacement_key_buffer; btree_key_t *key_to_replace = key_to_replace_buffer.key(); btree_key_t *replacement_key = replacement_key_buffer.key(); bool leveled = node::level(block_size, *buf.buf(), *sib_buf.buf(), key_to_replace, replacement_key, parent_node); if (leveled) { internal_node::update_key(*last_buf.buf(), key_to_replace, replacement_key); } } } } // Get a root block given a superblock, or make a new root if there isn't one. void get_root(transaction_t& txn, buf_lock_t& sb_buf, block_size_t block_size, buf_lock_t *buf_out, repli_timestamp timestamp) { rassert(!buf_out->is_acquired()); block_id_t node_id = reinterpret_cast<const btree_superblock_t*>(sb_buf->get_data_read())->root_block; if (node_id != NULL_BLOCK_ID) { buf_lock_t tmp(&txn, node_id, rwi_write); buf_out->swap(tmp); } else { buf_out->allocate(&txn); leaf::init(block_size, *buf_out->buf(), timestamp); insert_root(buf_out->buf()->get_block_id(), sb_buf); } } // Runs a btree_modify_oper_t. void run_btree_modify_oper(btree_modify_oper_t *oper, btree_slice_t *slice, const store_key_t &store_key, castime_t castime, order_token_t token) { scoped_malloc<btree_value_t> the_value(MAX_BTREE_VALUE_SIZE); btree_key_buffer_t kbuffer(store_key); btree_key_t *key = kbuffer.key(); oper->slice = slice; // TODO: Figure out a way to do this more nicely -- it's only used for generating a CAS value. block_size_t block_size = slice->cache()->get_block_size(); { slice->assert_thread(); slice->pre_begin_transaction_sink_.check_out(token); order_token_t begin_transaction_token = slice->pre_begin_transaction_write_mode_source_.check_in(token.tag() + "+begin_transaction_token"); // TODO: why is this a shared_ptr? boost::shared_ptr<transaction_t> txn(new transaction_t(slice->cache(), rwi_write, oper->compute_expected_change_count(slice->cache()->get_block_size().value()), castime.timestamp)); slice->post_begin_transaction_sink_.check_out(begin_transaction_token); txn->set_token(slice->post_begin_transaction_source_.check_in(token.tag() + "+post")); buf_lock_t sb_buf(txn.get(), SUPERBLOCK_ID, rwi_write); // TODO: do_superblock_sidequest is blocking. It doesn't have // to be, but when you fix this, make sure the superblock // sidequest is done using the superblock before the // superblock gets released. oper->do_superblock_sidequest(txn, sb_buf, castime.timestamp, &store_key); buf_lock_t last_buf; buf_lock_t buf; get_root(*txn, sb_buf, block_size, &buf, castime.timestamp); // Walk down the tree to the leaf. while (node::is_internal(ptr_cast<node_t>(buf->get_data_read()))) { // Check if the node is overfull and proactively split it if it is (since this is an internal node). check_and_handle_split(*txn, buf, last_buf, sb_buf, key, NULL, block_size); // Check if the node is underfull, and merge/level if it is. check_and_handle_underfull(*txn, buf, last_buf, sb_buf, key, block_size); // Release the superblock, if we've gone past the root (and haven't // already released it). If we're still at the root or at one of // its direct children, we might still want to replace the root, so // we can't release the superblock yet. if (sb_buf.is_acquired() && last_buf.is_acquired()) { sb_buf.release(); } // Release the old previous node (unless we're at the root), and set // the next previous node (which is the current node). // Look up and acquire the next node. block_id_t node_id = internal_node::lookup(ptr_cast<internal_node_t>(buf->get_data_read()), key); rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID); buf_lock_t tmp(txn.get(), node_id, rwi_write); last_buf.swap(tmp); buf.swap(last_buf); } // We've gone down the tree and gotten to a leaf. Now look up the key. bool key_found = leaf::lookup(block_size, ptr_cast<leaf_node_t>(buf->get_data_read()), key, the_value.get()); bool expired = key_found && the_value->expired(); if (expired) key_found = false; // If the value's expired, delet it. if (expired) { blob_t b(block_size, the_value->value_ref(), blob::btree_maxreflen); b.unappend_region(txn.get(), b.valuesize()); the_value.reset(); } bool update_needed = oper->operate(txn, the_value); // If the value is expired and operate() decided not to make any // change, we'll silently delete the key. if (!update_needed && expired) { rassert(!the_value); update_needed = true; } // Actually update the leaf, if needed. if (update_needed) { if (the_value) { // We have a value to insert. // Split the node if necessary, to make sure that we have room // for the value; This isn't necessary when we're deleting, // because the node isn't going to grow. check_and_handle_split(*txn, buf, last_buf, sb_buf, key, the_value.get(), block_size); // Add a CAS to the value if necessary (this won't change its size). if (the_value->has_cas()) { rassert(castime.proposed_cas != BTREE_MODIFY_OPER_DUMMY_PROPOSED_CAS); the_value->set_cas(block_size, castime.proposed_cas); } repli_timestamp new_value_timestamp = castime.timestamp; bool success = leaf::insert(block_size, *buf.buf(), key, the_value.get(), new_value_timestamp); guarantee(success, "could not insert leaf btree node"); } else { // Delete the value if it's there. if (key_found || expired) { leaf::remove(block_size, *buf.buf(), key); } else { // operate() told us to delete a value (update_needed && !the_value), but the // key wasn't in the node (!key_found && !expired), so we do nothing. } } // XXX: Previously this was checked whether or not update_needed, // but I'm pretty sure a leaf node can only be underfull // immediately following a split or an update. Double check this. // Check to see if the leaf is underfull (following a change in // size or a deletion), and merge/level if it is. check_and_handle_underfull(*txn, buf, last_buf, sb_buf, key, block_size); } // Release bufs as necessary. sb_buf.release_if_acquired(); rassert(buf.is_acquired()); buf.release(); last_buf.release_if_acquired(); // Committing the transaction and moving back to the home thread are // handled automatically with RAII. } } <commit_msg>Fixed valgrind error that occurred because we did not initialize the_value in modify oper.<commit_after> #include "btree/modify_oper.hpp" #include "utils.hpp" #include <boost/shared_ptr.hpp> #include "buffer_cache/buf_lock.hpp" #include "buffer_cache/co_functions.hpp" #include "btree/leaf_node.hpp" #include "btree/internal_node.hpp" #include "buffer_cache/co_functions.hpp" #include "slice.hpp" // TODO: consider B#/B* trees to improve space efficiency // TODO: perhaps allow memory reclamation due to oversplitting? We can // be smart and only use a limited amount of ram for incomplete nodes // (doing this efficiently very tricky for high insert // workloads). Also, if the serializer is log-structured, we can write // only a small part of each node. // TODO: change rwi_write to rwi_intent followed by rwi_upgrade where // relevant. void insert_root(block_id_t root_id, buf_lock_t& sb_buf) { rassert(sb_buf.is_acquired()); sb_buf->set_data(const_cast<block_id_t *>(&ptr_cast<btree_superblock_t>(sb_buf->get_data_read())->root_block), &root_id, sizeof(root_id)); sb_buf.release(); } // Split the node if necessary. If the node is a leaf_node, provide the new // value that will be inserted; if it's an internal node, provide NULL (we // split internal nodes proactively). void check_and_handle_split(transaction_t& txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, btree_value_t *new_value, block_size_t block_size) { txn.assert_thread(); const node_t *node = ptr_cast<node_t>(buf->get_data_read()); // If the node isn't full, we don't need to split, so we're done. if (node::is_leaf(node)) { // This should only be called when update_needed. rassert(new_value); if (!leaf::is_full(txn.get_cache()->get_block_size(), ptr_cast<leaf_node_t>(node), key, new_value)) return; } else { rassert(!new_value); if (!internal_node::is_full(ptr_cast<internal_node_t>(node))) return; } // Allocate a new node to split into, and some temporary memory to keep // track of the median key in the split; then actually split. buf_lock_t rbuf; rbuf.allocate(&txn); btree_key_buffer_t median_buffer; btree_key_t *median = median_buffer.key(); node::split(block_size, *buf.buf(), *rbuf.buf(), median); // Insert the key that sets the two nodes apart into the parent. if (!last_buf.is_acquired()) { // We're splitting what was previously the root, so create a new root to use as the parent. last_buf.allocate(&txn); internal_node::init(block_size, *last_buf.buf()); insert_root(last_buf->get_block_id(), sb_buf); } bool success __attribute__((unused)) = internal_node::insert(block_size, *last_buf.buf(), median, buf->get_block_id(), rbuf->get_block_id()); rassert(success, "could not insert internal btree node"); // We've split the node; now figure out where the key goes and release the other buf (since we're done with it). if (0 >= sized_strcmp(key->contents, key->size, median->contents, median->size)) { // The key goes in the old buf (the left one). // Do nothing. } else { // The key goes in the new buf (the right one). buf.swap(rbuf); } } // Merge or level the node if necessary. void check_and_handle_underfull(transaction_t& txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, block_size_t block_size) { const node_t *node = ptr_cast<node_t>(buf->get_data_read()); if (last_buf.is_acquired() && node::is_underfull(block_size, node)) { // The root node is never underfull. const internal_node_t *parent_node = ptr_cast<internal_node_t>(last_buf->get_data_read()); // Acquire a sibling to merge or level with. block_id_t sib_node_id; int nodecmp_node_with_sib = internal_node::sibling(parent_node, key, &sib_node_id); // Now decide whether to merge or level. buf_lock_t sib_buf(&txn, sib_node_id, rwi_write); const node_t *sib_node = ptr_cast<node_t>(sib_buf->get_data_read()); #ifndef NDEBUG node::validate(block_size, sib_node); #endif if (node::is_mergable(block_size, node, sib_node, parent_node)) { // Merge. // This is the key that we remove. btree_key_buffer_t key_to_remove_buffer; btree_key_t *key_to_remove = key_to_remove_buffer.key(); if (nodecmp_node_with_sib < 0) { // Nodes must be passed to merge in ascending order. node::merge(block_size, node, *sib_buf.buf(), key_to_remove, parent_node); buf->mark_deleted(); buf.swap(sib_buf); } else { node::merge(block_size, sib_node, *buf.buf(), key_to_remove, parent_node); sib_buf->mark_deleted(); } sib_buf.release(); if (!internal_node::is_singleton(parent_node)) { internal_node::remove(block_size, *last_buf.buf(), key_to_remove); } else { // The parent has only 1 key after the merge (which means that // it's the root and our node is its only child). Insert our // node as the new root. last_buf->mark_deleted(); insert_root(buf->get_block_id(), sb_buf); } } else { // Level btree_key_buffer_t key_to_replace_buffer, replacement_key_buffer; btree_key_t *key_to_replace = key_to_replace_buffer.key(); btree_key_t *replacement_key = replacement_key_buffer.key(); bool leveled = node::level(block_size, *buf.buf(), *sib_buf.buf(), key_to_replace, replacement_key, parent_node); if (leveled) { internal_node::update_key(*last_buf.buf(), key_to_replace, replacement_key); } } } } // Get a root block given a superblock, or make a new root if there isn't one. void get_root(transaction_t& txn, buf_lock_t& sb_buf, block_size_t block_size, buf_lock_t *buf_out, repli_timestamp timestamp) { rassert(!buf_out->is_acquired()); block_id_t node_id = reinterpret_cast<const btree_superblock_t*>(sb_buf->get_data_read())->root_block; if (node_id != NULL_BLOCK_ID) { buf_lock_t tmp(&txn, node_id, rwi_write); buf_out->swap(tmp); } else { buf_out->allocate(&txn); leaf::init(block_size, *buf_out->buf(), timestamp); insert_root(buf_out->buf()->get_block_id(), sb_buf); } } // Runs a btree_modify_oper_t. void run_btree_modify_oper(btree_modify_oper_t *oper, btree_slice_t *slice, const store_key_t &store_key, castime_t castime, order_token_t token) { scoped_malloc<btree_value_t> the_value(MAX_BTREE_VALUE_SIZE); memset(the_value.get(), 0, MAX_BTREE_VALUE_SIZE); btree_key_buffer_t kbuffer(store_key); btree_key_t *key = kbuffer.key(); oper->slice = slice; // TODO: Figure out a way to do this more nicely -- it's only used for generating a CAS value. block_size_t block_size = slice->cache()->get_block_size(); { slice->assert_thread(); slice->pre_begin_transaction_sink_.check_out(token); order_token_t begin_transaction_token = slice->pre_begin_transaction_write_mode_source_.check_in(token.tag() + "+begin_transaction_token"); // TODO: why is this a shared_ptr? boost::shared_ptr<transaction_t> txn(new transaction_t(slice->cache(), rwi_write, oper->compute_expected_change_count(slice->cache()->get_block_size().value()), castime.timestamp)); slice->post_begin_transaction_sink_.check_out(begin_transaction_token); txn->set_token(slice->post_begin_transaction_source_.check_in(token.tag() + "+post")); buf_lock_t sb_buf(txn.get(), SUPERBLOCK_ID, rwi_write); // TODO: do_superblock_sidequest is blocking. It doesn't have // to be, but when you fix this, make sure the superblock // sidequest is done using the superblock before the // superblock gets released. oper->do_superblock_sidequest(txn, sb_buf, castime.timestamp, &store_key); buf_lock_t last_buf; buf_lock_t buf; get_root(*txn, sb_buf, block_size, &buf, castime.timestamp); // Walk down the tree to the leaf. while (node::is_internal(ptr_cast<node_t>(buf->get_data_read()))) { // Check if the node is overfull and proactively split it if it is (since this is an internal node). check_and_handle_split(*txn, buf, last_buf, sb_buf, key, NULL, block_size); // Check if the node is underfull, and merge/level if it is. check_and_handle_underfull(*txn, buf, last_buf, sb_buf, key, block_size); // Release the superblock, if we've gone past the root (and haven't // already released it). If we're still at the root or at one of // its direct children, we might still want to replace the root, so // we can't release the superblock yet. if (sb_buf.is_acquired() && last_buf.is_acquired()) { sb_buf.release(); } // Release the old previous node (unless we're at the root), and set // the next previous node (which is the current node). // Look up and acquire the next node. block_id_t node_id = internal_node::lookup(ptr_cast<internal_node_t>(buf->get_data_read()), key); rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID); buf_lock_t tmp(txn.get(), node_id, rwi_write); last_buf.swap(tmp); buf.swap(last_buf); } // We've gone down the tree and gotten to a leaf. Now look up the key. bool key_found = leaf::lookup(block_size, ptr_cast<leaf_node_t>(buf->get_data_read()), key, the_value.get()); bool expired = key_found && the_value->expired(); if (expired) key_found = false; // If the value's expired, delet it. if (expired) { blob_t b(block_size, the_value->value_ref(), blob::btree_maxreflen); b.unappend_region(txn.get(), b.valuesize()); the_value.reset(); } bool update_needed = oper->operate(txn, the_value); // If the value is expired and operate() decided not to make any // change, we'll silently delete the key. if (!update_needed && expired) { rassert(!the_value); update_needed = true; } // Actually update the leaf, if needed. if (update_needed) { if (the_value) { // We have a value to insert. // Split the node if necessary, to make sure that we have room // for the value; This isn't necessary when we're deleting, // because the node isn't going to grow. check_and_handle_split(*txn, buf, last_buf, sb_buf, key, the_value.get(), block_size); // Add a CAS to the value if necessary (this won't change its size). if (the_value->has_cas()) { rassert(castime.proposed_cas != BTREE_MODIFY_OPER_DUMMY_PROPOSED_CAS); the_value->set_cas(block_size, castime.proposed_cas); } repli_timestamp new_value_timestamp = castime.timestamp; bool success = leaf::insert(block_size, *buf.buf(), key, the_value.get(), new_value_timestamp); guarantee(success, "could not insert leaf btree node"); } else { // Delete the value if it's there. if (key_found || expired) { leaf::remove(block_size, *buf.buf(), key); } else { // operate() told us to delete a value (update_needed && !the_value), but the // key wasn't in the node (!key_found && !expired), so we do nothing. } } // XXX: Previously this was checked whether or not update_needed, // but I'm pretty sure a leaf node can only be underfull // immediately following a split or an update. Double check this. // Check to see if the leaf is underfull (following a change in // size or a deletion), and merge/level if it is. check_and_handle_underfull(*txn, buf, last_buf, sb_buf, key, block_size); } // Release bufs as necessary. sb_buf.release_if_acquired(); rassert(buf.is_acquired()); buf.release(); last_buf.release_if_acquired(); // Committing the transaction and moving back to the home thread are // handled automatically with RAII. } } <|endoftext|>
<commit_before>/** * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashGraph. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <signal.h> #ifdef PROFILER #include <google/profiler.h> #endif #include <vector> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" edge_type traverse_edge = edge_type::OUT_EDGE; class bfs_vertex: public compute_directed_vertex { bool visited; public: bfs_vertex(vertex_id_t id): compute_directed_vertex(id) { visited = false; } bool has_visited() const { return visited; } bool set_visited(bool visited) { this->visited = visited; } void run(vertex_program &prog) { if (!has_visited()) { directed_vertex_request req(get_id(), traverse_edge); request_partial_vertices(&req, 1); } } void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &prog, const vertex_message &msg) { } }; void bfs_vertex::run(vertex_program &prog, const page_vertex &vertex) { assert(!has_visited()); set_visited(true); int num_dests = vertex.get_num_edges(traverse_edge); if (num_dests == 0) return; // We need to add the neighbors of the vertex to the queue of // the next level. #ifdef USE_ARRAY stack_array<vertex_id_t, 1024> neighs(num_dests); vertex.read_edges(traverse_edge, neighs.data(), num_dests); prog.activate_vertices(neighs.data(), num_dests); #else edge_seq_iterator it = vertex.get_neigh_seq_it(traverse_edge, 0, num_dests); prog.activate_vertices(it); #endif } class count_vertex_query: public vertex_query { size_t num_visited; public: count_vertex_query() { num_visited = 0; } virtual void run(graph_engine &graph, compute_vertex &v) { bfs_vertex &bfs_v = (bfs_vertex &) v; if (bfs_v.has_visited()) num_visited++; } virtual void merge(graph_engine &graph, vertex_query::ptr q) { count_vertex_query *cvq = (count_vertex_query *) q.get(); num_visited += cvq->num_visited; } virtual ptr clone() { return vertex_query::ptr(new count_vertex_query()); } size_t get_num_visited() const { return num_visited; } }; void int_handler(int sig_num) { #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif exit(0); } void print_usage() { fprintf(stderr, "bfs [options] conf_file graph_file index_file start_vertex\n"); fprintf(stderr, "-c confs: add more configurations to the system\n"); fprintf(stderr, "-b: traverse with both in-edges and out-edges\n"); graph_conf.print_help(); params.print_help(); } int main(int argc, char *argv[]) { int opt; std::string confs; int num_opts = 0; while ((opt = getopt(argc, argv, "c:b")) != -1) { num_opts++; switch (opt) { case 'c': confs = optarg; num_opts++; break; case 'b': traverse_edge = edge_type::BOTH_EDGES; break; default: print_usage(); } } argv += 1 + num_opts; argc -= 1 + num_opts; if (argc < 4) { print_usage(); exit(-1); } std::string conf_file = argv[0]; std::string graph_file = argv[1]; std::string index_file = argv[2]; vertex_id_t start_vertex = atoi(argv[3]); config_map configs(conf_file); configs.add_options(confs); signal(SIGINT, int_handler); graph_index::ptr index = NUMA_graph_index<bfs_vertex>::create(index_file); graph_engine::ptr graph = graph_engine::create(graph_file, index, configs); printf("BFS starts\n"); printf("prof_file: %s\n", graph_conf.get_prof_file().c_str()); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); #endif struct timeval start, end; gettimeofday(&start, NULL); graph->start(&start_vertex, 1); graph->wait4complete(); gettimeofday(&end, NULL); vertex_query::ptr cvq(new count_vertex_query()); graph->query_on_all(cvq); size_t num_visited = ((count_vertex_query *) cvq.get())->get_num_visited(); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif printf("BFS from vertex %ld visits %ld vertices. It takes %f seconds\n", (unsigned long) start_vertex, num_visited, time_diff(start, end)); } <commit_msg>[Graph]: simplify bfs 2.<commit_after>/** * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashGraph. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <signal.h> #ifdef PROFILER #include <google/profiler.h> #endif #include <vector> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" edge_type traverse_edge = edge_type::OUT_EDGE; class bfs_vertex: public compute_directed_vertex { bool visited; public: bfs_vertex(vertex_id_t id): compute_directed_vertex(id) { visited = false; } bool has_visited() const { return visited; } void set_visited(bool visited) { this->visited = visited; } void run(vertex_program &prog) { if (!has_visited()) { directed_vertex_request req(get_id(), traverse_edge); request_partial_vertices(&req, 1); } } void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &prog, const vertex_message &msg) { } }; void bfs_vertex::run(vertex_program &prog, const page_vertex &vertex) { assert(!has_visited()); set_visited(true); int num_dests = vertex.get_num_edges(traverse_edge); if (num_dests == 0) return; // We need to add the neighbors of the vertex to the queue of // the next level. #ifdef USE_ARRAY stack_array<vertex_id_t, 1024> neighs(num_dests); vertex.read_edges(traverse_edge, neighs.data(), num_dests); prog.activate_vertices(neighs.data(), num_dests); #else edge_seq_iterator it = vertex.get_neigh_seq_it(traverse_edge, 0, num_dests); prog.activate_vertices(it); #endif } class count_vertex_query: public vertex_query { size_t num_visited; public: count_vertex_query() { num_visited = 0; } virtual void run(graph_engine &graph, compute_vertex &v) { bfs_vertex &bfs_v = (bfs_vertex &) v; if (bfs_v.has_visited()) num_visited++; } virtual void merge(graph_engine &graph, vertex_query::ptr q) { count_vertex_query *cvq = (count_vertex_query *) q.get(); num_visited += cvq->num_visited; } virtual ptr clone() { return vertex_query::ptr(new count_vertex_query()); } size_t get_num_visited() const { return num_visited; } }; void int_handler(int sig_num) { #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif exit(0); } void print_usage() { fprintf(stderr, "bfs [options] conf_file graph_file index_file start_vertex\n"); fprintf(stderr, "-c confs: add more configurations to the system\n"); fprintf(stderr, "-b: traverse with both in-edges and out-edges\n"); graph_conf.print_help(); params.print_help(); } int main(int argc, char *argv[]) { int opt; std::string confs; int num_opts = 0; while ((opt = getopt(argc, argv, "c:b")) != -1) { num_opts++; switch (opt) { case 'c': confs = optarg; num_opts++; break; case 'b': traverse_edge = edge_type::BOTH_EDGES; break; default: print_usage(); } } argv += 1 + num_opts; argc -= 1 + num_opts; if (argc < 4) { print_usage(); exit(-1); } std::string conf_file = argv[0]; std::string graph_file = argv[1]; std::string index_file = argv[2]; vertex_id_t start_vertex = atoi(argv[3]); config_map configs(conf_file); configs.add_options(confs); signal(SIGINT, int_handler); graph_index::ptr index = NUMA_graph_index<bfs_vertex>::create(index_file); graph_engine::ptr graph = graph_engine::create(graph_file, index, configs); printf("BFS starts\n"); printf("prof_file: %s\n", graph_conf.get_prof_file().c_str()); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); #endif struct timeval start, end; gettimeofday(&start, NULL); graph->start(&start_vertex, 1); graph->wait4complete(); gettimeofday(&end, NULL); vertex_query::ptr cvq(new count_vertex_query()); graph->query_on_all(cvq); size_t num_visited = ((count_vertex_query *) cvq.get())->get_num_visited(); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif printf("BFS from vertex %ld visits %ld vertices. It takes %f seconds\n", (unsigned long) start_vertex, num_visited, time_diff(start, end)); } <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "btree/operations.hpp" #include "btree/internal_node.hpp" #include "btree/leaf_node.hpp" #include "btree/node.hpp" #include "btree/slice.hpp" #include "buffer_cache/alt/alt.hpp" #include "concurrency/promise.hpp" #include "rdb_protocol/profile.hpp" // TODO: consider B#/B* trees to improve space efficiency /* Passing in a pass_back_superblock parameter will cause this function to * return the superblock after it's no longer needed (rather than releasing * it). Notice the superblock is not guaranteed to be returned until the * keyvalue_location_t that's passed in (keyvalue_location_out) is destroyed. * This is because it may need to use the superblock for some of its methods. * */ // KSI: It seems like really we should pass the superblock_t via rvalue reference. // Is that possible? (promise_t makes it hard.) template <class Value> void find_keyvalue_location_for_write( superblock_t *superblock, const btree_key_t *key, keyvalue_location_t<Value> *keyvalue_location_out, btree_stats_t *stats, profile::trace_t *trace, promise_t<superblock_t *> *pass_back_superblock = NULL) { value_sizer_t<Value> sizer(superblock->expose_buf().cache()->max_block_size()); keyvalue_location_out->superblock = superblock; keyvalue_location_out->pass_back_superblock = pass_back_superblock; ensure_stat_block(superblock); keyvalue_location_out->stat_block = keyvalue_location_out->superblock->get_stat_block_id(); keyvalue_location_out->stats = stats; // KSI: Make sure we do the logic smart here -- don't needlessly hold both // buffers. (This finds the keyvalue for _write_ so that probably won't really // happen.) buf_lock_t last_buf; buf_lock_t buf; { // RSI: We can't acquire the block for write here -- we could, but it would // worsen the performance of the program -- sometimes we only end up using // this block for read. So the profiling information is not very good. profile::starter_t starter("Acquiring block for write.\n", trace); buf = get_root(&sizer, superblock); } // Walk down the tree to the leaf. for (;;) { { buf_read_t read(&buf); if (!node::is_internal(static_cast<const node_t *>(read.get_data_read()))) { break; } } // Check if the node is overfull and proactively split it if it is (since this is an internal node). { profile::starter_t starter("Perhaps split node.", trace); check_and_handle_split(&sizer, &buf, &last_buf, superblock, key, static_cast<Value *>(NULL)); } // Check if the node is underfull, and merge/level if it is. { profile::starter_t starter("Perhaps merge nodes.", trace); check_and_handle_underfull(&sizer, &buf, &last_buf, superblock, key); } // Release the superblock, if we've gone past the root (and haven't // already released it). If we're still at the root or at one of // its direct children, we might still want to replace the root, so // we can't release the superblock yet. if (!last_buf.empty() && keyvalue_location_out->superblock) { if (pass_back_superblock != NULL) { pass_back_superblock->pulse(superblock); keyvalue_location_out->superblock = NULL; } else { keyvalue_location_out->superblock->release(); keyvalue_location_out->superblock = NULL; } } // Release the old previous node (unless we're at the root), and set // the next previous node (which is the current node). last_buf.reset_buf_lock(); // Look up and acquire the next node. block_id_t node_id; { buf_read_t read(&buf); auto node = static_cast<const internal_node_t *>(read.get_data_read()); node_id = internal_node::lookup(node, key); } rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID); { profile::starter_t starter("Acquiring block for write.\n", trace); buf_lock_t tmp(&buf, node_id, access_t::write); last_buf = std::move(buf); buf = std::move(tmp); } } { scoped_malloc_t<Value> tmp(sizer.max_possible_size()); // We've gone down the tree and gotten to a leaf. Now look up the key. buf_read_t read(&buf); auto node = static_cast<const leaf_node_t *>(read.get_data_read()); bool key_found = leaf::lookup(&sizer, node, key, tmp.get()); if (key_found) { keyvalue_location_out->there_originally_was_value = true; keyvalue_location_out->value = std::move(tmp); } } keyvalue_location_out->last_buf.swap(last_buf); keyvalue_location_out->buf.swap(buf); } template <class Value> void find_keyvalue_location_for_read( superblock_t *superblock, const btree_key_t *key, keyvalue_location_t<Value> *keyvalue_location_out, btree_stats_t *stats, profile::trace_t *trace) { stats->pm_keys_read.record(); value_sizer_t<Value> sizer(superblock->expose_buf().cache()->max_block_size()); const block_id_t root_id = superblock->get_root_block_id(); rassert(root_id != SUPERBLOCK_ID); if (root_id == NULL_BLOCK_ID) { // There is no root, so the tree is empty. superblock->release(); return; } buf_lock_t buf; { profile::starter_t starter("Acquire a block for read.", trace); buf_lock_t tmp(superblock->expose_buf(), root_id, access_t::read); superblock->release(); buf = std::move(tmp); } #ifndef NDEBUG { buf_read_t read(&buf); node::validate(&sizer, static_cast<const node_t *>(read.get_data_read())); } #endif // NDEBUG for (;;) { { buf_read_t read(&buf); if (!node::is_internal(static_cast<const node_t *>(read.get_data_read()))) { break; } } block_id_t node_id; { buf_read_t read(&buf); const internal_node_t *node = static_cast<const internal_node_t *>(read.get_data_read()); node_id = internal_node::lookup(node, key); } rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID); { profile::starter_t starter("Acquire a block for read.", trace); buf_lock_t tmp(&buf, node_id, access_t::read); buf.reset_buf_lock(); buf = std::move(tmp); } #ifndef NDEBUG { buf_read_t read(&buf); node::validate(&sizer, static_cast<const node_t *>(read.get_data_read())); } #endif // NDEBUG } // Got down to the leaf, now probe it. scoped_malloc_t<Value> value(sizer.max_possible_size()); bool value_found; { buf_read_t read(&buf); const leaf_node_t *leaf = static_cast<const leaf_node_t *>(read.get_data_read()); value_found = leaf::lookup(&sizer, leaf, key, value.get()); } if (value_found) { keyvalue_location_out->buf = std::move(buf); keyvalue_location_out->there_originally_was_value = true; keyvalue_location_out->value = std::move(value); } } enum class expired_t { NO, YES }; template <class Value> void apply_keyvalue_change(keyvalue_location_t<Value> *kv_loc, const btree_key_t *key, repli_timestamp_t tstamp, expired_t expired, key_modification_callback_t<Value> *km_callback) { value_sizer_t<Value> sizer(kv_loc->buf.cache()->get_block_size()); key_modification_proof_t km_proof = km_callback->value_modification(kv_loc, key); /* how much this keyvalue change affects the total population of the btree * (should be -1, 0 or 1) */ int population_change; if (kv_loc->value.has()) { // We have a value to insert. // Split the node if necessary, to make sure that we have room // for the value. Not necessary when deleting, because the // node won't grow. check_and_handle_split(&sizer, &kv_loc->buf, &kv_loc->last_buf, kv_loc->superblock, key, kv_loc->value.get()); { #ifndef NDEBUG buf_read_t read(&kv_loc->buf); auto leaf_node = static_cast<const leaf_node_t *>(read.get_data_read()); rassert(!leaf::is_full(&sizer, leaf_node, key, kv_loc->value.get())); #endif } if (kv_loc->there_originally_was_value) { population_change = 0; } else { population_change = 1; } { buf_write_t write(&kv_loc->buf); auto leaf_node = static_cast<leaf_node_t *>(write.get_data_write()); leaf::insert(&sizer, leaf_node, key, kv_loc->value.get(), tstamp, km_proof); } kv_loc->stats->pm_keys_set.record(); } else { // Delete the value if it's there. if (kv_loc->there_originally_was_value) { if (expired == expired_t::NO) { rassert(tstamp != repli_timestamp_t::invalid, "Deletes need a valid timestamp now."); { buf_write_t write(&kv_loc->buf); auto leaf_node = static_cast<leaf_node_t *>(write.get_data_write()); leaf::remove(&sizer, leaf_node, key, tstamp, km_proof); } population_change = -1; kv_loc->stats->pm_keys_set.record(); } else { // TODO: Oh god oh god get rid of "expired". // Expirations do an erase, not a delete. { buf_write_t write(&kv_loc->buf); auto leaf_node = static_cast<leaf_node_t *>(write.get_data_write()); leaf::erase_presence(&sizer, leaf_node, key, km_proof); } population_change = 0; kv_loc->stats->pm_keys_expired.record(); } } else { population_change = 0; } } // Check to see if the leaf is underfull (following a change in // size or a deletion, and merge/level if it is. check_and_handle_underfull(&sizer, &kv_loc->buf, &kv_loc->last_buf, kv_loc->superblock, key); // Modify the stats block. buf_lock_t stat_block(buf_parent_t(&kv_loc->buf.txn()), kv_loc->stat_block, access_t::write); buf_write_t stat_block_write(&stat_block); auto stat_block_buf = static_cast<btree_statblock_t *>(stat_block_write.get_data_write()); stat_block_buf->population += population_change; } <commit_msg>Changed RSI about profiling information to a KSI.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "btree/operations.hpp" #include "btree/internal_node.hpp" #include "btree/leaf_node.hpp" #include "btree/node.hpp" #include "btree/slice.hpp" #include "buffer_cache/alt/alt.hpp" #include "concurrency/promise.hpp" #include "rdb_protocol/profile.hpp" // TODO: consider B#/B* trees to improve space efficiency /* Passing in a pass_back_superblock parameter will cause this function to * return the superblock after it's no longer needed (rather than releasing * it). Notice the superblock is not guaranteed to be returned until the * keyvalue_location_t that's passed in (keyvalue_location_out) is destroyed. * This is because it may need to use the superblock for some of its methods. * */ // KSI: It seems like really we should pass the superblock_t via rvalue reference. // Is that possible? (promise_t makes it hard.) template <class Value> void find_keyvalue_location_for_write( superblock_t *superblock, const btree_key_t *key, keyvalue_location_t<Value> *keyvalue_location_out, btree_stats_t *stats, profile::trace_t *trace, promise_t<superblock_t *> *pass_back_superblock = NULL) { value_sizer_t<Value> sizer(superblock->expose_buf().cache()->max_block_size()); keyvalue_location_out->superblock = superblock; keyvalue_location_out->pass_back_superblock = pass_back_superblock; ensure_stat_block(superblock); keyvalue_location_out->stat_block = keyvalue_location_out->superblock->get_stat_block_id(); keyvalue_location_out->stats = stats; // KSI: Make sure we do the logic smart here -- don't needlessly hold both // buffers. (This finds the keyvalue for _write_ so that probably won't really // happen.) buf_lock_t last_buf; buf_lock_t buf; { // KSI: We can't acquire the block for write here -- we could, but it would // worsen the performance of the program -- sometimes we only end up using // this block for read. So the profiling information is not very good. profile::starter_t starter("Acquiring block for write.\n", trace); buf = get_root(&sizer, superblock); } // Walk down the tree to the leaf. for (;;) { { buf_read_t read(&buf); if (!node::is_internal(static_cast<const node_t *>(read.get_data_read()))) { break; } } // Check if the node is overfull and proactively split it if it is (since this is an internal node). { profile::starter_t starter("Perhaps split node.", trace); check_and_handle_split(&sizer, &buf, &last_buf, superblock, key, static_cast<Value *>(NULL)); } // Check if the node is underfull, and merge/level if it is. { profile::starter_t starter("Perhaps merge nodes.", trace); check_and_handle_underfull(&sizer, &buf, &last_buf, superblock, key); } // Release the superblock, if we've gone past the root (and haven't // already released it). If we're still at the root or at one of // its direct children, we might still want to replace the root, so // we can't release the superblock yet. if (!last_buf.empty() && keyvalue_location_out->superblock) { if (pass_back_superblock != NULL) { pass_back_superblock->pulse(superblock); keyvalue_location_out->superblock = NULL; } else { keyvalue_location_out->superblock->release(); keyvalue_location_out->superblock = NULL; } } // Release the old previous node (unless we're at the root), and set // the next previous node (which is the current node). last_buf.reset_buf_lock(); // Look up and acquire the next node. block_id_t node_id; { buf_read_t read(&buf); auto node = static_cast<const internal_node_t *>(read.get_data_read()); node_id = internal_node::lookup(node, key); } rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID); { profile::starter_t starter("Acquiring block for write.\n", trace); buf_lock_t tmp(&buf, node_id, access_t::write); last_buf = std::move(buf); buf = std::move(tmp); } } { scoped_malloc_t<Value> tmp(sizer.max_possible_size()); // We've gone down the tree and gotten to a leaf. Now look up the key. buf_read_t read(&buf); auto node = static_cast<const leaf_node_t *>(read.get_data_read()); bool key_found = leaf::lookup(&sizer, node, key, tmp.get()); if (key_found) { keyvalue_location_out->there_originally_was_value = true; keyvalue_location_out->value = std::move(tmp); } } keyvalue_location_out->last_buf.swap(last_buf); keyvalue_location_out->buf.swap(buf); } template <class Value> void find_keyvalue_location_for_read( superblock_t *superblock, const btree_key_t *key, keyvalue_location_t<Value> *keyvalue_location_out, btree_stats_t *stats, profile::trace_t *trace) { stats->pm_keys_read.record(); value_sizer_t<Value> sizer(superblock->expose_buf().cache()->max_block_size()); const block_id_t root_id = superblock->get_root_block_id(); rassert(root_id != SUPERBLOCK_ID); if (root_id == NULL_BLOCK_ID) { // There is no root, so the tree is empty. superblock->release(); return; } buf_lock_t buf; { profile::starter_t starter("Acquire a block for read.", trace); buf_lock_t tmp(superblock->expose_buf(), root_id, access_t::read); superblock->release(); buf = std::move(tmp); } #ifndef NDEBUG { buf_read_t read(&buf); node::validate(&sizer, static_cast<const node_t *>(read.get_data_read())); } #endif // NDEBUG for (;;) { { buf_read_t read(&buf); if (!node::is_internal(static_cast<const node_t *>(read.get_data_read()))) { break; } } block_id_t node_id; { buf_read_t read(&buf); const internal_node_t *node = static_cast<const internal_node_t *>(read.get_data_read()); node_id = internal_node::lookup(node, key); } rassert(node_id != NULL_BLOCK_ID && node_id != SUPERBLOCK_ID); { profile::starter_t starter("Acquire a block for read.", trace); buf_lock_t tmp(&buf, node_id, access_t::read); buf.reset_buf_lock(); buf = std::move(tmp); } #ifndef NDEBUG { buf_read_t read(&buf); node::validate(&sizer, static_cast<const node_t *>(read.get_data_read())); } #endif // NDEBUG } // Got down to the leaf, now probe it. scoped_malloc_t<Value> value(sizer.max_possible_size()); bool value_found; { buf_read_t read(&buf); const leaf_node_t *leaf = static_cast<const leaf_node_t *>(read.get_data_read()); value_found = leaf::lookup(&sizer, leaf, key, value.get()); } if (value_found) { keyvalue_location_out->buf = std::move(buf); keyvalue_location_out->there_originally_was_value = true; keyvalue_location_out->value = std::move(value); } } enum class expired_t { NO, YES }; template <class Value> void apply_keyvalue_change(keyvalue_location_t<Value> *kv_loc, const btree_key_t *key, repli_timestamp_t tstamp, expired_t expired, key_modification_callback_t<Value> *km_callback) { value_sizer_t<Value> sizer(kv_loc->buf.cache()->get_block_size()); key_modification_proof_t km_proof = km_callback->value_modification(kv_loc, key); /* how much this keyvalue change affects the total population of the btree * (should be -1, 0 or 1) */ int population_change; if (kv_loc->value.has()) { // We have a value to insert. // Split the node if necessary, to make sure that we have room // for the value. Not necessary when deleting, because the // node won't grow. check_and_handle_split(&sizer, &kv_loc->buf, &kv_loc->last_buf, kv_loc->superblock, key, kv_loc->value.get()); { #ifndef NDEBUG buf_read_t read(&kv_loc->buf); auto leaf_node = static_cast<const leaf_node_t *>(read.get_data_read()); rassert(!leaf::is_full(&sizer, leaf_node, key, kv_loc->value.get())); #endif } if (kv_loc->there_originally_was_value) { population_change = 0; } else { population_change = 1; } { buf_write_t write(&kv_loc->buf); auto leaf_node = static_cast<leaf_node_t *>(write.get_data_write()); leaf::insert(&sizer, leaf_node, key, kv_loc->value.get(), tstamp, km_proof); } kv_loc->stats->pm_keys_set.record(); } else { // Delete the value if it's there. if (kv_loc->there_originally_was_value) { if (expired == expired_t::NO) { rassert(tstamp != repli_timestamp_t::invalid, "Deletes need a valid timestamp now."); { buf_write_t write(&kv_loc->buf); auto leaf_node = static_cast<leaf_node_t *>(write.get_data_write()); leaf::remove(&sizer, leaf_node, key, tstamp, km_proof); } population_change = -1; kv_loc->stats->pm_keys_set.record(); } else { // TODO: Oh god oh god get rid of "expired". // Expirations do an erase, not a delete. { buf_write_t write(&kv_loc->buf); auto leaf_node = static_cast<leaf_node_t *>(write.get_data_write()); leaf::erase_presence(&sizer, leaf_node, key, km_proof); } population_change = 0; kv_loc->stats->pm_keys_expired.record(); } } else { population_change = 0; } } // Check to see if the leaf is underfull (following a change in // size or a deletion, and merge/level if it is. check_and_handle_underfull(&sizer, &kv_loc->buf, &kv_loc->last_buf, kv_loc->superblock, key); // Modify the stats block. buf_lock_t stat_block(buf_parent_t(&kv_loc->buf.txn()), kv_loc->stat_block, access_t::write); buf_write_t stat_block_write(&stat_block); auto stat_block_buf = static_cast<btree_statblock_t *>(stat_block_write.get_data_write()); stat_block_buf->population += population_change; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993-2010 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <string> #include <vector> #include <map> /* common headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "commands.h" #include "bzfsAPI.h" #include "DirectoryNames.h" #ifdef _WIN32 std::string extension = ".dll"; std::string globalPluginDir = ".\\plugins\\"; #else std::string extension = ".so"; std::string globalPluginDir = INSTALL_LIB_DIR; #endif typedef std::map<std::string, bz_APIPluginHandler*> tmCustomPluginMap; tmCustomPluginMap customPluginMap; typedef struct { std::string name; std::string filename; bz_Plugin* plugin; #ifdef _WIN32 HINSTANCE handle; #else void* handle; #endif }trPluginRecord; std::string findPlugin ( std::string pluginName ) { // see if we can just open the bloody thing FILE *fp = fopen(pluginName.c_str(),"rb"); if (fp) { fclose(fp); return pluginName; } // now try it with the standard extension std::string name = pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the local users plugins dir name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the global plugins dir name = globalPluginDir + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } return std::string(""); } std::vector<trPluginRecord> vPluginList; void unload1Plugin ( int iPluginID ); bool PluginExists ( const char* n ) { std::string name = n; std::vector<trPluginRecord>::iterator itr = vPluginList.begin(); while ( itr != vPluginList.end()) { if (itr->name == name) return true; itr++; } return false; } bz_Plugin* getPlugin( const char* n ) { std::string name = n; std::vector<trPluginRecord>::iterator itr = vPluginList.begin(); while ( itr != vPluginList.end()) { if (itr->name == name) return itr->plugin; itr++; } return NULL; } #ifdef _WIN32 # include <windows.h> int getPluginVersion ( HINSTANCE hLib ) { int (*lpProc)(void); lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetMinVersion"); if (lpProc) return lpProc(); return 0; } bool load1Plugin ( std::string plugin, std::string config ) { bz_Plugin* (*lpProc)(void); std::string realPluginName = findPlugin(plugin); HINSTANCE hLib = LoadLibrary(realPluginName.c_str()); if (hLib) { if (getPluginVersion(hLib) > BZ_API_VERSION) { logDebugMessage(1,"Plugin:%s found but needs a newer API version (%d), upgrade server\n",plugin.c_str(),getPluginVersion(hLib)); FreeLibrary(hLib); return false; } else { lpProc = (bz_Plugin* (__cdecl *)(void))GetProcAddress(hLib, "bz_GetPlugin"); if (lpProc) { bz_Plugin* p = lpProc(); if (!p) return false; std::string name = p->Name(); if (PluginExists(name.c_str())) { FreeLibrary(hLib); return false; } trPluginRecord pluginRecord; pluginRecord.name = name; pluginRecord.handle = hLib; pluginRecord.plugin = p; pluginRecord.filename = plugin; vPluginList.push_back(pluginRecord); p->Init(config.c_str()); logDebugMessage(1,"Plugin:%s loaded from $s\n",pluginRecord.name.c_str(),plugin.c_str()); return true; } else { logDebugMessage(1,"Plugin:%s found but does not contain bz_GetPlugin method\n",plugin.c_str()); FreeLibrary(hLib); return false; } } } else { logDebugMessage(1,"Plugin:%s not found\n",plugin.c_str()); return false; } } void unload1Plugin ( int iPluginID ) { void (*lpProc)(bz_Plugin*); trPluginRecord &plugin = vPluginList[iPluginID]; plugin.plugin->Cleanup(); lpProc = (void (__cdecl *)(bz_Plugin*))GetProcAddress(plugin.handle, "bz_FreePlugin"); if (lpProc) lpProc(plugin.plugin); else logDebugMessage(1,"Plugin does not contain bz_FreePlugin method, leaking memory\n"); FreeLibrary(plugin.handle); plugin.handle = NULL; plugin.plugin = NULL; } #else # include <dlfcn.h> std::vector<void*> vLibHandles; int getPluginVersion ( void* hLib ) { int (*lpProc)(void); *(void**) &lpProc = dlsym(hLib,"bz_GetMinVersion"); if (lpProc) return (*lpProc)(); return 0; } bool load1Plugin ( std::string plugin, std::string config ) { bz_Plugin* (*lpProc)(); std::string realPluginName = findPlugin(plugin); void *hLib = dlopen(realPluginName.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (hLib) { if (dlsym(hLib, "bz_GetPlugin") == NULL) { logDebugMessage(1,"Plugin:%s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror()); dlclose(hLib); return false; } int version = getPluginVersion(hLib); if (version > BZ_API_VERSION) { logDebugMessage(1,"Plugin:%s found but needs a newer API version (%d), upgrade server\n",plugin.c_str(), version); dlclose(hLib); return false; } else { *(void**) &lpProc = dlsym(hLib,"bz_GetPlugin"); if (lpProc) { bz_Plugin * p = (*lpProc)(); if (!p) return false; std::string name = p->Name(); if (PluginExists(name.c_str())) return false; trPluginRecord pluginRecord; pluginRecord.handle = hLib; pluginRecord.name = name; pluginRecord.plugin = p; pluginRecord.filename = plugin; vPluginList.push_back(pluginRecord); logDebugMessage(1,"Plugin:%s loaded from $s\n",pluginRecord.name.c_str(),plugin.c_str()); p->Init(config.c_str()); return true; } } } else { logDebugMessage(1,"Plugin:%s not found, error %s\n",plugin.c_str(), dlerror()); return false; } logDebugMessage(1,"If you see this, there is something terribly wrong.\n"); return false; } void unload1Plugin ( int iPluginID ) { void (*lpProc)(bz_Plugin*); trPluginRecord &plugin = vPluginList[iPluginID]; plugin.plugin->Cleanup(); *(void**) &lpProc = dlsym(plugin.handle, "bz_FreePlugin"); if (lpProc) (*lpProc)(plugin.plugin); else logDebugMessage(1,"Plugin does not contain bz_FreePlugin method, error %s. Leaking memory\n",dlerror()); dlclose(plugin.handle); plugin.handle = NULL; plugin.plugin = NULL; } #endif bool loadPlugin ( std::string plugin, std::string config ) { // check and see if it's an extension we have a handler for std::string ext; std::vector<std::string> parts = TextUtils::tokenize(plugin,std::string(".")); ext = parts[parts.size()-1]; tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr != customPluginMap.end() && itr->second) { bz_APIPluginHandler *handler = itr->second; return handler->APIPlugin(plugin,config); } else { return load1Plugin(plugin,config); } } bool unloadPlugin ( std::string plugin ) { // unload the first one of the name we find for (unsigned int i = 0; i < vPluginList.size();i++) { if ( vPluginList[i].name == plugin || vPluginList[i].filename == plugin ) { unload1Plugin(i); vPluginList.erase(vPluginList.begin()+i); return true; } } return false; } void unloadPlugins ( void ) { for (unsigned int i = 0; i < vPluginList.size();i++) unload1Plugin(i); vPluginList.clear(); removeCustomSlashCommand("loadplugin"); removeCustomSlashCommand("unloadplugin"); removeCustomSlashCommand("listplugins"); } std::vector<std::string> getPluginList ( void ) { std::vector<std::string> plugins; for (unsigned int i = 0; i < vPluginList.size();i++) plugins.push_back(vPluginList[i].name); return plugins; } float getPluginMinWaitTime ( void ) { float maxTime = 1000.0; std::vector<std::string> plugins; for (unsigned int i = 0; i < vPluginList.size();i++) { if (vPluginList[i].plugin && vPluginList[i].plugin->MaxWaitTime < maxTime) maxTime = vPluginList[i].plugin->MaxWaitTime; } return maxTime; } void parseServerCommand(const char *message, int dstPlayerId); class DynamicPluginCommands : public bz_CustomSlashCommandHandler { public: virtual ~DynamicPluginCommands(){}; virtual bool SlashCommand ( int playerID, bz_ApiString _command, bz_ApiString _message, bz_APIStringList *params ) { bz_BasePlayerRecord record; std::string command = _command.c_str(); std::string message = _message.c_str(); bz_BasePlayerRecord *p = bz_getPlayerByIndex(playerID); if (!p) return false; record = *p; bz_freePlayerRecord(p); // list dosn't need admin if ( TextUtils::tolower(command) == "listplugins" ) { std::vector<std::string> plugins = getPluginList(); if (!plugins.size()) bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded."); else { bz_sendTextMessage(BZ_SERVER,playerID,"Plug-ins loaded:"); for ( unsigned int i = 0; i < plugins.size(); i++) bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str()); } return true; } if (!record.hasPerm("PLUGINS")) { bz_sendTextMessage(BZ_SERVER,playerID,"You do not have permission to (un)load plug-ins."); return true; } if ( TextUtils::tolower(command) == "loadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /loadplugin plug-in"); return true; } std::vector<std::string> subparams = TextUtils::tokenize(message,std::string(",")); std::string config; if ( subparams.size() >1) config = subparams[1]; if (loadPlugin(subparams[0],config)) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded."); else bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in load failed."); return true; } if ( TextUtils::tolower(command) == "unloadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /unloadplugin plug-in"); return true; } if ( unloadPlugin(std::string(params->get(0).c_str())) ) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded."); return true; } return true; } }; DynamicPluginCommands command; void initPlugins ( void ) { customPluginMap.clear(); registerCustomSlashCommand("loadplugin",&command); registerCustomSlashCommand("unloadplugin",&command); registerCustomSlashCommand("listplugins",&command); } bool registerCustomPluginHandler ( std::string exte, bz_APIPluginHandler *handler ) { std::string ext = TextUtils::tolower(exte); customPluginMap[ext] = handler; return true; } bool removeCustomPluginHandler ( std::string ext, bz_APIPluginHandler *handler ) { tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr == customPluginMap.end() || itr->second != handler) return false; customPluginMap.erase(itr); return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Use valid syntax in debug message format strings. Use consistent style in debug messages.<commit_after>/* bzflag * Copyright (c) 1993-2010 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <string> #include <vector> #include <map> /* common headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "commands.h" #include "bzfsAPI.h" #include "DirectoryNames.h" #ifdef _WIN32 std::string extension = ".dll"; std::string globalPluginDir = ".\\plugins\\"; #else std::string extension = ".so"; std::string globalPluginDir = INSTALL_LIB_DIR; #endif typedef std::map<std::string, bz_APIPluginHandler*> tmCustomPluginMap; tmCustomPluginMap customPluginMap; typedef struct { std::string name; std::string filename; bz_Plugin* plugin; #ifdef _WIN32 HINSTANCE handle; #else void* handle; #endif }trPluginRecord; std::string findPlugin ( std::string pluginName ) { // see if we can just open the bloody thing FILE *fp = fopen(pluginName.c_str(),"rb"); if (fp) { fclose(fp); return pluginName; } // now try it with the standard extension std::string name = pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the local users plugins dir name = getConfigDirName(BZ_CONFIG_DIR_VERSION) + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } // check the global plugins dir name = globalPluginDir + pluginName + extension; fp = fopen(name.c_str(),"rb"); if (fp) { fclose(fp); return name; } return std::string(""); } std::vector<trPluginRecord> vPluginList; void unload1Plugin ( int iPluginID ); bool PluginExists ( const char* n ) { std::string name = n; std::vector<trPluginRecord>::iterator itr = vPluginList.begin(); while ( itr != vPluginList.end()) { if (itr->name == name) return true; itr++; } return false; } bz_Plugin* getPlugin( const char* n ) { std::string name = n; std::vector<trPluginRecord>::iterator itr = vPluginList.begin(); while ( itr != vPluginList.end()) { if (itr->name == name) return itr->plugin; itr++; } return NULL; } #ifdef _WIN32 # include <windows.h> int getPluginVersion ( HINSTANCE hLib ) { int (*lpProc)(void); lpProc = (int (__cdecl *)(void))GetProcAddress(hLib, "bz_GetMinVersion"); if (lpProc) return lpProc(); return 0; } bool load1Plugin ( std::string plugin, std::string config ) { bz_Plugin* (*lpProc)(void); std::string realPluginName = findPlugin(plugin); HINSTANCE hLib = LoadLibrary(realPluginName.c_str()); if (hLib) { if (getPluginVersion(hLib) > BZ_API_VERSION) { logDebugMessage(1,"Plugin: %s found but needs a newer API version (%d), upgrade server\n",plugin.c_str(),getPluginVersion(hLib)); FreeLibrary(hLib); return false; } else { lpProc = (bz_Plugin* (__cdecl *)(void))GetProcAddress(hLib, "bz_GetPlugin"); if (lpProc) { bz_Plugin* p = lpProc(); if (!p) return false; std::string name = p->Name(); if (PluginExists(name.c_str())) { FreeLibrary(hLib); return false; } trPluginRecord pluginRecord; pluginRecord.name = name; pluginRecord.handle = hLib; pluginRecord.plugin = p; pluginRecord.filename = plugin; vPluginList.push_back(pluginRecord); p->Init(config.c_str()); logDebugMessage(1,"Plugin: %s loaded from %s\n",pluginRecord.name.c_str(),plugin.c_str()); return true; } else { logDebugMessage(1,"Plugin: %s found but does not contain bz_GetPlugin method\n",plugin.c_str()); FreeLibrary(hLib); return false; } } } else { logDebugMessage(1,"Plugin: %s not found\n",plugin.c_str()); return false; } } void unload1Plugin ( int iPluginID ) { void (*lpProc)(bz_Plugin*); trPluginRecord &plugin = vPluginList[iPluginID]; plugin.plugin->Cleanup(); lpProc = (void (__cdecl *)(bz_Plugin*))GetProcAddress(plugin.handle, "bz_FreePlugin"); if (lpProc) lpProc(plugin.plugin); else logDebugMessage(1,"Plugin: bz_FreePlugin method not used by number %d. Leaking memory.\n",iPluginID); FreeLibrary(plugin.handle); plugin.handle = NULL; plugin.plugin = NULL; } #else # include <dlfcn.h> std::vector<void*> vLibHandles; int getPluginVersion ( void* hLib ) { int (*lpProc)(void); *(void**) &lpProc = dlsym(hLib,"bz_GetMinVersion"); if (lpProc) return (*lpProc)(); return 0; } bool load1Plugin ( std::string plugin, std::string config ) { bz_Plugin* (*lpProc)(); std::string realPluginName = findPlugin(plugin); void *hLib = dlopen(realPluginName.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (hLib) { if (dlsym(hLib, "bz_GetPlugin") == NULL) { logDebugMessage(1,"Plugin: %s found but does not contain bz_Load method, error %s\n",plugin.c_str(),dlerror()); dlclose(hLib); return false; } int version = getPluginVersion(hLib); if (version > BZ_API_VERSION) { logDebugMessage(1,"Plugin: %s found but needs a newer API version (%d), upgrade server\n",plugin.c_str(), version); dlclose(hLib); return false; } else { *(void**) &lpProc = dlsym(hLib,"bz_GetPlugin"); if (lpProc) { bz_Plugin * p = (*lpProc)(); if (!p) return false; std::string name = p->Name(); if (PluginExists(name.c_str())) return false; trPluginRecord pluginRecord; pluginRecord.handle = hLib; pluginRecord.name = name; pluginRecord.plugin = p; pluginRecord.filename = plugin; vPluginList.push_back(pluginRecord); logDebugMessage(1,"Plugin: %s loaded from %s\n",pluginRecord.name.c_str(),plugin.c_str()); p->Init(config.c_str()); return true; } } } else { logDebugMessage(1,"Plugin: %s not found, error %s\n",plugin.c_str(), dlerror()); return false; } logDebugMessage(1,"Plugin: load1Plugin() coding error\n"); return false; } void unload1Plugin ( int iPluginID ) { void (*lpProc)(bz_Plugin*); trPluginRecord &plugin = vPluginList[iPluginID]; plugin.plugin->Cleanup(); *(void**) &lpProc = dlsym(plugin.handle, "bz_FreePlugin"); if (lpProc) (*lpProc)(plugin.plugin); else logDebugMessage(1,"Plugin: bz_FreePlugin method not used by number %d, error %s. Leaking memory.\n",iPluginID,dlerror()); dlclose(plugin.handle); plugin.handle = NULL; plugin.plugin = NULL; } #endif bool loadPlugin ( std::string plugin, std::string config ) { // check and see if it's an extension we have a handler for std::string ext; std::vector<std::string> parts = TextUtils::tokenize(plugin,std::string(".")); ext = parts[parts.size()-1]; tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr != customPluginMap.end() && itr->second) { bz_APIPluginHandler *handler = itr->second; return handler->APIPlugin(plugin,config); } else { return load1Plugin(plugin,config); } } bool unloadPlugin ( std::string plugin ) { // unload the first one of the name we find for (unsigned int i = 0; i < vPluginList.size();i++) { if ( vPluginList[i].name == plugin || vPluginList[i].filename == plugin ) { unload1Plugin(i); vPluginList.erase(vPluginList.begin()+i); return true; } } return false; } void unloadPlugins ( void ) { for (unsigned int i = 0; i < vPluginList.size();i++) unload1Plugin(i); vPluginList.clear(); removeCustomSlashCommand("loadplugin"); removeCustomSlashCommand("unloadplugin"); removeCustomSlashCommand("listplugins"); } std::vector<std::string> getPluginList ( void ) { std::vector<std::string> plugins; for (unsigned int i = 0; i < vPluginList.size();i++) plugins.push_back(vPluginList[i].name); return plugins; } float getPluginMinWaitTime ( void ) { float maxTime = 1000.0; std::vector<std::string> plugins; for (unsigned int i = 0; i < vPluginList.size();i++) { if (vPluginList[i].plugin && vPluginList[i].plugin->MaxWaitTime < maxTime) maxTime = vPluginList[i].plugin->MaxWaitTime; } return maxTime; } void parseServerCommand(const char *message, int dstPlayerId); class DynamicPluginCommands : public bz_CustomSlashCommandHandler { public: virtual ~DynamicPluginCommands(){}; virtual bool SlashCommand ( int playerID, bz_ApiString _command, bz_ApiString _message, bz_APIStringList *params ) { bz_BasePlayerRecord record; std::string command = _command.c_str(); std::string message = _message.c_str(); bz_BasePlayerRecord *p = bz_getPlayerByIndex(playerID); if (!p) return false; record = *p; bz_freePlayerRecord(p); // list dosn't need admin if ( TextUtils::tolower(command) == "listplugins" ) { std::vector<std::string> plugins = getPluginList(); if (!plugins.size()) bz_sendTextMessage(BZ_SERVER,playerID,"No Plug-ins loaded."); else { bz_sendTextMessage(BZ_SERVER,playerID,"Plug-ins loaded:"); for ( unsigned int i = 0; i < plugins.size(); i++) bz_sendTextMessage(BZ_SERVER,playerID,plugins[i].c_str()); } return true; } if (!record.hasPerm("PLUGINS")) { bz_sendTextMessage(BZ_SERVER,playerID,"You do not have permission to (un)load plug-ins."); return true; } if ( TextUtils::tolower(command) == "loadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /loadplugin plug-in"); return true; } std::vector<std::string> subparams = TextUtils::tokenize(message,std::string(",")); std::string config; if ( subparams.size() >1) config = subparams[1]; if (loadPlugin(subparams[0],config)) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in loaded."); else bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in load failed."); return true; } if ( TextUtils::tolower(command) == "unloadplugin" ) { if ( !params->size() ) { bz_sendTextMessage(BZ_SERVER,playerID,"Usage: /unloadplugin plug-in"); return true; } if ( unloadPlugin(std::string(params->get(0).c_str())) ) bz_sendTextMessage(BZ_SERVER,playerID,"Plug-in unloaded."); return true; } return true; } }; DynamicPluginCommands command; void initPlugins ( void ) { customPluginMap.clear(); registerCustomSlashCommand("loadplugin",&command); registerCustomSlashCommand("unloadplugin",&command); registerCustomSlashCommand("listplugins",&command); } bool registerCustomPluginHandler ( std::string exte, bz_APIPluginHandler *handler ) { std::string ext = TextUtils::tolower(exte); customPluginMap[ext] = handler; return true; } bool removeCustomPluginHandler ( std::string ext, bz_APIPluginHandler *handler ) { tmCustomPluginMap::iterator itr = customPluginMap.find(TextUtils::tolower(ext)); if (itr == customPluginMap.end() || itr->second != handler) return false; customPluginMap.erase(itr); return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>