text
stringlengths
54
60.6k
<commit_before>#include "NotepadPlugin.h" #include <LuminaXDG.h> #include "LSession.h" NotePadPlugin::NotePadPlugin(QWidget* parent, QString ID) : LDPlugin(parent, ID){ QVBoxLayout *vlay = new QVBoxLayout(); this->setLayout( new QVBoxLayout() ); this->layout()->setContentsMargins(0,0,0,0); vlay->setContentsMargins(3,3,3,3); frame = new QFrame(this); frame->setObjectName("notepadbase"); frame->setStyleSheet("QFrame#notepadbase{border-size: 1px; background: rgba(255,255,255,100); color: black;} QFrame{ border: none; border-radius: 3px; background: rgba(255,255,255,100); color: black;}"); this->layout()->addWidget(frame); frame->setLayout(vlay); //Setup the title bar header buttons QHBoxLayout *hlay = new QHBoxLayout(); next = new QToolButton(this); next->setAutoRaise(true); prev = new QToolButton(this); prev->setAutoRaise(true); add = new QToolButton(this); add->setAutoRaise(true); rem = new QToolButton(this); rem->setAutoRaise(true); label = new QLabel(this); label->setAlignment(Qt::AlignCenter); hlay->addWidget(prev); hlay->addWidget(next); hlay->addWidget(label); hlay->addWidget(add); hlay->addWidget(rem); vlay->addLayout(hlay); //Setup the main text widget edit = new QPlainTextEdit(this); edit->setReadOnly(false); vlay->addWidget(edit); //Now setup the initial values cnote = this->settings->value("currentNote", 1).toInt(); maxnote = this->settings->value("availableNotes",1).toInt(); this->setInitialSize(200,300); //Setup the button connections connect(next, SIGNAL(clicked()), this, SLOT(nextNote()) ); connect(prev, SIGNAL(clicked()), this, SLOT(prevNote()) ); connect(add, SIGNAL(clicked()), this, SLOT(newNote()) ); connect(rem, SIGNAL(clicked()), this, SLOT(remNote()) ); connect(edit, SIGNAL(textChanged()), this, SLOT(noteChanged()) ); QTimer::singleShot(0,this, SLOT(loadIcons()) ); QTimer::singleShot(0,this, SLOT(updateContents()) ); } NotePadPlugin::~NotePadPlugin(){ } void NotePadPlugin::nextNote(){ cnote++; if(cnote>maxnote){ cnote = 1; } //go to the first updateContents(); } void NotePadPlugin::prevNote(){ cnote--; if(cnote<1){ cnote = maxnote; } //go to the last updateContents(); } void NotePadPlugin::newNote(){ maxnote++; cnote = maxnote; updateContents(); } void NotePadPlugin::remNote(){ //Clear the current note settings->remove("Note-"+QString::number(cnote)); //If the last note, also decrease the max number if(cnote==maxnote && maxnote>1){ maxnote--; } //Now go to the previous note cnote--; if(cnote<1){ cnote = maxnote; } updateContents(); } void NotePadPlugin::updateContents(){ next->setEnabled(cnote<maxnote); prev->setEnabled(cnote>1); label->setText( QString(tr("Note #%1")).arg(QString::number(cnote)) ); settings->setValue("currentNote", cnote); settings->setValue("availableNotes", maxnote); edit->setPlainText( settings->value("Note-"+QString::number(cnote), "").toString() ); } void NotePadPlugin::noteChanged(){ //Save the current text settings->setValue("Note-"+QString::number(cnote), edit->toPlainText()); } void NotePadPlugin::loadIcons(){ next->setIcon( LXDG::findIcon("go-next-view","") ); prev->setIcon( LXDG::findIcon("go-previous-view","") ); add->setIcon( LXDG::findIcon("document-new","") ); rem->setIcon( LXDG::findIcon("document-close","") ); } <commit_msg>Increase the transparency of the notepad desktop plugin background.<commit_after>#include "NotepadPlugin.h" #include <LuminaXDG.h> #include "LSession.h" NotePadPlugin::NotePadPlugin(QWidget* parent, QString ID) : LDPlugin(parent, ID){ QVBoxLayout *vlay = new QVBoxLayout(); this->setLayout( new QVBoxLayout() ); this->layout()->setContentsMargins(0,0,0,0); vlay->setContentsMargins(3,3,3,3); frame = new QFrame(this); frame->setObjectName("notepadbase"); frame->setStyleSheet("QFrame#notepadbase{border-size: 1px; background: rgba(255,255,255,50); color: black;} QFrame{ border: none; border-radius: 3px; background: rgba(255,255,255,100); color: black;}"); this->layout()->addWidget(frame); frame->setLayout(vlay); //Setup the title bar header buttons QHBoxLayout *hlay = new QHBoxLayout(); next = new QToolButton(this); next->setAutoRaise(true); prev = new QToolButton(this); prev->setAutoRaise(true); add = new QToolButton(this); add->setAutoRaise(true); rem = new QToolButton(this); rem->setAutoRaise(true); label = new QLabel(this); label->setAlignment(Qt::AlignCenter); hlay->addWidget(prev); hlay->addWidget(next); hlay->addWidget(label); hlay->addWidget(add); hlay->addWidget(rem); vlay->addLayout(hlay); //Setup the main text widget edit = new QPlainTextEdit(this); edit->setReadOnly(false); vlay->addWidget(edit); //Now setup the initial values cnote = this->settings->value("currentNote", 1).toInt(); maxnote = this->settings->value("availableNotes",1).toInt(); this->setInitialSize(200,300); //Setup the button connections connect(next, SIGNAL(clicked()), this, SLOT(nextNote()) ); connect(prev, SIGNAL(clicked()), this, SLOT(prevNote()) ); connect(add, SIGNAL(clicked()), this, SLOT(newNote()) ); connect(rem, SIGNAL(clicked()), this, SLOT(remNote()) ); connect(edit, SIGNAL(textChanged()), this, SLOT(noteChanged()) ); QTimer::singleShot(0,this, SLOT(loadIcons()) ); QTimer::singleShot(0,this, SLOT(updateContents()) ); } NotePadPlugin::~NotePadPlugin(){ } void NotePadPlugin::nextNote(){ cnote++; if(cnote>maxnote){ cnote = 1; } //go to the first updateContents(); } void NotePadPlugin::prevNote(){ cnote--; if(cnote<1){ cnote = maxnote; } //go to the last updateContents(); } void NotePadPlugin::newNote(){ maxnote++; cnote = maxnote; updateContents(); } void NotePadPlugin::remNote(){ //Clear the current note settings->remove("Note-"+QString::number(cnote)); //If the last note, also decrease the max number if(cnote==maxnote && maxnote>1){ maxnote--; } //Now go to the previous note cnote--; if(cnote<1){ cnote = maxnote; } updateContents(); } void NotePadPlugin::updateContents(){ next->setEnabled(cnote<maxnote); prev->setEnabled(cnote>1); label->setText( QString(tr("Note #%1")).arg(QString::number(cnote)) ); settings->setValue("currentNote", cnote); settings->setValue("availableNotes", maxnote); edit->setPlainText( settings->value("Note-"+QString::number(cnote), "").toString() ); } void NotePadPlugin::noteChanged(){ //Save the current text settings->setValue("Note-"+QString::number(cnote), edit->toPlainText()); } void NotePadPlugin::loadIcons(){ next->setIcon( LXDG::findIcon("go-next-view","") ); prev->setIcon( LXDG::findIcon("go-previous-view","") ); add->setIcon( LXDG::findIcon("document-new","") ); rem->setIcon( LXDG::findIcon("document-close","") ); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: collator_unicode.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-04-08 15:43:32 $ * * 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 _I18N_COLLATOR_UNICODE_HXX_ #define _I18N_COLLATOR_UNICODE_HXX_ #include <com/sun/star/uno/Reference.h> #include <com/sun/star/i18n/XCollator.hpp> #include <com/sun/star/i18n/TransliterationModules.hpp> #include <cppuhelper/implbase1.hxx> // ---------------------------------------------------- // class Collator_Unicode // ---------------------------------------------------- namespace com { namespace sun { namespace star { namespace i18n { class Collator_Unicode : public cppu::WeakImplHelper1 < XCollator > { public: // Constructors Collator_Unicode(); // Destructor ~Collator_Unicode(); virtual sal_Int32 SAL_CALL compareSubstring( const rtl::OUString& s1, sal_Int32 off1, sal_Int32 len1, const rtl::OUString& s2, sal_Int32 off2, sal_Int32 len2) throw(com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL compareString( const rtl::OUString& s1, const rtl::OUString& s2) throw(com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL loadCollatorAlgorithm( const rtl::OUString& impl, const lang::Locale& rLocale, sal_Int32 collatorOptions) throw(com::sun::star::uno::RuntimeException); // following 4 methods are implemented in collatorImpl. sal_Int32 SAL_CALL loadDefaultCollator( const lang::Locale& rLocale, sal_Int32 collatorOptions) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} void SAL_CALL loadCollatorAlgorithmWithEndUserOption( const rtl::OUString& impl, const lang::Locale& rLocale, const com::sun::star::uno::Sequence< sal_Int32 >& collatorOptions) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL listCollatorAlgorithms( const lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL listCollatorOptions( const rtl::OUString& collatorAlgorithmName ) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException ); protected: sal_Char *implementationName; com::sun::star::lang::Locale aLocale; TransliterationModules tranModules; }; } } } } #endif <commit_msg>INTEGRATION: CWS i18n10 (1.3.54); FILE MERGED 2003/12/17 20:08:41 khong 1.3.54.1: #i22138# #112506# migrate to ICU collator and remove link to tool library<commit_after>/************************************************************************* * * $RCSfile: collator_unicode.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-01-20 13:18:27 $ * * 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 _I18N_COLLATOR_UNICODE_HXX_ #define _I18N_COLLATOR_UNICODE_HXX_ #include <com/sun/star/uno/Reference.h> #include <com/sun/star/i18n/XCollator.hpp> #include <cppuhelper/implbase1.hxx> #include <unicode/tblcoll.h> // ---------------------------------------------------- // class Collator_Unicode // ---------------------------------------------------- namespace com { namespace sun { namespace star { namespace i18n { class Collator_Unicode : public cppu::WeakImplHelper1 < XCollator > { public: // Constructors Collator_Unicode(); // Destructor ~Collator_Unicode(); sal_Int32 SAL_CALL compareSubstring( const rtl::OUString& s1, sal_Int32 off1, sal_Int32 len1, const rtl::OUString& s2, sal_Int32 off2, sal_Int32 len2) throw(com::sun::star::uno::RuntimeException); sal_Int32 SAL_CALL compareString( const rtl::OUString& s1, const rtl::OUString& s2) throw(com::sun::star::uno::RuntimeException); sal_Int32 SAL_CALL loadCollatorAlgorithm( const rtl::OUString& impl, const lang::Locale& rLocale, sal_Int32 collatorOptions) throw(com::sun::star::uno::RuntimeException); // following 4 methods are implemented in collatorImpl. sal_Int32 SAL_CALL loadDefaultCollator( const lang::Locale& rLocale, sal_Int32 collatorOptions) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} void SAL_CALL loadCollatorAlgorithmWithEndUserOption( const rtl::OUString& impl, const lang::Locale& rLocale, const com::sun::star::uno::Sequence< sal_Int32 >& collatorOptions) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL listCollatorAlgorithms( const lang::Locale& rLocale ) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL listCollatorOptions( const rtl::OUString& collatorAlgorithmName ) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();} //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException ); protected: const sal_Char *implementationName; const sal_uInt8 *rulesImage; private: RuleBasedCollator *collator; }; #define COLLATOR( algorithm ) \ class Collator_##algorithm : public Collator_Unicode {\ public:\ Collator_##algorithm(); \ }; COLLATOR( zh_pinyin ) COLLATOR( zh_radical ) COLLATOR( zh_stroke ) COLLATOR( zh_charset ) COLLATOR( zh_zhuyin ) COLLATOR( zh_TW_radical ) COLLATOR( zh_TW_stroke ) COLLATOR( zh_TW_charset ) COLLATOR( ko_dict ) COLLATOR( ko_charset ) COLLATOR( ja_charset ) COLLATOR( ja_phonetic_alphanumeric_first ) COLLATOR( ja_phonetic_alphanumeric_last ) #undef COLLATOR } } } } #endif <|endoftext|>
<commit_before>#pragma once #include <ceres/ceres.h> #include <ceres/rotation.h> #include <openMVG/geometry/pose3.hpp> #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> //todo: not generic // only Pinhole_Intrinsic_Radial_K3 is currently supported // todo: allows internal parameters refinement namespace openMVG { namespace rig { class ResidualErrorMainCameraFunctor { public : ResidualErrorMainCameraFunctor( const cameras::Pinhole_Intrinsic_Radial_K3 & intrinsics, const Vec2 & x, const Vec3 & X) { // Set the intrinsics _K = intrinsics.K(); _params.reserve(3); _params.push_back(intrinsics.getParams()[3]); _params.push_back(intrinsics.getParams()[4]); _params.push_back(intrinsics.getParams()[5]); // Set the observation _observation[0] = x[0]; _observation[1] = x[1]; // Set the 3D point _point(0) = X(0); _point(1) = X(1); _point(2) = X(2); } // Enum to map intrinsics parameters between openMVG & ceres camera data parameter block. // enum { // OFFSET_FOCAL_LENGTH = 0, // OFFSET_PRINCIPAL_POINT_X = 1, // OFFSET_PRINCIPAL_POINT_Y = 2, // OFFSET_DISTO_K1 = 3, // OFFSET_DISTO_K2 = 4, // OFFSET_DISTO_K3 = 5, // }; /** * @param[in] cam_K: Camera intrinsics( focal, principal point [x,y] ) * @param[in] cam_Rt: Camera parameterized using one block of 6 parameters [R;t]: * - 3 for rotation(angle axis), 3 for translation * @param[in] pos_3dpoint * @param[out] out_residuals */ template <typename T> bool operator()( const T* const cam_Rt, T* out_residuals) const { //-- // Apply external parameters (Pose) //-- const T * cam_R = cam_Rt; const T * cam_t = &cam_Rt[3]; T pos_3dpoint[3]; pos_3dpoint[0]= T(_point(0)); pos_3dpoint[1]= T(_point(1)); pos_3dpoint[2]= T(_point(2)); T pos_proj[3]; // Rotate the point according the camera rotation ceres::AngleAxisRotatePoint(cam_R, pos_3dpoint, pos_proj); // Apply the camera translation pos_proj[0] += cam_t[0]; pos_proj[1] += cam_t[1]; pos_proj[2] += cam_t[2]; // Transform the point from homogeneous to euclidean (undistorted point) const T x_u = pos_proj[0] / pos_proj[2]; const T y_u = pos_proj[1] / pos_proj[2]; //-- // Apply intrinsic parameters //-- const T focal = T(_K(0,0)); const T principal_point_x = T(_K(0,2)); const T principal_point_y = T(_K(1,2)); const T k1 = T(_params[0]); const T k2 = T(_params[1]); const T k3 = T(_params[2]); // Apply distortion (xd,yd) = disto(x_u,y_u) const T r2 = x_u*x_u + y_u*y_u; const T r4 = r2 * r2; const T r6 = r4 * r2; const T r_coeff = (T(1) + k1*r2 + k2*r4 + k3*r6); const T x_d = x_u * r_coeff; const T y_d = y_u * r_coeff; // Apply focal length and principal point to get the final image coordinates const T projected_x = principal_point_x + focal * x_d; const T projected_y = principal_point_y + focal * y_d; // Compute and return the error is the difference between the predicted // and observed position out_residuals[0] = projected_x - _observation[0]; out_residuals[1] = projected_y - _observation[1]; return true; } private : openMVG::Mat3 _K; // Calibration matrix std::vector<double> _params; // {K1, K2, K3} openMVG::Vec3 _point; // 3D point openMVG::Vec2 _observation; // its image location }; class ResidualErrorSecondaryCameraFunctor { public : ResidualErrorSecondaryCameraFunctor(const cameras::Pinhole_Intrinsic_Radial_K3 & intrinsics, const openMVG::Vec2 & x, const openMVG::Vec3 & X) // const double* const pos_2dpoint { // Set the intrinsics _K = intrinsics.K(); _params.reserve(3); _params.push_back(intrinsics.getParams()[3]); _params.push_back(intrinsics.getParams()[4]); _params.push_back(intrinsics.getParams()[5]); // Set the observation _observation[0] = x[0]; _observation[1] = x[1]; // Set the 3D point _point(0) = X(0); _point(1) = X(1); _point(2) = X(2); } // Enum to map intrinsics parameters between openMVG & ceres camera data parameter block. // enum { // OFFSET_FOCAL_LENGTH = 0, // OFFSET_PRINCIPAL_POINT_X = 1, // OFFSET_PRINCIPAL_POINT_Y = 2, // OFFSET_DISTO_K1 = 3, // OFFSET_DISTO_K2 = 4, // OFFSET_DISTO_K3 = 5, // }; /** * @param[in] cam_Rt_main: Main camera parameterized using one block of 6 parameters [R;t]: * - 3 for rotation(angle axis), 3 for translation * @param[in] cam_Rt_relative: Relative pose of the witness camera relatively to the main one * parameterized using one block of 6 parameters [R;t]: * - 3 for rotation(angle axis), 3 for translation * @param[out] out_residuals */ template <typename T> bool operator()( const T* const cam_Rt_main, const T* const cam_Rt_relative, T* out_residuals) const { //-- // Apply external parameters (Pose) //-- const T * RMain = cam_Rt_main; const T * tMain = &cam_Rt_main[3]; const T * RRelative = cam_Rt_relative; const T * tRelative = &cam_Rt_relative[3]; T pos_3dpoint[3]; pos_3dpoint[0]= T(_point(0)); pos_3dpoint[1]= T(_point(1)); pos_3dpoint[2]= T(_point(2)); T pos_tmp[3]; // Rotate the point according the relative rotation first ceres::AngleAxisRotatePoint(RMain, pos_3dpoint, pos_tmp); // Apply the relative translation first pos_tmp[0] += tMain[0]; pos_tmp[1] += tMain[1]; pos_tmp[2] += tMain[2]; T pos_proj[3]; // Rotate the point according the main camera rotation ceres::AngleAxisRotatePoint(RRelative, pos_tmp, pos_proj); // Apply the main camera translation pos_proj[0] += tRelative[0]; pos_proj[1] += tRelative[1]; pos_proj[2] += tRelative[2]; // Transform the point from homogeneous to euclidean (undistorted point) const T x_u = pos_proj[0] / pos_proj[2]; const T y_u = pos_proj[1] / pos_proj[2]; //-- // Apply intrinsic parameters //-- const T focal = T(_K(0,0)); const T principal_point_x = T(_K(0,2)); const T principal_point_y = T(_K(1,2)); const T k1 = T(_params[0]); const T k2 = T(_params[1]); const T k3 = T(_params[2]); // Apply distortion (xd,yd) = disto(x_u,y_u) const T r2 = x_u*x_u + y_u*y_u; const T r4 = r2 * r2; const T r6 = r4 * r2; const T r_coeff = (T(1) + k1*r2 + k2*r4 + k3*r6); const T x_d = x_u * r_coeff; const T y_d = y_u * r_coeff; // Apply focal length and principal point to get the final image coordinates const T projected_x = principal_point_x + focal * x_d; const T projected_y = principal_point_y + focal * y_d; // Compute and return the error is the difference between the predicted // and observed position out_residuals[0] = projected_x - _observation[0]; out_residuals[1] = projected_y - _observation[1]; return true; } private : openMVG::Mat3 _K; // Calibration matrix std::vector<double> _params; // {K1, K2, K3} openMVG::Vec3 _point; // 3D point openMVG::Vec2 _observation; // its image location }; } }<commit_msg>[rig] include order<commit_after>#pragma once #include <openMVG/geometry/pose3.hpp> #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> //todo: not generic // only Pinhole_Intrinsic_Radial_K3 is currently supported // todo: allows internal parameters refinement #include <ceres/ceres.h> #include <ceres/rotation.h> namespace openMVG { namespace rig { class ResidualErrorMainCameraFunctor { public : ResidualErrorMainCameraFunctor( const cameras::Pinhole_Intrinsic_Radial_K3 & intrinsics, const Vec2 & x, const Vec3 & X) { // Set the intrinsics _K = intrinsics.K(); _params.reserve(3); _params.push_back(intrinsics.getParams()[3]); _params.push_back(intrinsics.getParams()[4]); _params.push_back(intrinsics.getParams()[5]); // Set the observation _observation[0] = x[0]; _observation[1] = x[1]; // Set the 3D point _point(0) = X(0); _point(1) = X(1); _point(2) = X(2); } // Enum to map intrinsics parameters between openMVG & ceres camera data parameter block. // enum { // OFFSET_FOCAL_LENGTH = 0, // OFFSET_PRINCIPAL_POINT_X = 1, // OFFSET_PRINCIPAL_POINT_Y = 2, // OFFSET_DISTO_K1 = 3, // OFFSET_DISTO_K2 = 4, // OFFSET_DISTO_K3 = 5, // }; /** * @param[in] cam_K: Camera intrinsics( focal, principal point [x,y] ) * @param[in] cam_Rt: Camera parameterized using one block of 6 parameters [R;t]: * - 3 for rotation(angle axis), 3 for translation * @param[in] pos_3dpoint * @param[out] out_residuals */ template <typename T> bool operator()( const T* const cam_Rt, T* out_residuals) const { //-- // Apply external parameters (Pose) //-- const T * cam_R = cam_Rt; const T * cam_t = &cam_Rt[3]; T pos_3dpoint[3]; pos_3dpoint[0]= T(_point(0)); pos_3dpoint[1]= T(_point(1)); pos_3dpoint[2]= T(_point(2)); T pos_proj[3]; // Rotate the point according the camera rotation ceres::AngleAxisRotatePoint(cam_R, pos_3dpoint, pos_proj); // Apply the camera translation pos_proj[0] += cam_t[0]; pos_proj[1] += cam_t[1]; pos_proj[2] += cam_t[2]; // Transform the point from homogeneous to euclidean (undistorted point) const T x_u = pos_proj[0] / pos_proj[2]; const T y_u = pos_proj[1] / pos_proj[2]; //-- // Apply intrinsic parameters //-- const T focal = T(_K(0,0)); const T principal_point_x = T(_K(0,2)); const T principal_point_y = T(_K(1,2)); const T k1 = T(_params[0]); const T k2 = T(_params[1]); const T k3 = T(_params[2]); // Apply distortion (xd,yd) = disto(x_u,y_u) const T r2 = x_u*x_u + y_u*y_u; const T r4 = r2 * r2; const T r6 = r4 * r2; const T r_coeff = (T(1) + k1*r2 + k2*r4 + k3*r6); const T x_d = x_u * r_coeff; const T y_d = y_u * r_coeff; // Apply focal length and principal point to get the final image coordinates const T projected_x = principal_point_x + focal * x_d; const T projected_y = principal_point_y + focal * y_d; // Compute and return the error is the difference between the predicted // and observed position out_residuals[0] = projected_x - _observation[0]; out_residuals[1] = projected_y - _observation[1]; return true; } private : openMVG::Mat3 _K; // Calibration matrix std::vector<double> _params; // {K1, K2, K3} openMVG::Vec3 _point; // 3D point openMVG::Vec2 _observation; // its image location }; class ResidualErrorSecondaryCameraFunctor { public : ResidualErrorSecondaryCameraFunctor(const cameras::Pinhole_Intrinsic_Radial_K3 & intrinsics, const openMVG::Vec2 & x, const openMVG::Vec3 & X) // const double* const pos_2dpoint { // Set the intrinsics _K = intrinsics.K(); _params.reserve(3); _params.push_back(intrinsics.getParams()[3]); _params.push_back(intrinsics.getParams()[4]); _params.push_back(intrinsics.getParams()[5]); // Set the observation _observation[0] = x[0]; _observation[1] = x[1]; // Set the 3D point _point(0) = X(0); _point(1) = X(1); _point(2) = X(2); } // Enum to map intrinsics parameters between openMVG & ceres camera data parameter block. // enum { // OFFSET_FOCAL_LENGTH = 0, // OFFSET_PRINCIPAL_POINT_X = 1, // OFFSET_PRINCIPAL_POINT_Y = 2, // OFFSET_DISTO_K1 = 3, // OFFSET_DISTO_K2 = 4, // OFFSET_DISTO_K3 = 5, // }; /** * @param[in] cam_Rt_main: Main camera parameterized using one block of 6 parameters [R;t]: * - 3 for rotation(angle axis), 3 for translation * @param[in] cam_Rt_relative: Relative pose of the witness camera relatively to the main one * parameterized using one block of 6 parameters [R;t]: * - 3 for rotation(angle axis), 3 for translation * @param[out] out_residuals */ template <typename T> bool operator()( const T* const cam_Rt_main, const T* const cam_Rt_relative, T* out_residuals) const { //-- // Apply external parameters (Pose) //-- const T * RMain = cam_Rt_main; const T * tMain = &cam_Rt_main[3]; const T * RRelative = cam_Rt_relative; const T * tRelative = &cam_Rt_relative[3]; T pos_3dpoint[3]; pos_3dpoint[0]= T(_point(0)); pos_3dpoint[1]= T(_point(1)); pos_3dpoint[2]= T(_point(2)); T pos_tmp[3]; // Rotate the point according the relative rotation first ceres::AngleAxisRotatePoint(RMain, pos_3dpoint, pos_tmp); // Apply the relative translation first pos_tmp[0] += tMain[0]; pos_tmp[1] += tMain[1]; pos_tmp[2] += tMain[2]; T pos_proj[3]; // Rotate the point according the main camera rotation ceres::AngleAxisRotatePoint(RRelative, pos_tmp, pos_proj); // Apply the main camera translation pos_proj[0] += tRelative[0]; pos_proj[1] += tRelative[1]; pos_proj[2] += tRelative[2]; // Transform the point from homogeneous to euclidean (undistorted point) const T x_u = pos_proj[0] / pos_proj[2]; const T y_u = pos_proj[1] / pos_proj[2]; //-- // Apply intrinsic parameters //-- const T focal = T(_K(0,0)); const T principal_point_x = T(_K(0,2)); const T principal_point_y = T(_K(1,2)); const T k1 = T(_params[0]); const T k2 = T(_params[1]); const T k3 = T(_params[2]); // Apply distortion (xd,yd) = disto(x_u,y_u) const T r2 = x_u*x_u + y_u*y_u; const T r4 = r2 * r2; const T r6 = r4 * r2; const T r_coeff = (T(1) + k1*r2 + k2*r4 + k3*r6); const T x_d = x_u * r_coeff; const T y_d = y_u * r_coeff; // Apply focal length and principal point to get the final image coordinates const T projected_x = principal_point_x + focal * x_d; const T projected_y = principal_point_y + focal * y_d; // Compute and return the error is the difference between the predicted // and observed position out_residuals[0] = projected_x - _observation[0]; out_residuals[1] = projected_y - _observation[1]; return true; } private : openMVG::Mat3 _K; // Calibration matrix std::vector<double> _params; // {K1, K2, K3} openMVG::Vec3 _point; // 3D point openMVG::Vec2 _observation; // its image location }; } }<|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/graphcompatibility.h" #include "elm/core/featuredata.h" #include "elm/core/signal.h" #include "elm/core/layerconfig.h" #include "elm/layers/layerfactory.h" #include "elm/ts/layer_assertions.h" using namespace std; using namespace boost; using namespace cv; using namespace elm; namespace { ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(GraphCompatibility); const string NAME_GRAPH_AB = "G_ab"; const string NAME_GRAPH_IJ = "g_ij"; const string NAME_M = "m"; class GraphCompatibilityInitTest : public ::testing::Test { protected: virtual void SetUp() { LayerConfig cfg; LayerIONames io; io.Input(GraphCompatibility::KEY_INPUT_GRAPH_AB, NAME_GRAPH_AB); io.Input(GraphCompatibility::KEY_INPUT_GRAPH_IJ, NAME_GRAPH_IJ); io.Output(GraphCompatibility::KEY_OUTPUT_RESPONSE, NAME_M); to_ = LayerFactory::CreateShared("GraphCompatibility", cfg, io); } // members LayerFactory::LayerShared to_; ///< pointer to test object }; TEST_F(GraphCompatibilityInitTest, Constructor_overloaded) { LayerConfig cfg; EXPECT_NO_THROW(to_.reset(new GraphCompatibility(cfg))); } class GraphCompatibilityTest : public GraphCompatibilityInitTest { protected: virtual void SetUp() { GraphCompatibilityInitTest::SetUp(); // initialize test graphs const int A=4; ///< no. of nodes in G const int I=A; ///< no. of nodes in g // generate random adjacency matrices g_ab_ = Mat1f(A, A); Mat1i tmp(A, A); int s = 1000; randu(tmp, 0, s); g_ab_ = tmp/static_cast<float>(s); // distance from node to itself is 0 for(int r=0; r<g_ab_.rows; r++) { g_ab_(r, r) = 0.f; } // make symmetrical for(int r=0; r<g_ab_.rows; r++) { for(int c=0; c<g_ab_.rows; c++) { g_ab_(r, c) = g_ab_(c, r); } } g_ij_ = Mat1f(I, I); g_ij_ = g_ab_.clone(); // make them equal Mat1f noise(g_ij_.size()); randn(noise, 0.f, 0.02f); g_ij_ += noise; g_ij_.setTo(0.f, g_ij_ < 0.f); g_ij_.setTo(1.f, g_ij_ > 1.f); for(int r=0; r<g_ij_.rows; r++) { g_ij_(r, r) = 0.f; for(int c=0; c<g_ij_.cols; c++) { g_ij_(r, c) = g_ij_(c, r); } } // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); } virtual void TearDown() { sig_.Clear(); } // members Mat1f g_ab_; ///< adj. matrix for test graph Mat1f g_ij_; ///< adj. matrix for test graph Signal sig_; }; TEST_F(GraphCompatibilityTest, Activate_invalid_non_square_adj_mat) { g_ab_ = Mat1f::ones(11, 7) - Mat1f::eye(11, 7); g_ij_ = g_ab_.clone(); sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); EXPECT_THROW(to_->Activate(sig_), ExceptionBadDims); } TEST_F(GraphCompatibilityTest, Dims) { for(int A=1; A<10; A++) { for(int I=1; I<10; I++) { // generate random adjacency matrices g_ab_ = Mat1f(A, A, 1.f); g_ij_ = Mat1f(I, I, 1.f); sig_.Clear(); // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Clear(); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); ASSERT_EQ(4, c_aibj.dims()) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(A, c_aibj.size(0)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(I, c_aibj.size(1)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(A, c_aibj.size(2)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(I, c_aibj.size(3)) << "Match matrix should be of size (A, I, A, I)"; } } } /** * @brief graph without any connections should yield all-zero compatibility */ TEST_F(GraphCompatibilityTest, NoConnections) { const int NB_VERTICES = 5; g_ab_ = Mat1f::zeros(NB_VERTICES, NB_VERTICES); g_ij_ = g_ab_.clone(); // make them equal // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); ASSERT_EQ(4, c_aibj.dims()) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(0)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(1)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(2)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(3)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(static_cast<size_t>(0), c_aibj.nzcount()); } /** * @brief zero-compatibility for node without edges */ TEST_F(GraphCompatibilityTest, NoConnections_for_one_node_in_g_ab) { int vertex_idx = abs(randu<int>()) % g_ab_.rows; g_ab_.row(vertex_idx).setTo(0.f); g_ab_.col(vertex_idx).setTo(0.f); // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); for(int i=0; i<g_ij_.rows; i++) { for(int b=0; b<g_ab_.rows; b++) { for(int j=0; j<g_ij_.rows; j++) { int idx[4] = {vertex_idx, i, b, j}; EXPECT_FLOAT_EQ(0.f, c_aibj.ref(idx)) << "Expecting all-zero row for slice a=" << vertex_idx << " since this vertex doesn't have any edges"; } } } } /** * @brief zero-compatibility for node without edges */ TEST_F(GraphCompatibilityTest, NoConnections_for_one_node_in_g_ij) { int vertex_idx = abs(randu<int>()) % g_ij_.rows; g_ij_.row(vertex_idx).setTo(0.f); g_ij_.col(vertex_idx).setTo(0.f); // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); for(int a=0; a<g_ij_.rows; a++) { for(int b=0; b<g_ab_.rows; b++) { for(int j=0; j<g_ij_.rows; j++) { int idx[4] = {a, vertex_idx, b, j}; EXPECT_FLOAT_EQ(0.f, c_aibj.ref(idx)) << "Expecting all-zero row for slice i=" << vertex_idx << " since this vertex doesn't have any edges"; } } } } /** * @brief Make weights of two vertices very compatible and compare * their compatibility score with that of other nodes. * This test does not assume that both adjacency graphs share the same dimensions. */ TEST_F(GraphCompatibilityTest, CompatibilityIntegration) { // sanity check ASSERT_GT(g_ab_.rows, 1) << "this test requires adjacency graphs for graphs with > 1 vertex"; ASSERT_GT(g_ij_.rows, 1) << "this test requires adjacency graphs for graphs with > 1 vertex"; const int MIN_DIM = static_cast<int>(min(g_ab_.rows, g_ij_.rows)); const int N=5; // do this for multiple vertices for(int i=0; i<N; i++) { // make two vertices in both graph very compatible int vertex_compat_idx = abs(randu<int>()) % MIN_DIM; // actual weight value doesn't matter // it only matters that the edges in both graphs appear similar for a pair of vertices. int rand_value = static_cast<float>(abs(randu<int>()) % 100); float weight = rand_value/100.f; g_ab_.row(vertex_compat_idx).setTo(weight); g_ab_.col(vertex_compat_idx).setTo(weight); g_ab_(vertex_compat_idx, vertex_compat_idx) = 0.f; g_ij_.row(vertex_compat_idx).setTo(weight); g_ij_.col(vertex_compat_idx).setTo(weight); g_ij_(vertex_compat_idx, vertex_compat_idx) = 0.f; // make two other vertices in both graph very un-compatible int vertex_non_compat_idx = (vertex_compat_idx + 1) % MIN_DIM; g_ab_.row(vertex_non_compat_idx).setTo(weight); g_ab_.col(vertex_non_compat_idx).setTo(weight); // select second weight to be different from first for vertices to seem less compatible float weight2 = static_cast<float>(rand_value+30 % 100)/100.f; // sanity check ASSERT_GT(abs(weight-weight2), 0.25f) << "Difference between weights not large enough"; g_ij_.row(vertex_non_compat_idx).setTo(weight2); g_ab_(vertex_non_compat_idx, vertex_non_compat_idx) = 0.f; g_ij_.col(vertex_non_compat_idx).setTo(weight2); g_ij_(vertex_non_compat_idx, vertex_non_compat_idx) = 0.f; // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); Mat1f c_ai = GraphCompatibility::Integrate(c_aibj, Mat1f(g_ab_.rows, g_ij_.rows, 1.f)); EXPECT_GT(c_ai(vertex_compat_idx, vertex_compat_idx), c_ai(vertex_non_compat_idx, vertex_non_compat_idx)) << "Score of compatible vertex should exceed that of non-compatible one."; } } } // annonymous namespace for test cases and fixtures <commit_msg>test protected method for individual compatibility score<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/graphcompatibility.h" #include "elm/core/featuredata.h" #include "elm/core/signal.h" #include "elm/core/layerconfig.h" #include "elm/layers/layerfactory.h" #include "elm/ts/layer_assertions.h" using namespace std; using namespace boost; using namespace cv; using namespace elm; namespace { ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(GraphCompatibility); const string NAME_GRAPH_AB = "G_ab"; const string NAME_GRAPH_IJ = "g_ij"; const string NAME_M = "m"; class GraphCompatibilityInitTest : public ::testing::Test { protected: virtual void SetUp() { LayerConfig cfg; LayerIONames io; io.Input(GraphCompatibility::KEY_INPUT_GRAPH_AB, NAME_GRAPH_AB); io.Input(GraphCompatibility::KEY_INPUT_GRAPH_IJ, NAME_GRAPH_IJ); io.Output(GraphCompatibility::KEY_OUTPUT_RESPONSE, NAME_M); to_ = LayerFactory::CreateShared("GraphCompatibility", cfg, io); } // members LayerFactory::LayerShared to_; ///< pointer to test object }; TEST_F(GraphCompatibilityInitTest, Constructor_overloaded) { LayerConfig cfg; EXPECT_NO_THROW(to_.reset(new GraphCompatibility(cfg))); } class GraphCompatibilityTest : public GraphCompatibilityInitTest { protected: virtual void SetUp() { GraphCompatibilityInitTest::SetUp(); // initialize test graphs const int A=4; ///< no. of nodes in G const int I=A; ///< no. of nodes in g // generate random adjacency matrices g_ab_ = Mat1f(A, A); Mat1i tmp(A, A); int s = 1000; randu(tmp, 0, s); g_ab_ = tmp/static_cast<float>(s); // distance from node to itself is 0 for(int r=0; r<g_ab_.rows; r++) { g_ab_(r, r) = 0.f; } // make symmetrical for(int r=0; r<g_ab_.rows; r++) { for(int c=0; c<g_ab_.rows; c++) { g_ab_(r, c) = g_ab_(c, r); } } g_ij_ = Mat1f(I, I); g_ij_ = g_ab_.clone(); // make them equal Mat1f noise(g_ij_.size()); randn(noise, 0.f, 0.02f); g_ij_ += noise; g_ij_.setTo(0.f, g_ij_ < 0.f); g_ij_.setTo(1.f, g_ij_ > 1.f); for(int r=0; r<g_ij_.rows; r++) { g_ij_(r, r) = 0.f; for(int c=0; c<g_ij_.cols; c++) { g_ij_(r, c) = g_ij_(c, r); } } // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); } virtual void TearDown() { sig_.Clear(); } // members Mat1f g_ab_; ///< adj. matrix for test graph Mat1f g_ij_; ///< adj. matrix for test graph Signal sig_; }; TEST_F(GraphCompatibilityTest, Activate_invalid_non_square_adj_mat) { g_ab_ = Mat1f::ones(11, 7) - Mat1f::eye(11, 7); g_ij_ = g_ab_.clone(); sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); EXPECT_THROW(to_->Activate(sig_), ExceptionBadDims); } TEST_F(GraphCompatibilityTest, Dims) { for(int A=1; A<10; A++) { for(int I=1; I<10; I++) { // generate random adjacency matrices g_ab_ = Mat1f(A, A, 1.f); g_ij_ = Mat1f(I, I, 1.f); sig_.Clear(); // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Clear(); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); ASSERT_EQ(4, c_aibj.dims()) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(A, c_aibj.size(0)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(I, c_aibj.size(1)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(A, c_aibj.size(2)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(I, c_aibj.size(3)) << "Match matrix should be of size (A, I, A, I)"; } } } /** * @brief graph without any connections should yield all-zero compatibility */ TEST_F(GraphCompatibilityTest, NoConnections) { const int NB_VERTICES = 5; g_ab_ = Mat1f::zeros(NB_VERTICES, NB_VERTICES); g_ij_ = g_ab_.clone(); // make them equal // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); ASSERT_EQ(4, c_aibj.dims()) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(0)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(1)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(2)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(NB_VERTICES, c_aibj.size(3)) << "Match matrix should be of size (A, I, A, I)"; EXPECT_EQ(static_cast<size_t>(0), c_aibj.nzcount()); } /** * @brief zero-compatibility for node without edges */ TEST_F(GraphCompatibilityTest, NoConnections_for_one_node_in_g_ab) { int vertex_idx = abs(randu<int>()) % g_ab_.rows; g_ab_.row(vertex_idx).setTo(0.f); g_ab_.col(vertex_idx).setTo(0.f); // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); for(int i=0; i<g_ij_.rows; i++) { for(int b=0; b<g_ab_.rows; b++) { for(int j=0; j<g_ij_.rows; j++) { int idx[4] = {vertex_idx, i, b, j}; EXPECT_FLOAT_EQ(0.f, c_aibj.ref(idx)) << "Expecting all-zero row for slice a=" << vertex_idx << " since this vertex doesn't have any edges"; } } } } /** * @brief zero-compatibility for node without edges */ TEST_F(GraphCompatibilityTest, NoConnections_for_one_node_in_g_ij) { int vertex_idx = abs(randu<int>()) % g_ij_.rows; g_ij_.row(vertex_idx).setTo(0.f); g_ij_.col(vertex_idx).setTo(0.f); // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); for(int a=0; a<g_ij_.rows; a++) { for(int b=0; b<g_ab_.rows; b++) { for(int j=0; j<g_ij_.rows; j++) { int idx[4] = {a, vertex_idx, b, j}; EXPECT_FLOAT_EQ(0.f, c_aibj.ref(idx)) << "Expecting all-zero row for slice i=" << vertex_idx << " since this vertex doesn't have any edges"; } } } } /** * @brief Make weights of two vertices very compatible and compare * their compatibility score with that of other nodes. * This test does not assume that both adjacency graphs share the same dimensions. */ TEST_F(GraphCompatibilityTest, CompatibilityIntegration) { // sanity check ASSERT_GT(g_ab_.rows, 1) << "this test requires adjacency graphs for graphs with > 1 vertex"; ASSERT_GT(g_ij_.rows, 1) << "this test requires adjacency graphs for graphs with > 1 vertex"; const int MIN_DIM = static_cast<int>(min(g_ab_.rows, g_ij_.rows)); const int N=5; // do this for multiple vertices for(int i=0; i<N; i++) { // make two vertices in both graph very compatible int vertex_compat_idx = abs(randu<int>()) % MIN_DIM; // actual weight value doesn't matter // it only matters that the edges in both graphs appear similar for a pair of vertices. int rand_value = static_cast<float>(abs(randu<int>()) % 100); float weight = rand_value/100.f; g_ab_.row(vertex_compat_idx).setTo(weight); g_ab_.col(vertex_compat_idx).setTo(weight); g_ab_(vertex_compat_idx, vertex_compat_idx) = 0.f; g_ij_.row(vertex_compat_idx).setTo(weight); g_ij_.col(vertex_compat_idx).setTo(weight); g_ij_(vertex_compat_idx, vertex_compat_idx) = 0.f; // make two other vertices in both graph very un-compatible int vertex_non_compat_idx = (vertex_compat_idx + 1) % MIN_DIM; g_ab_.row(vertex_non_compat_idx).setTo(weight); g_ab_.col(vertex_non_compat_idx).setTo(weight); // select second weight to be different from first for vertices to seem less compatible float weight2 = static_cast<float>(rand_value+30 % 100)/100.f; // sanity check ASSERT_GT(abs(weight-weight2), 0.25f) << "Difference between weights not large enough"; g_ij_.row(vertex_non_compat_idx).setTo(weight2); g_ab_(vertex_non_compat_idx, vertex_non_compat_idx) = 0.f; g_ij_.col(vertex_non_compat_idx).setTo(weight2); g_ij_(vertex_non_compat_idx, vertex_non_compat_idx) = 0.f; // add test graphs to signal sig_.Append(NAME_GRAPH_AB, g_ab_); sig_.Append(NAME_GRAPH_IJ, g_ij_); to_->Activate(sig_); to_->Response(sig_); SparseMat1f c_aibj = sig_.MostRecent(NAME_M).get<SparseMat1f>(); Mat1f c_ai = GraphCompatibility::Integrate(c_aibj, Mat1f(g_ab_.rows, g_ij_.rows, 1.f)); EXPECT_GT(c_ai(vertex_compat_idx, vertex_compat_idx), c_ai(vertex_non_compat_idx, vertex_non_compat_idx)) << "Score of compatible vertex should exceed that of non-compatible one."; } } class GraphCompatibilityProtected : public GraphCompatibility { public: float Compatibility(float w1, float w2) const { return GraphCompatibility::Compatibility(w1, w2); } }; class GraphCompatibilityProtectedTest : public ::testing::Test { }; TEST_F(GraphCompatibilityProtectedTest, Compatibility_weights) { GraphCompatibilityProtected to; ///< test object EXPECT_EQ(0.f, to.Compatibility(0.f, 1.f)); EXPECT_EQ(0.f, to.Compatibility(0.f, 3.f)); EXPECT_EQ(to.Compatibility(1.f, 0.f), to.Compatibility(0.f, 1.f)) << "compatibility is not symmetric"; EXPECT_EQ(to.Compatibility(0.3f, 0.f), to.Compatibility(0.f, 0.3f)) << "compatibility is not symmetric"; EXPECT_EQ(to.Compatibility(0.7, 0.3), to.Compatibility(0.3f, 0.7f)) << "compatibility is not symmetric"; } } // annonymous namespace for test cases and fixtures <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "BasicNNTrainer.h" #include "Sampler.h" registerMooseObject("StochasticToolsApp", BasicNNTrainer); InputParameters BasicNNTrainer::validParams() { InputParameters params = SurrogateTrainer::validParams(); params.addClassDescription("Computes coefficients for polynomial regession model."); MooseEnum data_type("real=0 vector_real=1", "real"); params.addRequiredParam<ReporterName>( "response", "Reporter value of response results, can be vpp with <vpp_name>/<vector_name> or sampler " "column with 'sampler/col_<index>'."); params.addParam<MooseEnum>("response_type", data_type, "Response data type."); params.addParam<std::vector<ReporterName>>( "predictors", std::vector<ReporterName>(), "Reporter values used as the independent random variables, If 'predictors' and " "'predictor_cols' are both empty, all sampler columns are used."); params.addParam<std::vector<unsigned int>>( "predictor_cols", std::vector<unsigned int>(), "Sampler columns used as the independent random variables, If 'predictors' and " "'predictor_cols' are both empty, all sampler columns are used."); params.addParam<unsigned int>("no_batches", 1, "Number of batches."); params.addParam<unsigned int>("no_epochs", 1, "Number of epochs."); params.addParam<unsigned int>("no_hidden_layers", 0, "Number of hidden layers."); params.addParam<std::vector<unsigned int>>( "no_neurons_per_layer", std::vector<unsigned int>(), "Number of neurons per layer."); params.addParam<Real>("learning_rate", 0.001, "Learning rate (relaxation)."); return params; } BasicNNTrainer::BasicNNTrainer(const InputParameters & parameters) : SurrogateTrainer(parameters), _sampler_row(getSamplerData()), _sample_points(declareModelData<std::vector<std::vector<Real>>>("_sample_points")), _pvals(getParam<std::vector<ReporterName>>("predictors").size()), _pcols(getParam<std::vector<unsigned int>>("predictor_cols")), _response(getTrainingData<Real>(getParam<ReporterName>("response"))), _no_batches(getParam<unsigned int>("no_batches")), _no_epocs(getParam<unsigned int>("no_epochs")), _no_hidden_layers(getParam<unsigned int>("no_hidden_layers")), _no_neurons_per_layer(getParam<std::vector<unsigned int>>("no_neurons_per_layer")), _learning_rate(getParam<Real>("learning_rate")) { const auto & pnames = getParam<std::vector<ReporterName>>("predictors"); for (unsigned int i = 0; i < pnames.size(); ++i) _pvals[i] = &getTrainingData<Real>(pnames[i]); // If predictors and predictor_cols are empty, use all sampler columns if (_pvals.empty() && _pcols.empty()) { _pcols.resize(_sampler.getNumberOfCols()); std::iota(_pcols.begin(), _pcols.end(), 0); } // Resize sample points to number of predictors _sample_points.resize(_pvals.size() + _pcols.size() + 1); if (_no_hidden_layers != _no_neurons_per_layer.size()) mooseError("The number of layers are not the same!"); } void BasicNNTrainer::preTrain() { // Resize to number of sample points for (auto & it : _sample_points) it.resize(_sampler.getNumberOfLocalRows()); } void BasicNNTrainer::train() { unsigned int d = 0; // Get predictors from reporter values for (const auto & val : _pvals) _sample_points[d++][_local_row] = *val; // Get predictors from sampler for (const auto & col : _pcols) _sample_points[d++][_local_row] = _sampler_row[col]; _sample_points.back()[_local_row] = _response; } void BasicNNTrainer::postTrain() { for (auto & it : _sample_points) _communicator.allgather(it); #ifdef ENABLE_TF // Linearizing the data to make sure we can stor it in a tensor // Fixing the RNG seed to make sure every experiment is the same. // Otherwise sampling / stochastic gradient descent would be different. torch::manual_seed(11); // Now we convert the internal data-structure to torch::Tensors std::vector<Real> flattened_data; std::vector<Real> flattened_response; // First, we flatten (serialize) out containers for (const auto & r : _sample_points) { if (&r == &_sample_points.back()) for (const auto & c : r) flattened_response.push_back(c); else for (const auto & c : r) flattened_data.push_back(c); } // Then, we create and load our Tensors int n_rows = _sample_points.size() - 1; int n_cols = _sample_points[0].size(); // The default data type in pytorch is float, while we use double in MOOSE. // Therefore, in some cases we have to convert Tensors to double. auto options = torch::TensorOptions().dtype(at::kDouble); torch::Tensor data_tensor = torch::from_blob(flattened_data.data(), {n_rows, n_cols}, options).to(at::kDouble); torch::Tensor response_tensor = torch::from_blob(flattened_response.data(), {n_cols}, options).to(at::kDouble); // We create a custom data loader which can be used to select samples for the in // the training process. See the header file for the definition of this structure. MyData my_data(data_tensor, response_tensor); // We initialize a data_loader for the training part. unsigned int sample_per_batch = n_cols > _no_batches ? n_cols / _no_batches : 1; auto data_loader = torch::data::make_data_loader<torch::data::samplers::SequentialSampler>( std::move(my_data.map(torch::data::transforms::Stack<>())), sample_per_batch); // We create a neural net (for the definition of the net see the header file) auto net = std::make_shared<MyNet>(n_rows, _no_hidden_layers, _no_neurons_per_layer, 1); // Initialize the optimizer torch::optim::Adam optimizer(net->parameters(), torch::optim::AdamOptions(_learning_rate)); // Begin training loop for (size_t epoch = 1; epoch <= _no_epocs; ++epoch) { size_t batch_index = 0; Real epoch_error = 0.0; for (auto & batch : *data_loader) { // Reset gradients optimizer.zero_grad(); // Compute prediction torch::Tensor prediction = net->forward(torch::transpose(batch.data, 1, 2)); // Compute loss values using a MSE ( mean squared error) torch::Tensor loss = torch::mse_loss(prediction, batch.target); // Propagate error back loss.backward(); // Use new gradients to update the parameters optimizer.step(); epoch_error += loss.item<double>(); } if (epoch % 10 == 0) std::cout << "Epoch: " << epoch << " | Loss: " << epoch_error << std::endl; } #endif } <commit_msg>Correct typo in comp command. (#19571)<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "BasicNNTrainer.h" #include "Sampler.h" registerMooseObject("StochasticToolsApp", BasicNNTrainer); InputParameters BasicNNTrainer::validParams() { InputParameters params = SurrogateTrainer::validParams(); params.addClassDescription("Computes coefficients for polynomial regession model."); MooseEnum data_type("real=0 vector_real=1", "real"); params.addRequiredParam<ReporterName>( "response", "Reporter value of response results, can be vpp with <vpp_name>/<vector_name> or sampler " "column with 'sampler/col_<index>'."); params.addParam<MooseEnum>("response_type", data_type, "Response data type."); params.addParam<std::vector<ReporterName>>( "predictors", std::vector<ReporterName>(), "Reporter values used as the independent random variables, If 'predictors' and " "'predictor_cols' are both empty, all sampler columns are used."); params.addParam<std::vector<unsigned int>>( "predictor_cols", std::vector<unsigned int>(), "Sampler columns used as the independent random variables, If 'predictors' and " "'predictor_cols' are both empty, all sampler columns are used."); params.addParam<unsigned int>("no_batches", 1, "Number of batches."); params.addParam<unsigned int>("no_epochs", 1, "Number of epochs."); params.addParam<unsigned int>("no_hidden_layers", 0, "Number of hidden layers."); params.addParam<std::vector<unsigned int>>( "no_neurons_per_layer", std::vector<unsigned int>(), "Number of neurons per layer."); params.addParam<Real>("learning_rate", 0.001, "Learning rate (relaxation)."); return params; } BasicNNTrainer::BasicNNTrainer(const InputParameters & parameters) : SurrogateTrainer(parameters), _sampler_row(getSamplerData()), _sample_points(declareModelData<std::vector<std::vector<Real>>>("_sample_points")), _pvals(getParam<std::vector<ReporterName>>("predictors").size()), _pcols(getParam<std::vector<unsigned int>>("predictor_cols")), _response(getTrainingData<Real>(getParam<ReporterName>("response"))), _no_batches(getParam<unsigned int>("no_batches")), _no_epocs(getParam<unsigned int>("no_epochs")), _no_hidden_layers(getParam<unsigned int>("no_hidden_layers")), _no_neurons_per_layer(getParam<std::vector<unsigned int>>("no_neurons_per_layer")), _learning_rate(getParam<Real>("learning_rate")) { const auto & pnames = getParam<std::vector<ReporterName>>("predictors"); for (unsigned int i = 0; i < pnames.size(); ++i) _pvals[i] = &getTrainingData<Real>(pnames[i]); // If predictors and predictor_cols are empty, use all sampler columns if (_pvals.empty() && _pcols.empty()) { _pcols.resize(_sampler.getNumberOfCols()); std::iota(_pcols.begin(), _pcols.end(), 0); } // Resize sample points to number of predictors _sample_points.resize(_pvals.size() + _pcols.size() + 1); if (_no_hidden_layers != _no_neurons_per_layer.size()) mooseError("The number of layers are not the same!"); } void BasicNNTrainer::preTrain() { // Resize to number of sample points for (auto & it : _sample_points) it.resize(_sampler.getNumberOfLocalRows()); } void BasicNNTrainer::train() { unsigned int d = 0; // Get predictors from reporter values for (const auto & val : _pvals) _sample_points[d++][_local_row] = *val; // Get predictors from sampler for (const auto & col : _pcols) _sample_points[d++][_local_row] = _sampler_row[col]; _sample_points.back()[_local_row] = _response; } void BasicNNTrainer::postTrain() { for (auto & it : _sample_points) _communicator.allgather(it); #ifdef ENABLE_PT // Linearizing the data to make sure we can stor it in a tensor // Fixing the RNG seed to make sure every experiment is the same. // Otherwise sampling / stochastic gradient descent would be different. torch::manual_seed(11); // Now we convert the internal data-structure to torch::Tensors std::vector<Real> flattened_data; std::vector<Real> flattened_response; // First, we flatten (serialize) out containers for (const auto & r : _sample_points) { if (&r == &_sample_points.back()) for (const auto & c : r) flattened_response.push_back(c); else for (const auto & c : r) flattened_data.push_back(c); } // Then, we create and load our Tensors int n_rows = _sample_points.size() - 1; int n_cols = _sample_points[0].size(); // The default data type in pytorch is float, while we use double in MOOSE. // Therefore, in some cases we have to convert Tensors to double. auto options = torch::TensorOptions().dtype(at::kDouble); torch::Tensor data_tensor = torch::from_blob(flattened_data.data(), {n_rows, n_cols}, options).to(at::kDouble); torch::Tensor response_tensor = torch::from_blob(flattened_response.data(), {n_cols}, options).to(at::kDouble); // We create a custom data loader which can be used to select samples for the in // the training process. See the header file for the definition of this structure. MyData my_data(data_tensor, response_tensor); // We initialize a data_loader for the training part. unsigned int sample_per_batch = n_cols > _no_batches ? n_cols / _no_batches : 1; auto data_loader = torch::data::make_data_loader<torch::data::samplers::SequentialSampler>( std::move(my_data.map(torch::data::transforms::Stack<>())), sample_per_batch); // We create a neural net (for the definition of the net see the header file) auto net = std::make_shared<MyNet>(n_rows, _no_hidden_layers, _no_neurons_per_layer, 1); // Initialize the optimizer torch::optim::Adam optimizer(net->parameters(), torch::optim::AdamOptions(_learning_rate)); // Begin training loop for (size_t epoch = 1; epoch <= _no_epocs; ++epoch) { size_t batch_index = 0; Real epoch_error = 0.0; for (auto & batch : *data_loader) { // Reset gradients optimizer.zero_grad(); // Compute prediction torch::Tensor prediction = net->forward(torch::transpose(batch.data, 1, 2)); // Compute loss values using a MSE ( mean squared error) torch::Tensor loss = torch::mse_loss(prediction, batch.target); // Propagate error back loss.backward(); // Use new gradients to update the parameters optimizer.step(); epoch_error += loss.item<double>(); } if (epoch % 10 == 0) std::cout << "Epoch: " << epoch << " | Loss: " << epoch_error << std::endl; } #endif } <|endoftext|>
<commit_before>#include <stdio.h> #include <conio.h> #include <stdlib.h> #include <string.h> //Criao da estrutura para AP2 typedef struct { int codigo; char raca[30], nome[100]; } registro; typedef struct { int codigo, offset; } indice1; typedef struct { char vacina[30]; int offset; } indice2; int Menu(); void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2); void CadastraVacina(FILE **AP1, FILE **AP2); void CadastraCachorro(FILE **AP2); void AtualizaInfoIndice(char status, FILE **arq); int ExisteCachorro(int codigo, FILE **AP2); int ProcuraEspacoVazio(FILE **AP1, int tam_reg); void AlteraCachorro(FILE **AP2); int main() { int opcao; FILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2; AbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2); opcao = Menu(); while (1) { switch(opcao) { case 1: CadastraCachorro(&AP2); break; case 2: CadastraVacina(&AP1, &AP2); break; case 3: AlteraCachorro(&AP2); break; case 0: printf("\nSaindo do Programa..."); fclose(AP1); fclose(AP2); //fecha arquivos principais fclose(IndPrim); fclose(IndSec1); fclose(IndSec2); //fecha ndices getch(); break; default: printf("\nOpcao invalida!"); getch(); break; } opcao = Menu(); } return 0; } /* DESCRIO: Exibe as opes do menu. RETORNO: O nmero da opo escolhida pelo usurio */ int Menu() { int opcao; system("CLS"); printf("\n 1 - Cadastra Cachorro"); printf("\n 2 - Cadastra Vacina"); printf("\n3 - Altera Cachorro"); printf("\n 0 - Sair"); printf("\n\nEscolha a opcao: "); scanf("%d", &opcao); return opcao; } /* DESCRIO: Verifica os arquivos j foram criados. Se no, cria-os. PARMETROS: AP1 - Arquivo Principal 1 AP2 - Arquivo Principal 2 IndPrim - Arquivo de ndice (busca por chave primria) IndSec1 - Arquivo de ndice 1 (busca por chave secundria) IndSec2 - Arquivo de ndice 2 (busca por chave secundria) */ void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2) { int header = -1; /*No primeiro caso, ele entra no if pois o arquivo ainda no existe (Com o uso do r+b o arquivo tem que existir). A ento ele cria o arquivo com w+b*/ if ((*AP1 = fopen("AP1.bin", "r+b")) == NULL) //se o arquivo no exisitr { *AP1 = fopen("AP1.bin", "w+b"); //cria um novo arquivo vazio (AP1) fwrite(&header, sizeof(int), 1, *AP1); *IndPrim = fopen("IndPrim.bin", "w+b"); AtualizaInfoIndice('!', IndPrim); *IndSec1 = fopen("IndSec1.bin", "w+b"); AtualizaInfoIndice('!', IndSec1); *IndSec2 = fopen("IndSec2.bin", "w+b"); AtualizaInfoIndice('!', IndSec2); } /*else if (ExigeRecriaIndice(IndPrim)) { RecriaIndicePrim(AP1); QuickSortInd1(INDEX1, 0, tam1); } else { IndPrim = fopen("IndPrim.bin", "r+b"); CarregaIndice(IndPrim, 1); IndSec1 = fopen("IndSec1.bin", "r+b"); CarregaIndice(IndSec1, 2); IndSec2 = fopen("IndSec2.bin", "r+b"); CarregaIndice(IndSec2, 1); }*/ if ((*AP2 = fopen("AP2.bin", "r+b")) == NULL) //se o arquivo no existir *AP2 = fopen("AP2.bin", "w+b"); //cria um novo arquivo vazio (AP2) } /* DESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2 PARMETROS: AP2 - Arquivo Principal 2 */ void CadastraCachorro(FILE **AP2) { registro reg; system("CLS"); printf("\nCodigo: "); scanf("%d", &reg.codigo); while (ExisteCachorro(reg.codigo, AP2)) { system("CLS"); printf("\nCodigo ja cadastrado. Digite novamente!"); getch(); system("CLS"); printf("\nCodigo: "); scanf("%d", &reg.codigo); } fflush(stdin); printf("Raca: "); gets(reg.raca); printf("Nome do Cachorro: "); gets(reg.nome); fseek(*AP2, 0, SEEK_END); //seta a posio para o fim do arquivo. fwrite(&reg, sizeof(reg), 1, *AP2); //escreve no fim do arquivo. } /* DESCRIO: Atualiza o header do ndice com o status de atualizao PARMETROS: status - '*' - ndice atualizado '!' - ndice desatualizado arq - ndice a ser atualizado */ void AtualizaInfoIndice(char status, FILE **arq) { fseek(*arq, 0, SEEK_SET); fputc(status, *arq); } /* DESCRIO: Verifica se o cdigo j existe no arquivo. PARMETROS: codigo - Cdigo a ser verificado AP2 - Arquivo Principal 2 RETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro 1 - Existe um cachorro com o cdigo passado por parmetro */ int ExisteCachorro(int codigo, FILE **AP2) { registro reg; rewind(*AP2); while (fread(&reg, sizeof(registro), 1, *AP2)) { if (reg.codigo == codigo) { return 1; break; } } return 0; } /* DESCRIO: Realiza o cadastro de vacinas PARMETROS: AP1 - Arquivo principal 1 AP2 - Arquivo principal 2 */ void CadastraVacina(FILE **AP1, FILE **AP2) { int cod_controle = 0, cod_cachorro, tam_reg, posicao, aux = 0; char verificador = '*', vacina[30], data[6], respo[100], registro[255]; system("CLS"); printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: "); scanf("%d", &cod_cachorro); if (cod_cachorro == -1) CadastraCachorro(AP2); else { while (!ExisteCachorro(cod_cachorro, AP2)) { if (!aux) printf("\n Cachorro inexistente. Digite novamente!"); else printf("\n Nova busca..." ); getch(); system("CLS"); printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: "); scanf("%d", &cod_cachorro); if (cod_cachorro == -1) { CadastraCachorro(AP2); aux = 1; } } system("CLS"); cod_controle++;//cod_controle = pegar do INDEX1 ordenado; printf("\n Codigo do cachorro: %d", cod_cachorro); fflush(stdin); printf("\n\n Nome da vacina: "); gets(vacina); printf("\n Data de vacinacao <MM/AA>: "); gets(data); printf("\n Responsavel pela aplicacao: "); gets(respo); sprintf(registro, "%d|%d|%s|%s|%s|", cod_controle, cod_cachorro, vacina, data, respo); tam_reg = strlen(registro); posicao = ProcuraEspacoVazio(AP1, tam_reg); if (posicao != -1) fseek(*AP1, posicao, SEEK_SET); else fseek(*AP1, 0, SEEK_END); fwrite(&tam_reg, sizeof(int), 1, *AP1); fwrite(&verificador, sizeof(char), 1, *AP1); fwrite(registro, sizeof(char), tam_reg, *AP1); } } /* DESCRIO: Retorna o espao vazio encontrado no arquivo PARMETROS: AP1 - Arquivo principal 1 tam_reg - tamanho do registro a ser inserido RETORNO: posio livre para ser escrita */ int ProcuraEspacoVazio(FILE **AP1, int tam_reg) { int offset, tam, pos; char ch; rewind(*AP1); fread(&offset, sizeof(int), 1, *AP1); if (offset == -1) return -1; else { fseek(*AP1, offset, SEEK_SET); pos = ftell(*AP1); while (fread(&tam, sizeof(int), 1, *AP1)) { if (tam == -1) { return -1; break; } else { ch = fgetc(*AP1); if ((tam > tam_reg) && (ch == '!')) { return pos; break; } else { fread(&offset, sizeof(int), 1, *AP1); fseek(*AP1, offset, SEEK_SET); } } } } } /* DESCRIO: Altera dados de um cachorro PARMETRO: AP2 - arquivo principal 2 */ void AlteraCachorro(FILE **AP2) { int op, cod, i = 0; char raca[30], nome[100]; registro reg; system("CLS"); printf("Digite o codigo do cachorro: "); scanf("%d", &cod); while (!ExisteCachorro(cod, AP2)) { system("CLS"); printf("\n\nCachorro inexistente. Digite novamente!"); getch(); system("CLS"); printf("\n\nDigite o codigo do cachorro: "); scanf("%d", &cod); } rewind(*AP2); while (fread(&reg, sizeof(reg), 1, *AP2)) { if (reg.codigo == cod) break; i++; } system("CLS"); printf("Qual campo deseja alterar"); printf("\n\n1 - Raca"); printf("\n2 - Nome"); printf("\n\nEscolha a opcao: "); scanf("%d", &op); while ((op != 1) && (op != 2)) { system("CLS"); printf("Opcao invalida. Digite novamente!"); getch(); system("CLS"); printf("Qual campo deseja alterar"); printf("\n\n1 - Raca"); printf("\n2 - Nome"); printf("\n\nEscolha a opcao: "); scanf("%d", op); } fflush(stdin); system("CLS"); switch(op) { case 1: printf("Digite a nova raca: "); gets(raca); strcpy(reg.raca, raca); break; case 2: printf("Digite o novo nome: "); gets(nome); strcpy(reg.nome, nome); break; } fseek(*AP2, sizeof(reg)*i, SEEK_SET); fwrite(&reg, sizeof(reg), 1, *AP2); } <commit_msg>teste 2<commit_after>#include <stdio.h> #include <conio.h> #include <stdlib.h> #include <string.h> //Criao da estrutura para AP2 typedef struct { int codigo; char raca[30], nome[100]; } registro; typedef struct { int codigo, offset; } indice1; typedef struct { char vacina[30]; int offset; } indice2; int Menu(); void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2); void CadastraVacina(FILE **AP1, FILE **AP2); void CadastraCachorro(FILE **AP2); void AtualizaInfoIndice(char status, FILE **arq); int ExisteCachorro(int codigo, FILE **AP2); int ProcuraEspacoVazio(FILE **AP1, int tam_reg); void AlteraCachorro(FILE **AP2); int main() { int opcao; FILE *AP1, *AP2, *IndPrim, *IndSec1, *IndSec2; AbreArquivos(&AP1, &AP2, &IndPrim, &IndSec1, &IndSec2); opcao = Menu(); while (1) { switch(opcao) { case 1: CadastraCachorro(&AP2); break; case 2: CadastraVacina(&AP1, &AP2); break; case 3: AlteraCachorro(&AP2); break; case 0: printf("\nSaindo do Programa..."); fclose(AP1); fclose(AP2); //fecha arquivos principais fclose(IndPrim); fclose(IndSec1); fclose(IndSec2); //fecha ndices getch(); break; default: printf("\nOpcao invalida!"); getch(); break; } opcao = Menu(); } return 0; } /* DESCRIO: Exibe as opes do menu. RETORNO: O nmero da opo escolhida pelo usurio */ int Menu() { int opcao; system("CLS"); printf("\n 1 - Cadastra Cachorro"); printf("\n 2 - Cadastra Vacina"); printf("\n3 - Altera Cachorro"); printf("\n 0 - Sair"); printf("\n\nEscolha a opcao: "); scanf("%d", &opcao); return opcao; } /* DESCRIO: Verifica se os arquivos j foram criados. Se no, cria-os. PARMETROS: AP1 - Arquivo Principal 1 AP2 - Arquivo Principal 2 IndPrim - Arquivo de ndice (busca por chave primria) IndSec1 - Arquivo de ndice 1 (busca por chave secundria) IndSec2 - Arquivo de ndice 2 (busca por chave secundria) */ void AbreArquivos(FILE **AP1, FILE **AP2, FILE **IndPrim, FILE **IndSec1, FILE **IndSec2) { int header = -1; /*No primeiro caso, ele entra no if pois o arquivo ainda no existe (Com o uso do r+b o arquivo tem que existir). A ento ele cria o arquivo com w+b*/ if ((*AP1 = fopen("AP1.bin", "r+b")) == NULL) //se o arquivo no exisitr { *AP1 = fopen("AP1.bin", "w+b"); //cria um novo arquivo vazio (AP1) fwrite(&header, sizeof(int), 1, *AP1); *IndPrim = fopen("IndPrim.bin", "w+b"); AtualizaInfoIndice('!', IndPrim); *IndSec1 = fopen("IndSec1.bin", "w+b"); AtualizaInfoIndice('!', IndSec1); *IndSec2 = fopen("IndSec2.bin", "w+b"); AtualizaInfoIndice('!', IndSec2); } /*else if (ExigeRecriaIndice(IndPrim)) { RecriaIndicePrim(AP1); QuickSortInd1(INDEX1, 0, tam1); } else { IndPrim = fopen("IndPrim.bin", "r+b"); CarregaIndice(IndPrim, 1); IndSec1 = fopen("IndSec1.bin", "r+b"); CarregaIndice(IndSec1, 2); IndSec2 = fopen("IndSec2.bin", "r+b"); CarregaIndice(IndSec2, 1); }*/ if ((*AP2 = fopen("AP2.bin", "r+b")) == NULL) //se o arquivo no existir *AP2 = fopen("AP2.bin", "w+b"); //cria um novo arquivo vazio (AP2) } /* DESCRIO: Cadastra informaes de um cachorro no Arquivo Principal 2 PARMETROS: AP2 - Arquivo Principal 2 */ void CadastraCachorro(FILE **AP2) { registro reg; system("CLS"); printf("\nCodigo: "); scanf("%d", &reg.codigo); while (ExisteCachorro(reg.codigo, AP2)) { system("CLS"); printf("\nCodigo ja cadastrado. Digite novamente!"); getch(); system("CLS"); printf("\nCodigo: "); scanf("%d", &reg.codigo); } fflush(stdin); printf("Raca: "); gets(reg.raca); printf("Nome do Cachorro: "); gets(reg.nome); fseek(*AP2, 0, SEEK_END); //seta a posio para o fim do arquivo. fwrite(&reg, sizeof(reg), 1, *AP2); //escreve no fim do arquivo. } /* DESCRIO: Atualiza o header do ndice com o status de atualizao PARMETROS: status - '*' - ndice atualizado '!' - ndice desatualizado arq - ndice a ser atualizado */ void AtualizaInfoIndice(char status, FILE **arq) { fseek(*arq, 0, SEEK_SET); fputc(status, *arq); } /* DESCRIO: Verifica se o cdigo j existe no arquivo. PARMETROS: codigo - Cdigo a ser verificado AP2 - Arquivo Principal 2 RETORNOS: 0 - No existe um cachorro com o cdigo passado por parmetro 1 - Existe um cachorro com o cdigo passado por parmetro */ int ExisteCachorro(int codigo, FILE **AP2) { registro reg; rewind(*AP2); while (fread(&reg, sizeof(registro), 1, *AP2)) { if (reg.codigo == codigo) { return 1; break; } } return 0; } /* DESCRIO: Realiza o cadastro de vacinas PARMETROS: AP1 - Arquivo principal 1 AP2 - Arquivo principal 2 */ void CadastraVacina(FILE **AP1, FILE **AP2) { int cod_controle = 0, cod_cachorro, tam_reg, posicao, aux = 0; char verificador = '*', vacina[30], data[6], respo[100], registro[255]; system("CLS"); printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: "); scanf("%d", &cod_cachorro); if (cod_cachorro == -1) CadastraCachorro(AP2); else { while (!ExisteCachorro(cod_cachorro, AP2)) { if (!aux) printf("\n Cachorro inexistente. Digite novamente!"); else printf("\n Nova busca..." ); getch(); system("CLS"); printf("\n Digite o codigo do cachorro <-1 para cadastrar um cachorro>: "); scanf("%d", &cod_cachorro); if (cod_cachorro == -1) { CadastraCachorro(AP2); aux = 1; } } system("CLS"); cod_controle++;//cod_controle = pegar do INDEX1 ordenado; printf("\n Codigo do cachorro: %d", cod_cachorro); fflush(stdin); printf("\n\n Nome da vacina: "); gets(vacina); printf("\n Data de vacinacao <MM/AA>: "); gets(data); printf("\n Responsavel pela aplicacao: "); gets(respo); sprintf(registro, "%d|%d|%s|%s|%s|", cod_controle, cod_cachorro, vacina, data, respo); tam_reg = strlen(registro); posicao = ProcuraEspacoVazio(AP1, tam_reg); if (posicao != -1) fseek(*AP1, posicao, SEEK_SET); else fseek(*AP1, 0, SEEK_END); fwrite(&tam_reg, sizeof(int), 1, *AP1); fwrite(&verificador, sizeof(char), 1, *AP1); fwrite(registro, sizeof(char), tam_reg, *AP1); } } /* DESCRIO: Retorna o espao vazio encontrado no arquivo PARMETROS: AP1 - Arquivo principal 1 tam_reg - tamanho do registro a ser inserido RETORNO: posio livre para ser escrita */ int ProcuraEspacoVazio(FILE **AP1, int tam_reg) { int offset, tam, pos; char ch; rewind(*AP1); fread(&offset, sizeof(int), 1, *AP1); if (offset == -1) return -1; else { fseek(*AP1, offset, SEEK_SET); pos = ftell(*AP1); while (fread(&tam, sizeof(int), 1, *AP1)) { if (tam == -1) { return -1; break; } else { ch = fgetc(*AP1); if ((tam > tam_reg) && (ch == '!')) { return pos; break; } else { fread(&offset, sizeof(int), 1, *AP1); fseek(*AP1, offset, SEEK_SET); } } } } } /* DESCRIO: Altera dados de um cachorro PARMETRO: AP2 - arquivo principal 2 */ void AlteraCachorro(FILE **AP2) { int op, cod, i = 0; char raca[30], nome[100]; registro reg; system("CLS"); printf("Digite o codigo do cachorro: "); scanf("%d", &cod); while (!ExisteCachorro(cod, AP2)) { system("CLS"); printf("\n\nCachorro inexistente. Digite novamente!"); getch(); system("CLS"); printf("\n\nDigite o codigo do cachorro: "); scanf("%d", &cod); } rewind(*AP2); while (fread(&reg, sizeof(reg), 1, *AP2)) { if (reg.codigo == cod) break; i++; } system("CLS"); printf("Qual campo deseja alterar"); printf("\n\n1 - Raca"); printf("\n2 - Nome"); printf("\n\nEscolha a opcao: "); scanf("%d", &op); while ((op != 1) && (op != 2)) { system("CLS"); printf("Opcao invalida. Digite novamente!"); getch(); system("CLS"); printf("Qual campo deseja alterar"); printf("\n\n1 - Raca"); printf("\n2 - Nome"); printf("\n\nEscolha a opcao: "); scanf("%d", op); } fflush(stdin); system("CLS"); switch(op) { case 1: printf("Digite a nova raca: "); gets(raca); strcpy(reg.raca, raca); break; case 2: printf("Digite o novo nome: "); gets(nome); strcpy(reg.nome, nome); break; } fseek(*AP2, sizeof(reg)*i, SEEK_SET); fwrite(&reg, sizeof(reg), 1, *AP2); } <|endoftext|>
<commit_before>#include "tlang.h" #include <taichi/util.h> #include <taichi/visual/gui.h> #include <taichi/common/bit.h> TC_NAMESPACE_BEGIN using namespace Tlang; Matrix outer_product(Vector a, Vector b) { TC_ASSERT(a.m == 1); TC_ASSERT(b.m == 1); Matrix m(a.n, b.n); for (int i = 0; i < a.n; i++) { for (int j = 0; j < b.n; j++) { m(i, j) = a(i) * b(j); } } return m; } auto mpm = []() { bool use_adapter = true; constexpr int n = 64; // grid_resolution const real dt = 3e-5_f, frame_dt = 1e-3_f, dx = 1.0_f / n, inv_dx = 1.0_f / dx; auto particle_mass = 1.0_f, vol = 1.0_f; auto hardening = 10.0_f, E = 1e0_f, nu = 0.2_f; real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1 + nu) * (1 - 2 * nu)); int dim = 2; Vector particle_x(dim), particle_v(dim); Matrix particle_F(dim, dim), particle_C(dim, dim); Real particle_J; Vector grid_v(dim); Real grid_m; Real Jp; int n_particles = 800; Program prog(Arch::x86_64, n_particles); prog.general_scatter = true; prog.config.group_size = 1; prog.config.num_groups = 8; prog.layout([&]() { int counter = 0; auto place = [&](Expr &expr) { prog.buffer(0).range(n_particles).stream(counter++).group(0).place(expr); }; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { place(particle_C(i, j)); } place(particle_x(i)); place(particle_v(i)); } place(particle_J); prog.buffer(1).range(n * n).stream().group().place(grid_v(0), grid_v(1), grid_m); /* for (int k = 0; k < 2; k++) { prog.buffer(k).range(n * n).stream(i).group(0).place(attr[k][i]); } prog.buffer(2).range(n * n).stream(k).group(0).place(v[k]); */ }); TC_ASSERT(bit::is_power_of_two(n)); auto p2g = prog.def([&]() { auto index = Expr::index(0); for_loop(index, {0, n_particles}, [&] { auto x = particle_x[index]; auto v = particle_v[index]; // auto F = particle_F[index]; auto C = particle_C[index]; auto J = particle_J[index]; // ** gs = 2 auto base_coord = floor(imm(inv_dx) * x - imm(0.5_f)); auto fx = x * imm(inv_dx) - base_coord; Vector w[3]; w[0] = imm(0.5_f) * sqr(imm(1.5_f) - fx); w[1] = imm(0.75_f) - sqr(fx - imm(1.0_f)); w[2] = imm(0.5_f) * sqr(fx - imm(0.5_f)); auto cauchy = imm(E) * (J - imm(1.0_f)); auto stress = imm(-4 * inv_dx * inv_dx * dt * vol) * cauchy; auto affine = stress;// + imm(particle_mass) * C; // auto J = F(0, 0) * F(1, 1) - F(1, 0) * F(0, 1); auto base_offset = cast<int>(base_coord(0)) * imm(n) + cast<int>(base_coord(1)); // scatter for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { auto dpos = Vector(dim); dpos(0) = cast<float32>(imm(i)) - fx(0); dpos(1) = cast<float32>(imm(j)) - fx(1); auto weight = w[i](0) * w[j](1); auto node = base_offset + imm(i * n + j); grid_v[node] = grid_v[node] + weight * v + affine * dpos; grid_m[node] = grid_m[node] + imm(particle_mass) * weight; } } }); }); p2g(); auto grid_op = [&]() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { auto &v0 = prog.data(grid_v(0), i * n + j); auto &v1 = prog.data(grid_v(1), i * n + j); auto &m = prog.data(grid_m, i * n + j); if (m > 0) { v0 /= m; v1 /= m; v1 += dt * -200; } if (j < 5 || i < 5 || i > n - 5 || j > n - 5) { v0 = 0; v1 = 0; } } } }; auto g2p = prog.def([&]() { auto index = Expr::index(0); for_loop(index, {0, n_particles}, [&]() { auto x = particle_x[index]; auto v = Vector(dim); // auto F = particle_F[index]; auto C = Matrix(dim, dim); auto J = particle_J[index]; for (int i = 0; i < dim; i++) { v(i) = imm(0.0_f); for (int j = 0; j < dim; j++) { C(i, j) = imm(0.0_f); } } auto base_coord = floor(imm(inv_dx) * x - imm(0.5_f)); auto fx = x * imm(inv_dx) - base_coord; Vector w[3]; w[0] = imm(0.5_f) * sqr(imm(1.5_f) - fx); w[1] = imm(0.75_f) - sqr(fx - imm(1.0_f)); w[2] = imm(0.5_f) * sqr(fx - imm(0.5_f)); // auto J = F(0, 0) * F(1, 1) - F(1, 0) * F(0, 1); auto base_offset = cast<int>(base_coord(0)) * imm(n) + cast<int>(base_coord(1)); // scatter for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { auto dpos = Vector(dim); dpos(0) = cast<float32>(imm(i)) - fx(0); dpos(1) = cast<float32>(imm(j)) - fx(1); auto weight = w[i](0) * w[j](1); auto node = base_offset + imm(i * n + j); v = v + weight * grid_v[node]; C = C + imm(4 * inv_dx) * outer_product(weight * grid_v[node], dpos); } } J = J * (imm(1.0_f) + imm(dt) * (C(0, 0) + C(1, 1))); // particle_C[index] = C; particle_v[index] = v; particle_J[index] = J; x = x + imm(dt) * v; particle_x[index] = x; }); }); int scale = 8; GUI gui("MPM", n * scale, n * scale); for (int i = 0; i < n_particles; i++) { prog.data(particle_x(0), i) = 0.4_f + rand() * 0.2_f; prog.data(particle_x(1), i) = 0.4_f + rand() * 0.2_f; prog.data(particle_v(1), i) = -0.3_f; prog.data(particle_J, i) = 1_f; } for (int f = 0; f < 1000; f++) { for (int t = 0; t < 100; t++) { prog.clear_buffer(1); TC_TIME(p2g()); TC_TIME(grid_op()); TC_TIME(g2p()); } for (int i = 0; i < n * scale; i++) { for (int j = 0; j < n * scale; j++) { gui.buffer[i][j].x = prog.data(grid_v(0), i / scale * n + j / scale) + 0.5; gui.buffer[i][j].y = prog.data(grid_v(1), i / scale * n + j / scale) + 0.5; gui.buffer[i][j].z = prog.data(grid_m, i / scale * n + j / scale) / particle_mass * 0.0 + 0.5; } } gui.update(); // gui.screenshot(fmt::format("images/{:04d}.png", f)); } }; TC_REGISTER_TASK(mpm); TC_NAMESPACE_END /* TODO: arbitrary for loop (bounds using arbitrary constants) */ <commit_msg>water works<commit_after>#include "tlang.h" #include <taichi/util.h> #include <taichi/visual/gui.h> #include <taichi/common/bit.h> TC_NAMESPACE_BEGIN using namespace Tlang; Matrix outer_product(Vector a, Vector b) { TC_ASSERT(a.m == 1); TC_ASSERT(b.m == 1); Matrix m(a.n, b.n); for (int i = 0; i < a.n; i++) { for (int j = 0; j < b.n; j++) { m(i, j) = a(i) * b(j); } } return m; } auto mpm = []() { bool use_adapter = true; constexpr int n = 64; // grid_resolution const real dt = 3e-5_f, frame_dt = 1e-3_f, dx = 1.0_f / n, inv_dx = 1.0_f / dx; auto particle_mass = 1.0_f, vol = 1.0_f; auto hardening = 10.0_f, E = 1e3_f, nu = 0.2_f; real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1 + nu) * (1 - 2 * nu)); int dim = 2; Vector particle_x(dim), particle_v(dim); Matrix particle_F(dim, dim), particle_C(dim, dim); Real particle_J; Vector grid_v(dim); Real grid_m; Real Jp; int n_particles = 800; Program prog(Arch::x86_64, n_particles); prog.general_scatter = true; prog.config.group_size = 1; prog.config.num_groups = 8; prog.layout([&]() { int counter = 0; auto place = [&](Expr &expr) { prog.buffer(0).range(n_particles).stream(counter++).group(0).place(expr); }; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { place(particle_C(i, j)); } place(particle_x(i)); place(particle_v(i)); } place(particle_J); prog.buffer(1).range(n * n).stream().group().place(grid_v(0), grid_v(1), grid_m); /* for (int k = 0; k < 2; k++) { prog.buffer(k).range(n * n).stream(i).group(0).place(attr[k][i]); } prog.buffer(2).range(n * n).stream(k).group(0).place(v[k]); */ }); TC_ASSERT(bit::is_power_of_two(n)); auto p2g = prog.def([&]() { auto index = Expr::index(0); for_loop(index, {0, n_particles}, [&] { auto x = particle_x[index]; auto v = particle_v[index]; // auto F = particle_F[index]; auto C = particle_C[index]; auto J = particle_J[index]; // ** gs = 2 auto base_coord = floor(imm(inv_dx) * x - imm(0.5_f)); auto fx = x * imm(inv_dx) - base_coord; Vector w[3]; w[0] = imm(0.5_f) * sqr(imm(1.5_f) - fx); w[1] = imm(0.75_f) - sqr(fx - imm(1.0_f)); w[2] = imm(0.5_f) * sqr(fx - imm(0.5_f)); auto cauchy = imm(E) * (J - imm(1.0_f)); auto affine = imm(particle_mass) * C; for (int i = 0; i < dim; i++) { affine(i, i) = affine(i, i) + imm(-4 * inv_dx * inv_dx * dt * vol) * cauchy; } // auto J = F(0, 0) * F(1, 1) - F(1, 0) * F(0, 1); auto base_offset = cast<int>(base_coord(0)) * imm(n) + cast<int>(base_coord(1)); // scatter for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { auto dpos = Vector(dim); dpos(0) = imm(dx) * (cast<float32>(imm(i)) - fx(0)); dpos(1) = imm(dx) * (cast<float32>(imm(j)) - fx(1)); auto weight = w[i](0) * w[j](1); auto node = base_offset + imm(i * n + j); grid_v[node] = grid_v[node] + weight * (imm(particle_mass) * v + affine * dpos); grid_m[node] = grid_m[node] + imm(particle_mass) * weight; } } }); }); p2g(); auto grid_op = [&]() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { auto &v0 = prog.data(grid_v(0), i * n + j); auto &v1 = prog.data(grid_v(1), i * n + j); auto &m = prog.data(grid_m, i * n + j); if (m > 0) { v0 /= m; v1 /= m; v1 += dt * -200; } if (j < 5 || i < 5 || i > n - 5 || j > n - 5) { v0 = 0; v1 = 0; } } } }; auto g2p = prog.def([&]() { auto index = Expr::index(0); for_loop(index, {0, n_particles}, [&]() { auto x = particle_x[index]; auto v = Vector(dim); // auto F = particle_F[index]; auto C = Matrix(dim, dim); auto J = particle_J[index]; for (int i = 0; i < dim; i++) { v(i) = imm(0.0_f); for (int j = 0; j < dim; j++) { C(i, j) = imm(0.0_f); } } auto base_coord = floor(imm(inv_dx) * x - imm(0.5_f)); auto fx = x * imm(inv_dx) - base_coord; Vector w[3]; w[0] = imm(0.5_f) * sqr(imm(1.5_f) - fx); w[1] = imm(0.75_f) - sqr(fx - imm(1.0_f)); w[2] = imm(0.5_f) * sqr(fx - imm(0.5_f)); // auto J = F(0, 0) * F(1, 1) - F(1, 0) * F(0, 1); auto base_offset = cast<int>(base_coord(0)) * imm(n) + cast<int>(base_coord(1)); // scatter for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { auto dpos = Vector(dim); dpos(0) = cast<float32>(imm(i)) - fx(0); dpos(1) = cast<float32>(imm(j)) - fx(1); auto weight = w[i](0) * w[j](1); auto node = base_offset + imm(i * n + j); v = v + weight * grid_v[node]; C = C + imm(4 * inv_dx) * outer_product(weight * grid_v[node], dpos); } } J = J * (imm(1.0_f) + imm(dt) * (C(0, 0) + C(1, 1))); particle_C[index] = C; particle_v[index] = v; particle_J[index] = J; x = x + imm(dt) * v; particle_x[index] = x; }); }); int scale = 8; GUI gui("MPM", n * scale, n * scale); for (int i = 0; i < n_particles; i++) { prog.data(particle_x(0), i) = 0.4_f + rand() * 0.2_f; prog.data(particle_x(1), i) = 0.4_f + rand() * 0.2_f; prog.data(particle_v(1), i) = -0.3_f; prog.data(particle_J, i) = 1_f; } for (int f = 0; f < 1000; f++) { for (int t = 0; t < 100; t++) { prog.clear_buffer(1); TC_TIME(p2g()); TC_TIME(grid_op()); TC_TIME(g2p()); } for (int i = 0; i < n * scale; i++) { for (int j = 0; j < n * scale; j++) { gui.buffer[i][j].x = prog.data(grid_v(0), i / scale * n + j / scale) + 0.5; gui.buffer[i][j].y = prog.data(grid_v(1), i / scale * n + j / scale) + 0.5; gui.buffer[i][j].z = prog.data(grid_m, i / scale * n + j / scale) / particle_mass * 0.0 + 0.5; } } gui.update(); // gui.screenshot(fmt::format("images/{:04d}.png", f)); } }; TC_REGISTER_TASK(mpm); TC_NAMESPACE_END /* TODO: arbitrary for loop (bounds using arbitrary constants) */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scmdstrm.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-20 00:24:09 $ * * 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 * ************************************************************************/ #ifndef _SCMDSTRM_HXX #define _SCMDSTRM_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #include "cmdbasestream.hxx" class SvStream; class SfxPoolItem; class String; class ICommStream; class SCmdStream: public CmdBaseStream { SvStream *pSammel; public: SCmdStream( SvStream *pIn ); ~SCmdStream(); using CmdBaseStream::Read; void Read ( comm_USHORT &nNr ){CmdBaseStream::Read ( nNr );} void Read ( comm_ULONG &nNr ){CmdBaseStream::Read ( nNr );} // void Read ( comm_UniChar* &aString, comm_USHORT &nLenInChars ){CmdBaseStream::Read ( aString, nLenInChars );} void Read ( comm_BOOL &bBool ){CmdBaseStream::Read ( bBool );} // new void Read ( String &aString ); void Read ( SfxPoolItem *&pItem ); void Read ( ::com::sun::star::beans::PropertyValue &rItem ); virtual void Read (String* &pString); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.104); FILE MERGED 2008/04/01 15:00:03 thb 1.4.104.3: #i85898# Stripping all external header guards 2008/04/01 10:47:19 thb 1.4.104.2: #i85898# Stripping all external header guards 2008/03/28 16:03:38 rt 1.4.104.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scmdstrm.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SCMDSTRM_HXX #define _SCMDSTRM_HXX #include <tools/solar.h> #include <com/sun/star/beans/PropertyValue.hpp> #include "cmdbasestream.hxx" class SvStream; class SfxPoolItem; class String; class ICommStream; class SCmdStream: public CmdBaseStream { SvStream *pSammel; public: SCmdStream( SvStream *pIn ); ~SCmdStream(); using CmdBaseStream::Read; void Read ( comm_USHORT &nNr ){CmdBaseStream::Read ( nNr );} void Read ( comm_ULONG &nNr ){CmdBaseStream::Read ( nNr );} // void Read ( comm_UniChar* &aString, comm_USHORT &nLenInChars ){CmdBaseStream::Read ( aString, nLenInChars );} void Read ( comm_BOOL &bBool ){CmdBaseStream::Read ( bBool );} // new void Read ( String &aString ); void Read ( SfxPoolItem *&pItem ); void Read ( ::com::sun::star::beans::PropertyValue &rItem ); virtual void Read (String* &pString); }; #endif <|endoftext|>
<commit_before>#include <communication.h> Communication::Communication(ObjectExtractor *p_obj_e, FileAPI *p_api, JacoCustom *p_jaco) { m_object_ex_ptr = p_obj_e; m_api_ptr = p_api; m_jaco_ptr = p_jaco; m_coordinate_received = false; m_grasp_received = false; m_train_received = false; } //-----------------------------------------------------------------------------------// /* The call back when the apps send a coordinate. All the message send begin with a letter (ex c_...). The callBack will execute the right command. */ void Communication::callback_android_listener(const std_msgs::String &p_input) { switch(p_input.data[0]) { case('c'):coordinate_processing(p_input);break; case('t'):train_processing(p_input);break; case('g'):grasp_processing(p_input);break; default:break; } } //---------------------------------------------------------------------------------// /* Parse the the message received from the tablet when its a coordinate. Param[in] std_msgs::String a string message that tha tablet send. */ void Communication::coordinate_processing(std_msgs::String p_coordinate) { m_coordinate_received = true; m_grasp_received = false; m_train_received = false; std::string string_temp = ""; for(int i = 0; i < p_coordinate.data.size(); i ++) { if(p_coordinate.data.at(i) == '_') { m_coordinate_user_sended[0] = atof(string_temp.c_str()); string_temp.clear(); } else string_temp += p_coordinate.data.at(i); } m_coordinate_user_sended[1] = atof(string_temp.c_str()); m_coordinate_user_sended[0] = m_coordinate_user_sended[0]*640; m_coordinate_user_sended[1] = m_coordinate_user_sended[1]*480; } //----------------------------------------------------------------------------------------// /* Parse the the message received from the tablet when the user deceide to take the object. Param[in] std_msgs::String a string message that tha tablet send. */ void Communication::grasp_processing(std_msgs::String p_grasp) { m_coordinate_received = false; m_grasp_received = false; m_train_received = true; } //------------------------------------------------------------------------------------------// /* Parse the the message received from the tablet when the user deceide to train. Param[in] std_msgs::String a string message that tha tablet send. */ void Communication::train_processing(std_msgs::String p_train) { m_coordinate_received = false; m_grasp_received = false; m_train_received = true; } //------------------------------------------------------------------------------------------// bool Communication::get_coordinate_received() const { return m_coordinate_received; } //--------------------------------------------------------------------------------------------// bool Communication::get_grasp_received() const { return m_grasp_received; } //---------------------------------------------------------------------------------------------// bool Communication::get_train_received() const { return m_train_received; } //-----------------------------------------------------------------------------------------------// void Communication::spin_once() { if(m_coordinate_received) { m_position_vector_cvfh = m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended, m_api_ptr->getAllHistograms()); m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended,m_api_ptr->getAllHistograms()); m_object_ex_ptr->spin_once(); //pour retrouver l'object qui est reconnue par le cvfh //m_api_ptr->retrieveObjectFromHistogramme(m_position_vector_cvfh); } else if(m_train_received) { // Training and repeating steps should be in 2 steps : // 1) Check if object is recognized and load all appropriate data in Graphical User Interface // 2) Then Call the function train/repeat (depending on which button is clicked) with arguments (recognized or not, which pose is selected to grasp, etc.) train(); } else if(m_grasp_received) { repeat(); } else { m_object_ex_ptr->spin_once(); } m_coordinate_received = false; m_grasp_received = false; m_train_received = false; } //-----------------------------------------------------------------------------------------------// void Communication::train(){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr input_pointcloud = m_object_ex_ptr->getObjectToGrasp(); Eigen::Matrix4f calculated_object_transform; int object_index = m_object_ex_ptr->m_object_recognition.OURCVFHRecognition(input_pointcloud, m_api_ptr, calculated_object_transform); bool known_object = true; if(object_index < 0){ known_object = false; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_pointcloud; pcl::PointCloud<pcl::VFHSignature308>::Ptr object_signature; std::vector<tf::Transform> object_pose_vector; std::vector<tf::Transform> relative_arm_pose_vector; std::vector<Eigen::Matrix4f,Eigen::aligned_allocator<Eigen::Matrix4f> > surface_transforms; std::string name; ObjectBd obj; if(known_object){ //Load object from Histogram position obj = m_api_ptr->retrieveObjectFromHistogram(object_index); object_pointcloud = m_object_ex_ptr->m_object_recognition.transformAndVoxelizePointCloud(input_pointcloud, obj.getPointCloud(),calculated_object_transform); object_pose_vector = obj.getObjectPose(); relative_arm_pose_vector = obj.getArmPose(); surface_transforms = obj.getTransforms(); name = obj.getName(); } else{ object_pointcloud = input_pointcloud; } // Calculate surface signatures and transforms (coordinate systems) object_signature = m_object_ex_ptr->m_object_recognition.makeCVFH(object_pointcloud,surface_transforms); // ************** OBJECT POSE (Change later for position of the object in the map)************************************************************************** tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame(); object_pose_vector.push_back(object_tf); // JACO POSE tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getGraspArmPosition(); // For testing purposes only, comment the following line and uncomment previous one //tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getArmPositionFromCamera(); // RELATIVE POSE tf::Transform arm_rel_pose; tf::Vector3 translation = arm_pose_before_grasp.getOrigin() - object_tf.getOrigin(); arm_rel_pose = tf::Transform(object_tf.getBasis().transposeTimes(arm_pose_before_grasp.getBasis()), translation); relative_arm_pose_vector.push_back(arm_rel_pose); // TO VIEW FRAMES //static tf::TransformBroadcaster br; //br.sendTransform(object_tf); //br.sendTransform(tf::StampedTransform(diff,ros::Time::now(),"detected_object_centroids","jaco_relative_pose")); // PRINT POSE // cout << "arm pose : [" << arm_pose_before_grasp.getOrigin().getX() << ", " << // arm_pose_before_grasp.getOrigin().getY() << ", " << // arm_pose_before_grasp.getOrigin().getZ() << "]" << endl; // SAVE if(known_object){ obj.setAllAttribut(name,object_signature,object_pointcloud,relative_arm_pose_vector,object_pose_vector,surface_transforms); } else{ m_api_ptr->save(object_signature,object_pointcloud,relative_arm_pose_vector,object_pose_vector,surface_transforms); } m_relative_pose = arm_rel_pose; } void Communication::repeat(){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr input_pointcloud = m_object_ex_ptr->getObjectToGrasp(); Eigen::Matrix4f calculated_object_transform; int object_index = m_object_ex_ptr->m_object_recognition.OURCVFHRecognition(input_pointcloud, m_api_ptr, calculated_object_transform); // Object is recognized if(object_index >= 0){ ObjectBd obj = m_api_ptr->retrieveObjectFromHistogram(object_index); // Choose good index of object_tf // Select good index of arm_relative_pose (grasp position) // Publish TF in a thread and listen to it // Move the arm (MoveIt instead of direct moveToPoint function) } /* tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame(); tf::Vector3 translation2 = object_tf.getOrigin() + m_relative_pose.getOrigin(); tf::Transform tf_ = tf::Transform(object_tf.getRotation()*m_relative_pose.getRotation(), translation2); m_publish_relative_pose = true; boost::thread thread(&Communication::publishRelativePoseTF,this,tf_); tf::StampedTransform goal_pose; tf::TransformListener listener; listener.waitForTransform("jaco_api_origin","jaco_tool_relative_pose",ros::Time(0),ros::Duration(3.0)); listener.lookupTransform("jaco_api_origin","jaco_tool_relative_pose",ros::Time(0),goal_pose); m_publish_relative_pose = false; thread.join(); m_jaco_ptr->moveToPoint(goal_pose);*/ } void Communication::publishRelativePoseTF(tf::Transform relative_pose){ static tf::TransformBroadcaster br; ros::Rate r(10); while(m_publish_relative_pose){ tf::StampedTransform arm_relative = tf::StampedTransform(relative_pose,ros::Time::now(),"camera_rgb_frame","jaco_tool_relative_pose"); br.sendTransform(arm_relative); r.sleep(); } } void Communication::testTFandSurfaceTransforms(){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr input_pointcloud = m_object_ex_ptr->getObjectToGrasp(); std::vector<Eigen::Matrix4f,Eigen::aligned_allocator<Eigen::Matrix4f> > tf_vector; std::vector<Eigen::Vector3f> centroidVec; pcl::PointCloud<pcl::VFHSignature308>::Ptr sig = m_object_ex_ptr->m_object_recognition.makeCVFH(input_pointcloud,tf_vector, centroidVec); static tf::TransformBroadcaster br; tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame(); br.sendTransform(object_tf); /* To get the transfrom work we need to get the centroid directly from the ourcvfh algo. I make a new function that take the centroid in parameters. So this way we can set the orrigin of the tf */ m_object_ex_ptr->m_transform_pc->clear(); for(int i=0; i < tf_vector.size(); i++){ Eigen::Matrix4f matrix = tf_vector.at(i); tf::Transform tf_ = tfFromEigen(matrix); tf::Vector3 vec2(centroidVec[i](2,0), -(centroidVec[i](0,0)), -(centroidVec[i](1,0))); tf_.setOrigin(vec2); // Bad transformation (for testing purposes) tf::Transform tf_2; tf_2.setRotation(tf::Quaternion(0,0,0)); tf::Vector3 vec = tf_.getOrigin(); tf_2.setOrigin(tf::Vector3(vec.getZ(),-vec.getX(),-vec.getY())); // Send transforms std::stringstream ss; ss << i; std::string str = "surfaceTransform_" + ss.str(); br.sendTransform(tf::StampedTransform(tf_,ros::Time::now(),"camera_rgb_frame",str)); std::string str2 = "surfaceTransform_" + ss.str() +"_BAD"; br.sendTransform(tf::StampedTransform(tf_2,ros::Time::now(),"camera_rgb_frame",str2)); // Test aligning tfs std::string str3 = "surfaceTransform_" + ss.str() +"_aligned"; //tf::Vector3 translation = tf_2.getOrigin() - tf_.getOrigin(); //tf::Transform diff = tf::Transform(tf_.getBasis().transposeTimes(tf_2.getBasis()), translation); tf::Transform diff = tf_.inverseTimes(tf_2); //diff.setOrigin(translation); tf::StampedTransform test = tf::StampedTransform(diff,ros::Time::now(),str,str3); br.sendTransform(test); // test.setOrigin(translation); // str3 += "_test"; // tf::StampedTransform test2 = test; // test2.child_frame_id_ = str3; // br.sendTransform(test2); printf("Vector1 ---> %f | %f | %f \n", tf_.getOrigin().getX(), tf_.getOrigin().getY(), tf_.getOrigin().getZ()); printf("Vector2 ---> %f | %f | %f \n", tf_2.getOrigin().getX(), tf_2.getOrigin().getY(), tf_2.getOrigin().getZ()); printf("Vector3 ---> %f | %f | %f \n", test.getOrigin().getX(), test.getOrigin().getY(), test.getOrigin().getZ()); std::cout << std::endl; PointT pt; pt.x = vec2.getX(); pt.y = vec2.getY(); pt.z = vec2.getZ(); m_object_ex_ptr->m_transform_pc->push_back(pt); } } tf::Transform Communication::tfFromEigen(Eigen::Matrix4f trans) { Eigen::Matrix4f mf = trans; //The matrix I want to convert Eigen::Matrix4d md(mf.cast<double>()); Eigen::Affine3d affine(md); tf::Transform transform_; tf::transformEigenToTF(affine,transform_); tf::Quaternion test = transform_.getRotation().normalize(); transform_.setRotation(test); return transform_; } <commit_msg>removed garbage<commit_after>#include <communication.h> Communication::Communication(ObjectExtractor *p_obj_e, FileAPI *p_api, JacoCustom *p_jaco) { m_object_ex_ptr = p_obj_e; m_api_ptr = p_api; m_jaco_ptr = p_jaco; m_coordinate_received = false; m_grasp_received = false; m_train_received = false; } //-----------------------------------------------------------------------------------// /* The call back when the apps send a coordinate. All the message send begin with a letter (ex c_...). The callBack will execute the right command. */ void Communication::callback_android_listener(const std_msgs::String &p_input) { switch(p_input.data[0]) { case('c'):coordinate_processing(p_input);break; case('t'):train_processing(p_input);break; case('g'):grasp_processing(p_input);break; default:break; } } //---------------------------------------------------------------------------------// /* Parse the the message received from the tablet when its a coordinate. Param[in] std_msgs::String a string message that tha tablet send. */ void Communication::coordinate_processing(std_msgs::String p_coordinate) { m_coordinate_received = true; m_grasp_received = false; m_train_received = false; std::string string_temp = ""; for(int i = 0; i < p_coordinate.data.size(); i ++) { if(p_coordinate.data.at(i) == '_') { m_coordinate_user_sended[0] = atof(string_temp.c_str()); string_temp.clear(); } else string_temp += p_coordinate.data.at(i); } m_coordinate_user_sended[1] = atof(string_temp.c_str()); m_coordinate_user_sended[0] = m_coordinate_user_sended[0]*640; m_coordinate_user_sended[1] = m_coordinate_user_sended[1]*480; } //----------------------------------------------------------------------------------------// /* Parse the the message received from the tablet when the user deceide to take the object. Param[in] std_msgs::String a string message that tha tablet send. */ void Communication::grasp_processing(std_msgs::String p_grasp) { m_coordinate_received = false; m_grasp_received = false; m_train_received = true; } //------------------------------------------------------------------------------------------// /* Parse the the message received from the tablet when the user deceide to train. Param[in] std_msgs::String a string message that tha tablet send. */ void Communication::train_processing(std_msgs::String p_train) { m_coordinate_received = false; m_grasp_received = false; m_train_received = true; } //------------------------------------------------------------------------------------------// bool Communication::get_coordinate_received() const { return m_coordinate_received; } //--------------------------------------------------------------------------------------------// bool Communication::get_grasp_received() const { return m_grasp_received; } //---------------------------------------------------------------------------------------------// bool Communication::get_train_received() const { return m_train_received; } //-----------------------------------------------------------------------------------------------// void Communication::spin_once() { if(m_coordinate_received) { m_position_vector_cvfh = m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended, m_api_ptr->getAllHistograms()); m_object_ex_ptr->coordinate_processing(m_coordinate_user_sended,m_api_ptr->getAllHistograms()); m_object_ex_ptr->spin_once(); //pour retrouver l'object qui est reconnue par le cvfh //m_api_ptr->retrieveObjectFromHistogramme(m_position_vector_cvfh); } else if(m_train_received) { // Training and repeating steps should be in 2 steps : // 1) Check if object is recognized and load all appropriate data in Graphical User Interface // 2) Then Call the function train/repeat (depending on which button is clicked) with arguments (recognized or not, which pose is selected to grasp, etc.) train(); } else if(m_grasp_received) { repeat(); } else { m_object_ex_ptr->spin_once(); } m_coordinate_received = false; m_grasp_received = false; m_train_received = false; } //-----------------------------------------------------------------------------------------------// void Communication::train(){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr input_pointcloud = m_object_ex_ptr->getObjectToGrasp(); Eigen::Matrix4f calculated_object_transform; int object_index = m_object_ex_ptr->m_object_recognition.OURCVFHRecognition(input_pointcloud, m_api_ptr, calculated_object_transform); bool known_object = true; if(object_index < 0){ known_object = false; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_pointcloud; pcl::PointCloud<pcl::VFHSignature308>::Ptr object_signature; std::vector<tf::Transform> object_pose_vector; std::vector<tf::Transform> relative_arm_pose_vector; std::vector<Eigen::Matrix4f,Eigen::aligned_allocator<Eigen::Matrix4f> > surface_transforms; std::string name; ObjectBd obj; if(known_object){ //Load object from Histogram position obj = m_api_ptr->retrieveObjectFromHistogram(object_index); object_pointcloud = m_object_ex_ptr->m_object_recognition.transformAndVoxelizePointCloud(input_pointcloud, obj.getPointCloud(),calculated_object_transform); object_pose_vector = obj.getObjectPose(); relative_arm_pose_vector = obj.getArmPose(); surface_transforms = obj.getTransforms(); name = obj.getName(); } else{ object_pointcloud = input_pointcloud; } // Calculate surface signatures and transforms (coordinate systems) object_signature = m_object_ex_ptr->m_object_recognition.makeCVFH(object_pointcloud,surface_transforms); // ************** OBJECT POSE (Change later for position of the object in the map)************************************************************************** tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame(); object_pose_vector.push_back(object_tf); // JACO POSE tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getGraspArmPosition(); // For testing purposes only, comment the following line and uncomment previous one //tf::StampedTransform arm_pose_before_grasp = m_jaco_ptr->getArmPositionFromCamera(); // RELATIVE POSE tf::Transform arm_rel_pose; tf::Vector3 translation = arm_pose_before_grasp.getOrigin() - object_tf.getOrigin(); arm_rel_pose = tf::Transform(object_tf.getBasis().transposeTimes(arm_pose_before_grasp.getBasis()), translation); relative_arm_pose_vector.push_back(arm_rel_pose); // TO VIEW FRAMES //static tf::TransformBroadcaster br; //br.sendTransform(object_tf); //br.sendTransform(tf::StampedTransform(diff,ros::Time::now(),"detected_object_centroids","jaco_relative_pose")); // PRINT POSE // cout << "arm pose : [" << arm_pose_before_grasp.getOrigin().getX() << ", " << // arm_pose_before_grasp.getOrigin().getY() << ", " << // arm_pose_before_grasp.getOrigin().getZ() << "]" << endl; // SAVE if(known_object){ obj.setAllAttribut(name,object_signature,object_pointcloud,relative_arm_pose_vector,object_pose_vector,surface_transforms); } else{ m_api_ptr->save(object_signature,object_pointcloud,relative_arm_pose_vector,object_pose_vector,surface_transforms); } m_relative_pose = arm_rel_pose; } void Communication::repeat(){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr input_pointcloud = m_object_ex_ptr->getObjectToGrasp(); Eigen::Matrix4f calculated_object_transform; int object_index = m_object_ex_ptr->m_object_recognition.OURCVFHRecognition(input_pointcloud, m_api_ptr, calculated_object_transform); // Object is recognized if(object_index >= 0){ ObjectBd obj = m_api_ptr->retrieveObjectFromHistogram(object_index); // Choose good index of object_tf // Select good index of arm_relative_pose (grasp position) // Publish TF in a thread and listen to it // Move the arm (MoveIt instead of direct moveToPoint function) } /* tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame(); tf::Vector3 translation2 = object_tf.getOrigin() + m_relative_pose.getOrigin(); tf::Transform tf_ = tf::Transform(object_tf.getRotation()*m_relative_pose.getRotation(), translation2); m_publish_relative_pose = true; boost::thread thread(&Communication::publishRelativePoseTF,this,tf_); tf::StampedTransform goal_pose; tf::TransformListener listener; listener.waitForTransform("jaco_api_origin","jaco_tool_relative_pose",ros::Time(0),ros::Duration(3.0)); listener.lookupTransform("jaco_api_origin","jaco_tool_relative_pose",ros::Time(0),goal_pose); m_publish_relative_pose = false; thread.join(); m_jaco_ptr->moveToPoint(goal_pose);*/ } void Communication::publishRelativePoseTF(tf::Transform relative_pose){ static tf::TransformBroadcaster br; ros::Rate r(10); while(m_publish_relative_pose){ tf::StampedTransform arm_relative = tf::StampedTransform(relative_pose,ros::Time::now(),"camera_rgb_frame","jaco_tool_relative_pose"); br.sendTransform(arm_relative); r.sleep(); } } void Communication::testTFandSurfaceTransforms(){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr input_pointcloud = m_object_ex_ptr->getObjectToGrasp(); std::vector<Eigen::Matrix4f,Eigen::aligned_allocator<Eigen::Matrix4f> > tf_vector; std::vector<Eigen::Vector3f> centroidVec; pcl::PointCloud<pcl::VFHSignature308>::Ptr sig = m_object_ex_ptr->m_object_recognition.makeCVFH(input_pointcloud,tf_vector, centroidVec); static tf::TransformBroadcaster br; tf::StampedTransform object_tf = m_object_ex_ptr->getCentroidPositionRGBFrame(); br.sendTransform(object_tf); /* To get the transfrom work we need to get the centroid directly from the ourcvfh algo. I make a new function that take the centroid in parameters. So this way we can set the orrigin of the tf */ m_object_ex_ptr->m_transform_pc->clear(); for(int i=0; i < tf_vector.size(); i++){ Eigen::Matrix4f matrix = tf_vector.at(i); tf::Transform tf_ = tfFromEigen(matrix); tf::Vector3 vec2(centroidVec[i](2,0), -(centroidVec[i](0,0)), -(centroidVec[i](1,0))); tf_.setOrigin(vec2); // Send transform std::stringstream ss; ss << i; std::string str = "surfaceTransform_" + ss.str(); br.sendTransform(tf::StampedTransform(tf_,ros::Time::now(),"camera_rgb_frame",str)); PointT pt; pt.x = vec2.getX(); pt.y = vec2.getY(); pt.z = vec2.getZ(); m_object_ex_ptr->m_transform_pc->push_back(pt); } } tf::Transform Communication::tfFromEigen(Eigen::Matrix4f trans) { Eigen::Matrix4f mf = trans; //The matrix I want to convert Eigen::Matrix4d md(mf.cast<double>()); Eigen::Affine3d affine(md); tf::Transform transform_; tf::transformEigenToTF(affine,transform_); tf::Quaternion test = transform_.getRotation().normalize(); transform_.setRotation(test); return transform_; } <|endoftext|>
<commit_before> // // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "VideoWriterThread.h" #include "../base/ProfilingZoneID.h" #include "../base/ScopeTimer.h" #include "../base/StringHelper.h" using namespace std; namespace avg { const unsigned int VIDEO_BUFFER_SIZE = 400000; const ::PixelFormat STREAM_PIXEL_FORMAT = ::PIX_FMT_YUVJ420P; VideoWriterThread::VideoWriterThread(CQueue& CmdQueue, const string& sFilename, IntPoint size, int frameRate, int qMin, int qMax) : WorkerThread<VideoWriterThread>(sFilename, CmdQueue, Logger::PROFILE), m_sFilename(sFilename), m_Size(size), m_FrameRate(frameRate), m_QMin(qMin), m_QMax(qMax), m_pOutputFormatContext() { } VideoWriterThread::~VideoWriterThread() { } static ProfilingZoneID ProfilingZoneEncodeFrame("Encode frame", true); void VideoWriterThread::encodeYUVFrame(BitmapPtr pBmp) { ScopeTimer timer(ProfilingZoneEncodeFrame); convertYUVImage(pBmp); writeFrame(m_pConvertedFrame); ThreadProfiler::get()->reset(); } void VideoWriterThread::encodeFrame(BitmapPtr pBmp) { ScopeTimer timer(ProfilingZoneEncodeFrame); convertRGBImage(pBmp); writeFrame(m_pConvertedFrame); ThreadProfiler::get()->reset(); } void VideoWriterThread::close() { if (m_pOutputFormatContext) { av_write_trailer(m_pOutputFormatContext); avcodec_close(m_pVideoStream->codec); for (unsigned int i=0; i<m_pOutputFormatContext->nb_streams; i++) { AVStream* pStream = m_pOutputFormatContext->streams[i]; pStream->discard = AVDISCARD_ALL; av_freep(&m_pOutputFormatContext->streams[i]->codec); av_freep(&m_pOutputFormatContext->streams[i]); } if (!(m_pOutputFormat->flags & AVFMT_NOFILE)) { url_fclose(m_pOutputFormatContext->pb); } av_free(m_pOutputFormatContext); av_free(m_pVideoBuffer); av_free(m_pConvertedFrame); av_free(m_pPictureBuffer); sws_freeContext(m_pFrameConversionContext); m_pOutputFormatContext = 0; } } bool VideoWriterThread::init() { open(); return true; } bool VideoWriterThread::work() { waitForCommand(); return true; } void VideoWriterThread::deinit() { close(); } void VideoWriterThread::open() { av_register_all(); // TODO: make sure this is only done once. // av_log_set_level(AV_LOG_DEBUG); #if LIBAVFORMAT_VERSION_MAJOR > 52 m_pOutputFormat = av_guess_format("mov", NULL, NULL); #else m_pOutputFormat = guess_format("mov", NULL, NULL); #endif m_pOutputFormat->video_codec = CODEC_ID_MJPEG; #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(52, 24, 0) m_pOutputFormatContext = avformat_alloc_context(); #else m_pOutputFormatContext = av_alloc_format_context(); #endif m_pOutputFormatContext->oformat = m_pOutputFormat; strncpy(m_pOutputFormatContext->filename, m_sFilename.c_str(), sizeof(m_pOutputFormatContext->filename)); if (m_pOutputFormat->video_codec != CODEC_ID_NONE) { setupVideoStream(); } #if LIBAVFORMAT_VERSION_MAJOR < 52 av_set_parameters(m_pOutputFormatContext, NULL); #endif #if LIBAVFORMAT_VERSION_MAJOR < 54 float muxPreload = 0.5; m_pOutputFormatContext->preload = int(muxPreload * AV_TIME_BASE); #endif float muxMaxDelay = 0.7; m_pOutputFormatContext->max_delay = int(muxMaxDelay * AV_TIME_BASE); // av_dump_format(m_pOutputFormatContext, 0, m_sFilename.c_str(), 1); openVideoCodec(); m_pVideoBuffer = NULL; if (!(m_pOutputFormatContext->oformat->flags & AVFMT_RAWPICTURE)) { m_pVideoBuffer = (unsigned char*)(av_malloc(VIDEO_BUFFER_SIZE)); } if (!(m_pOutputFormat->flags & AVFMT_NOFILE)) { int retVal = url_fopen(&m_pOutputFormatContext->pb, m_sFilename.c_str(), URL_WRONLY); if (retVal < 0) { throw Exception(AVG_ERR_VIDEO_INIT_FAILED, string("Could not open output file: '") + m_sFilename + "'"); } } m_pFrameConversionContext = sws_getContext(m_Size.x, m_Size.y, ::PIX_FMT_RGB32, m_Size.x, m_Size.y, STREAM_PIXEL_FORMAT, SWS_BILINEAR, NULL, NULL, NULL); m_pConvertedFrame = createFrame(STREAM_PIXEL_FORMAT, m_Size); #if LIBAVFORMAT_VERSION_MAJOR > 52 avformat_write_header(m_pOutputFormatContext, 0); #else av_write_header(m_pOutputFormatContext); #endif } void VideoWriterThread::setupVideoStream() { m_pVideoStream = av_new_stream(m_pOutputFormatContext, 0); AVCodecContext* pCodecContext = m_pVideoStream->codec; pCodecContext->codec_id = static_cast<CodecID>(m_pOutputFormat->video_codec); pCodecContext->codec_type = AVMEDIA_TYPE_VIDEO; /* put sample parameters */ pCodecContext->bit_rate = 400000; /* resolution must be a multiple of two */ pCodecContext->width = m_Size.x; pCodecContext->height = m_Size.y; /* time base: this is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented. for fixed-fps content, timebase should be 1/framerate and timestamp increments should be identically 1. */ pCodecContext->time_base.den = m_FrameRate; pCodecContext->time_base.num = 1; // pCodecContext->gop_size = 12; /* emit one intra frame every twelve frames at most */ pCodecContext->pix_fmt = STREAM_PIXEL_FORMAT; // Quality of quantization pCodecContext->qmin = m_QMin; pCodecContext->qmax = m_QMax; // some formats want stream headers to be separate if (m_pOutputFormatContext->oformat->flags & AVFMT_GLOBALHEADER) { pCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER; } m_FramesWritten = 0; } void VideoWriterThread::openVideoCodec() { AVCodec* videoCodec = avcodec_find_encoder(m_pVideoStream->codec->codec_id); AVG_ASSERT(videoCodec); int rc = avcodec_open(m_pVideoStream->codec, videoCodec); AVG_ASSERT(rc == 0); } AVFrame* VideoWriterThread::createFrame(::PixelFormat pixelFormat, IntPoint size) { AVFrame* pPicture; pPicture = avcodec_alloc_frame(); int memNeeded = avpicture_get_size(pixelFormat, size.x, size.y); m_pPictureBuffer = static_cast<unsigned char*>(av_malloc(memNeeded)); avpicture_fill(reinterpret_cast<AVPicture*>(pPicture), m_pPictureBuffer, pixelFormat, size.x, size.y); return pPicture; } static ProfilingZoneID ProfilingZoneConvertImage(" Convert image", true); void VideoWriterThread::convertRGBImage(BitmapPtr pSrcBmp) { ScopeTimer timer(ProfilingZoneConvertImage); unsigned char* rgbData[3] = {pSrcBmp->getPixels(), NULL, NULL}; int rgbStride[3] = {pSrcBmp->getLineLen(), 0, 0}; sws_scale(m_pFrameConversionContext, rgbData, rgbStride, 0, m_Size.y, m_pConvertedFrame->data, m_pConvertedFrame->linesize); } void VideoWriterThread::convertYUVImage(BitmapPtr pSrcBmp) { ScopeTimer timer(ProfilingZoneConvertImage); IntPoint size = pSrcBmp->getSize(); BitmapPtr pYBmp(new Bitmap(size, I8, m_pConvertedFrame->data[0], m_pConvertedFrame->linesize[0], false)); BitmapPtr pUBmp(new Bitmap(size/2, I8, m_pConvertedFrame->data[1], m_pConvertedFrame->linesize[1], false)); BitmapPtr pVBmp(new Bitmap(size/2, I8, m_pConvertedFrame->data[2], m_pConvertedFrame->linesize[2], false)); for (int y=0; y<size.y/2; ++y) { int srcStride = pSrcBmp->getStride(); const unsigned char * pSrc = pSrcBmp->getPixels() + y*srcStride*2; int yStride = pYBmp->getStride(); unsigned char * pYDest = pYBmp->getPixels() + y*yStride*2; unsigned char * pUDest = pUBmp->getPixels() + y*pUBmp->getStride(); unsigned char * pVDest = pVBmp->getPixels() + y*pVBmp->getStride(); for (int x=0; x<size.x/2; ++x) { *pYDest = *pSrc; *(pYDest+1) = *(pSrc+4); *(pYDest+yStride) = *(pSrc+srcStride); *(pYDest+yStride+1) = *(pSrc+srcStride+4); *pUDest = ((int)*(pSrc+1) + *(pSrc+5) + *(pSrc+srcStride+1) + *(pSrc+srcStride+5) + 2)/4; *pVDest = ((int)*(pSrc+2) + *(pSrc+6) + *(pSrc+srcStride+2) + *(pSrc+srcStride+6) + 2)/4; pSrc += 8; pYDest += 2; pUDest += 1; pVDest += 1; } } // pSrcBmp->save("src"+toString(m_FramesWritten)+".png"); // pUBmp->save("foo"+toString(m_FramesWritten)+".png"); } static ProfilingZoneID ProfilingZoneWriteFrame(" Write frame", true); void VideoWriterThread::writeFrame(AVFrame* pFrame) { ScopeTimer timer(ProfilingZoneWriteFrame); m_FramesWritten++; AVCodecContext* pCodecContext = m_pVideoStream->codec; int out_size = avcodec_encode_video(pCodecContext, m_pVideoBuffer, VIDEO_BUFFER_SIZE, pFrame); /* if zero size, it means the image was buffered */ if (out_size > 0) { AVPacket packet; av_init_packet(&packet); if ((unsigned long long)(pCodecContext->coded_frame->pts) != AV_NOPTS_VALUE) { packet.pts = av_rescale_q(pCodecContext->coded_frame->pts, pCodecContext->time_base, m_pVideoStream->time_base); } if (pCodecContext->coded_frame->key_frame) { #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 31, 0) packet.flags |= AV_PKT_FLAG_KEY; #else packet.flags |= PKT_FLAG_KEY; #endif } packet.stream_index = m_pVideoStream->index; packet.data = m_pVideoBuffer; packet.size = out_size; /* write the compressed frame in the media file */ int ret = av_interleaved_write_frame(m_pOutputFormatContext, &packet); AVG_ASSERT(ret == 0); } } } <commit_msg>VideoWriter copes with debugWindowSize (Fixes #350).<commit_after> // // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "VideoWriterThread.h" #include "../base/ProfilingZoneID.h" #include "../base/ScopeTimer.h" #include "../base/StringHelper.h" using namespace std; namespace avg { const unsigned int VIDEO_BUFFER_SIZE = 400000; const ::PixelFormat STREAM_PIXEL_FORMAT = ::PIX_FMT_YUVJ420P; VideoWriterThread::VideoWriterThread(CQueue& CmdQueue, const string& sFilename, IntPoint size, int frameRate, int qMin, int qMax) : WorkerThread<VideoWriterThread>(sFilename, CmdQueue, Logger::PROFILE), m_sFilename(sFilename), m_Size(size), m_FrameRate(frameRate), m_QMin(qMin), m_QMax(qMax), m_pOutputFormatContext() { } VideoWriterThread::~VideoWriterThread() { } static ProfilingZoneID ProfilingZoneEncodeFrame("Encode frame", true); void VideoWriterThread::encodeYUVFrame(BitmapPtr pBmp) { ScopeTimer timer(ProfilingZoneEncodeFrame); convertYUVImage(pBmp); writeFrame(m_pConvertedFrame); ThreadProfiler::get()->reset(); } void VideoWriterThread::encodeFrame(BitmapPtr pBmp) { ScopeTimer timer(ProfilingZoneEncodeFrame); convertRGBImage(pBmp); writeFrame(m_pConvertedFrame); ThreadProfiler::get()->reset(); } void VideoWriterThread::close() { if (m_pOutputFormatContext) { av_write_trailer(m_pOutputFormatContext); avcodec_close(m_pVideoStream->codec); for (unsigned int i=0; i<m_pOutputFormatContext->nb_streams; i++) { AVStream* pStream = m_pOutputFormatContext->streams[i]; pStream->discard = AVDISCARD_ALL; av_freep(&m_pOutputFormatContext->streams[i]->codec); av_freep(&m_pOutputFormatContext->streams[i]); } if (!(m_pOutputFormat->flags & AVFMT_NOFILE)) { url_fclose(m_pOutputFormatContext->pb); } av_free(m_pOutputFormatContext); av_free(m_pVideoBuffer); av_free(m_pConvertedFrame); av_free(m_pPictureBuffer); sws_freeContext(m_pFrameConversionContext); m_pOutputFormatContext = 0; } } bool VideoWriterThread::init() { open(); return true; } bool VideoWriterThread::work() { waitForCommand(); return true; } void VideoWriterThread::deinit() { close(); } void VideoWriterThread::open() { av_register_all(); // TODO: make sure this is only done once. // av_log_set_level(AV_LOG_DEBUG); #if LIBAVFORMAT_VERSION_MAJOR > 52 m_pOutputFormat = av_guess_format(0, m_sFilename.c_str(), 0); #else m_pOutputFormat = guess_format(0, m_sFilename.c_str(), 0); #endif m_pOutputFormat->video_codec = CODEC_ID_MJPEG; #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(52, 24, 0) m_pOutputFormatContext = avformat_alloc_context(); #else m_pOutputFormatContext = av_alloc_format_context(); #endif m_pOutputFormatContext->oformat = m_pOutputFormat; strncpy(m_pOutputFormatContext->filename, m_sFilename.c_str(), sizeof(m_pOutputFormatContext->filename)); if (m_pOutputFormat->video_codec != CODEC_ID_NONE) { setupVideoStream(); } #if LIBAVFORMAT_VERSION_MAJOR < 52 av_set_parameters(m_pOutputFormatContext, NULL); #endif #if LIBAVFORMAT_VERSION_MAJOR < 54 float muxPreload = 0.5; m_pOutputFormatContext->preload = int(muxPreload * AV_TIME_BASE); #endif float muxMaxDelay = 0.7; m_pOutputFormatContext->max_delay = int(muxMaxDelay * AV_TIME_BASE); // av_dump_format(m_pOutputFormatContext, 0, m_sFilename.c_str(), 1); openVideoCodec(); m_pVideoBuffer = NULL; if (!(m_pOutputFormatContext->oformat->flags & AVFMT_RAWPICTURE)) { m_pVideoBuffer = (unsigned char*)(av_malloc(VIDEO_BUFFER_SIZE)); } if (!(m_pOutputFormat->flags & AVFMT_NOFILE)) { int retVal = url_fopen(&m_pOutputFormatContext->pb, m_sFilename.c_str(), URL_WRONLY); if (retVal < 0) { throw Exception(AVG_ERR_VIDEO_INIT_FAILED, string("Could not open output file: '") + m_sFilename + "'"); } } m_pFrameConversionContext = sws_getContext(m_Size.x, m_Size.y, ::PIX_FMT_RGB32, m_Size.x, m_Size.y, STREAM_PIXEL_FORMAT, SWS_BILINEAR, NULL, NULL, NULL); m_pConvertedFrame = createFrame(STREAM_PIXEL_FORMAT, m_Size); #if LIBAVFORMAT_VERSION_MAJOR > 52 avformat_write_header(m_pOutputFormatContext, 0); #else av_write_header(m_pOutputFormatContext); #endif } void VideoWriterThread::setupVideoStream() { m_pVideoStream = av_new_stream(m_pOutputFormatContext, 0); AVCodecContext* pCodecContext = m_pVideoStream->codec; pCodecContext->codec_id = static_cast<CodecID>(m_pOutputFormat->video_codec); pCodecContext->codec_type = AVMEDIA_TYPE_VIDEO; /* put sample parameters */ pCodecContext->bit_rate = 400000; /* resolution must be a multiple of two */ pCodecContext->width = m_Size.x; pCodecContext->height = m_Size.y; /* time base: this is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented. for fixed-fps content, timebase should be 1/framerate and timestamp increments should be identically 1. */ pCodecContext->time_base.den = m_FrameRate; pCodecContext->time_base.num = 1; // pCodecContext->gop_size = 12; /* emit one intra frame every twelve frames at most */ pCodecContext->pix_fmt = STREAM_PIXEL_FORMAT; // Quality of quantization pCodecContext->qmin = m_QMin; pCodecContext->qmax = m_QMax; // some formats want stream headers to be separate if (m_pOutputFormatContext->oformat->flags & AVFMT_GLOBALHEADER) { pCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER; } m_FramesWritten = 0; } void VideoWriterThread::openVideoCodec() { AVCodec* videoCodec = avcodec_find_encoder(m_pVideoStream->codec->codec_id); AVG_ASSERT(videoCodec); int rc = avcodec_open(m_pVideoStream->codec, videoCodec); AVG_ASSERT(rc == 0); } AVFrame* VideoWriterThread::createFrame(::PixelFormat pixelFormat, IntPoint size) { AVFrame* pPicture; pPicture = avcodec_alloc_frame(); int memNeeded = avpicture_get_size(pixelFormat, size.x, size.y); m_pPictureBuffer = static_cast<unsigned char*>(av_malloc(memNeeded)); avpicture_fill(reinterpret_cast<AVPicture*>(pPicture), m_pPictureBuffer, pixelFormat, size.x, size.y); return pPicture; } static ProfilingZoneID ProfilingZoneConvertImage(" Convert image", true); void VideoWriterThread::convertRGBImage(BitmapPtr pSrcBmp) { ScopeTimer timer(ProfilingZoneConvertImage); unsigned char* rgbData[3] = {pSrcBmp->getPixels(), NULL, NULL}; int rgbStride[3] = {pSrcBmp->getLineLen(), 0, 0}; sws_scale(m_pFrameConversionContext, rgbData, rgbStride, 0, m_Size.y, m_pConvertedFrame->data, m_pConvertedFrame->linesize); } void VideoWriterThread::convertYUVImage(BitmapPtr pSrcBmp) { ScopeTimer timer(ProfilingZoneConvertImage); IntPoint size = pSrcBmp->getSize(); BitmapPtr pYBmp(new Bitmap(size, I8, m_pConvertedFrame->data[0], m_pConvertedFrame->linesize[0], false)); BitmapPtr pUBmp(new Bitmap(size/2, I8, m_pConvertedFrame->data[1], m_pConvertedFrame->linesize[1], false)); BitmapPtr pVBmp(new Bitmap(size/2, I8, m_pConvertedFrame->data[2], m_pConvertedFrame->linesize[2], false)); for (int y=0; y<size.y/2; ++y) { int srcStride = pSrcBmp->getStride(); const unsigned char * pSrc = pSrcBmp->getPixels() + y*srcStride*2; int yStride = pYBmp->getStride(); unsigned char * pYDest = pYBmp->getPixels() + y*yStride*2; unsigned char * pUDest = pUBmp->getPixels() + y*pUBmp->getStride(); unsigned char * pVDest = pVBmp->getPixels() + y*pVBmp->getStride(); for (int x=0; x<size.x/2; ++x) { *pYDest = *pSrc; *(pYDest+1) = *(pSrc+4); *(pYDest+yStride) = *(pSrc+srcStride); *(pYDest+yStride+1) = *(pSrc+srcStride+4); *pUDest = ((int)*(pSrc+1) + *(pSrc+5) + *(pSrc+srcStride+1) + *(pSrc+srcStride+5) + 2)/4; *pVDest = ((int)*(pSrc+2) + *(pSrc+6) + *(pSrc+srcStride+2) + *(pSrc+srcStride+6) + 2)/4; pSrc += 8; pYDest += 2; pUDest += 1; pVDest += 1; } } // pSrcBmp->save("src"+toString(m_FramesWritten)+".png"); // pUBmp->save("foo"+toString(m_FramesWritten)+".png"); } static ProfilingZoneID ProfilingZoneWriteFrame(" Write frame", true); void VideoWriterThread::writeFrame(AVFrame* pFrame) { ScopeTimer timer(ProfilingZoneWriteFrame); m_FramesWritten++; AVCodecContext* pCodecContext = m_pVideoStream->codec; int out_size = avcodec_encode_video(pCodecContext, m_pVideoBuffer, VIDEO_BUFFER_SIZE, pFrame); /* if zero size, it means the image was buffered */ if (out_size > 0) { AVPacket packet; av_init_packet(&packet); if ((unsigned long long)(pCodecContext->coded_frame->pts) != AV_NOPTS_VALUE) { packet.pts = av_rescale_q(pCodecContext->coded_frame->pts, pCodecContext->time_base, m_pVideoStream->time_base); } if (pCodecContext->coded_frame->key_frame) { #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 31, 0) packet.flags |= AV_PKT_FLAG_KEY; #else packet.flags |= PKT_FLAG_KEY; #endif } packet.stream_index = m_pVideoStream->index; packet.data = m_pVideoBuffer; packet.size = out_size; /* write the compressed frame in the media file */ int ret = av_interleaved_write_frame(m_pOutputFormatContext, &packet); AVG_ASSERT(ret == 0); } } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** 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 "icore.h" /*! \namespace Core \brief The Core namespace contains all classes that make up the Core plugin which constitute the basic functionality of Qt Creator. */ /*! \namespace Core::Internal \internal */ /*! \class Core::ICore \brief The ICore class allows access to the different part that make up the basic functionality of Qt Creator. You should never create a subclass of this interface. The one and only instance is created by the Core plugin. You can access this instance from your plugin through \c{Core::instance()}. \mainclass */ /*! \fn QStringList ICore::showNewItemDialog(const QString &title, const QList<IWizard *> &wizards, const QString &defaultLocation = QString()) \brief Opens a dialog where the user can choose from a set of \a wizards that create new files/classes/projects. The \a title argument is shown as the dialogs title. The path where the files will be created (if the user doesn't change it) is set in \a defaultLocation. It defaults to the path of the file manager's current file. \sa Core::FileManager */ /*! \fn void setNewItemDialogPreferredWizardKinds(IWizard::WizardKinds kinds) \internal When set to true, the general "New File or Project" dialog will collapse the project categories. This is set by the project explorer: When projects are open, the preferred thing is to create files/classes, if no projects are open, the preferred thing to create are projects. */ /*! \fn bool ICore::showOptionsDialog(const QString &group = QString(), const QString &page = QString()) \brief Opens the application options/preferences dialog with preselected \a page in a specified \a group. The arguments refer to the string IDs of the corresponding IOptionsPage. */ /*! \fn bool ICore::showWarningWithOptions(const QString &title, const QString &text, const QString &details = QString(), const QString &settingsCategory = QString(), const QString &settingsId = QString(), QWidget *parent = 0); \brief Show a warning message with a button that opens a settings page. Should be used to display configuration errors and point users to the setting. Returns true if the settings dialog was accepted. */ /*! \fn ActionManager *ICore::actionManager() const \brief Returns the application's action manager. The action manager is responsible for registration of menus and menu items and keyboard shortcuts. */ /*! \fn FileManager *ICore::fileManager() const \brief Returns the application's file manager. The file manager keeps track of files for changes outside the application. */ /*! \fn UniqueIDManager *ICore::uniqueIDManager() const \brief Returns the application's id manager. The unique ID manager transforms strings in unique integers and the other way round. */ /*! \fn MessageManager *ICore::messageManager() const \brief Returns the application's message manager. The message manager is the interface to the "General" output pane for general application debug messages. */ /*! \fn ExtensionSystem::PluginManager *ICore::pluginManager() const \brief Returns the application's plugin manager. The plugin manager handles the plugin life cycles and manages the common object pool. */ /*! \fn EditorManager *ICore::editorManager() const \brief Returns the application's editor manager. The editor manager handles all editor related tasks like opening documents, the stack of currently open documents and the currently active document. */ /*! \fn ProgressManager *ICore::progressManager() const \brief Returns the application's progress manager. Use the progress manager to register a concurrent task to show a progress bar the way Qt Creator does it. */ /*! \fn ScriptManager *ICore::scriptManager() const \internal */ /*! \fn VariableManager *ICore::variableManager() const \brief Returns the application's variable manager. The variable manager is used to register application wide string variables like \c MY_PROJECT_DIR such that strings like \c{somecommand ${MY_PROJECT_DIR}/sub} can be resolved/expanded from anywhere in the application. */ /*! \fn VCSManager *ICore::vcsManager() const \brief Returns the application's vcs manager. The vcs manager can be used to e.g. retrieve information about the version control system used for a directory on hard disk. The actual functionality for a specific version control system must be implemented in a IVersionControl object and registered in the plugin manager's object pool. */ /*! \fn ModeManager *ICore::modeManager() const \brief Returns the application's mode manager. The mode manager handles everything related to the instances of IMode that were added to the plugin manager's object pool as well as their buttons and the tool bar with the round buttons in the lower left corner of Qt Creator. */ /*! \fn MimeDatabase *ICore::mimeDatabase() const \brief Returns the application's mime database. Use the mime database to manage mime types. */ /*! \fn QSettings *ICore::settings(QSettings::UserScope scope) const \brief Returns the application's main settings object. You can use it to retrieve or set application wide settings (in contrast to session or project specific settings). If \a scope is QSettings::UserScope (the default), the users settings will be read from the users settings, with a fallback to global settings provided with Qt Creator. If \a scope is QSettings::SystemScope, only the system settings shipped with the current version of Qt Creator will be read. This functionality exists for internal purposes only. \see settingsDatabase() */ /*! \fn SettingsDatabase *ICore::settingsDatabase() const \brief Returns the application's settings database. The settings database is meant as an alternative to the regular settings object. It is more suitable for storing large amounts of data. The settings are application wide. \see SettingsDatabase */ /*! \fn QPrinter *ICore::printer() const \brief Returns the application's printer object. Always use this printer object for printing, so the different parts of the application re-use its settings. */ /*! \fn QString ICore::resourcePath() const \brief Returns the absolute path that is used for resources like project templates and the debugger macros. This abstraction is needed to avoid platform-specific code all over the place, since e.g. on Mac the resources are part of the application bundle. */ /*! \fn QMainWindow *ICore::mainWindow() const \brief Returns the main application window. For use as dialog parent etc. */ /*! \fn IContext *ICore::currentContextObject() const \brief Returns the context object of the current main context. \sa ICore::addAdditionalContext() \sa ICore::addContextObject() */ /*! \fn void ICore::addAdditionalContext(int context) \brief Register additional context to be currently active. Appends the additional \a context to the list of currently active contexts. You need to call ICore::updateContext to make that change take effect. \sa ICore::removeAdditionalContext() \sa ICore::hasContext() \sa ICore::updateContext() */ /*! \fn void ICore::removeAdditionalContext(int context) \brief Removes the given \a context from the list of currently active contexts. You need to call ICore::updateContext to make that change take effect. \sa ICore::addAdditionalContext() \sa ICore::hasContext() \sa ICore::updateContext() */ /*! \fn bool ICore::hasContext(int context) const \brief Returns if the given \a context is currently one of the active contexts. \sa ICore::addAdditionalContext() \sa ICore::addContextObject() */ /*! \fn void ICore::addContextObject(IContext *context) \brief Registers an additional \a context object. After registration this context object gets automatically the current context object whenever its widget gets focus. \sa ICore::removeContextObject() \sa ICore::addAdditionalContext() \sa ICore::currentContextObject() */ /*! \fn void ICore::removeContextObject(IContext *context) \brief Unregisters a \a context object from the list of know contexts. \sa ICore::addContextObject() \sa ICore::addAdditionalContext() \sa ICore::currentContextObject() } */ /*! \fn void ICore::updateContext() \brief Update the list of active contexts after adding or removing additional ones. \sa ICore::addAdditionalContext() \sa ICore::removeAdditionalContext() */ /*! \fn void ICore::openFiles(const QStringList &fileNames) \brief Open all files from a list of \a fileNames like it would be done if they were given to Qt Creator on the command line, or they were opened via \gui{File|Open}. */ /*! \fn ICore::ICore() \internal */ /*! \fn ICore::~ICore() \internal */ /*! \fn void ICore::coreOpened() \brief Emitted after all plugins have been loaded and the main window shown. */ /*! \fn void ICore::saveSettingsRequested() \brief Emitted to signal that the user has requested that the global settings should be saved to disk. At the moment that happens when the application is closed, and on \gui{Save All}. */ /*! \fn void ICore::optionsDialogRequested() \brief Signal that allows plugins to perform actions just before the \gui{Tools|Options} dialog is shown. */ /*! \fn void ICore::coreAboutToClose() \brief Plugins can do some pre-end-of-life actions when they get this signal. The application is guaranteed to shut down after this signal is emitted. It's there as an addition to the usual plugin lifecycle methods, namely IPlugin::shutdown(), just for convenience. */ /*! \fn void ICore::contextAboutToChange(Core::IContext *context) \brief Sent just before a new \a context becomes the current context (meaning that its widget got focus). */ /*! \fn void ICore::contextChanged(Core::IContext *context, const QList<int> &additionalContexts) \brief Sent just after a new \a context became the current context (meaning that its widget got focus), or if the additional context ids changed. */ <commit_msg>Updated ICore documentation to recent additional contexts API change<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** 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 "icore.h" /*! \namespace Core \brief The Core namespace contains all classes that make up the Core plugin which constitute the basic functionality of Qt Creator. */ /*! \namespace Core::Internal \internal */ /*! \class Core::ICore \brief The ICore class allows access to the different part that make up the basic functionality of Qt Creator. You should never create a subclass of this interface. The one and only instance is created by the Core plugin. You can access this instance from your plugin through \c{Core::instance()}. \mainclass */ /*! \fn QStringList ICore::showNewItemDialog(const QString &title, const QList<IWizard *> &wizards, const QString &defaultLocation = QString()) \brief Opens a dialog where the user can choose from a set of \a wizards that create new files/classes/projects. The \a title argument is shown as the dialogs title. The path where the files will be created (if the user doesn't change it) is set in \a defaultLocation. It defaults to the path of the file manager's current file. \sa Core::FileManager */ /*! \fn void setNewItemDialogPreferredWizardKinds(IWizard::WizardKinds kinds) \internal When set to true, the general "New File or Project" dialog will collapse the project categories. This is set by the project explorer: When projects are open, the preferred thing is to create files/classes, if no projects are open, the preferred thing to create are projects. */ /*! \fn bool ICore::showOptionsDialog(const QString &group = QString(), const QString &page = QString()) \brief Opens the application options/preferences dialog with preselected \a page in a specified \a group. The arguments refer to the string IDs of the corresponding IOptionsPage. */ /*! \fn bool ICore::showWarningWithOptions(const QString &title, const QString &text, const QString &details = QString(), const QString &settingsCategory = QString(), const QString &settingsId = QString(), QWidget *parent = 0); \brief Show a warning message with a button that opens a settings page. Should be used to display configuration errors and point users to the setting. Returns true if the settings dialog was accepted. */ /*! \fn ActionManager *ICore::actionManager() const \brief Returns the application's action manager. The action manager is responsible for registration of menus and menu items and keyboard shortcuts. */ /*! \fn FileManager *ICore::fileManager() const \brief Returns the application's file manager. The file manager keeps track of files for changes outside the application. */ /*! \fn UniqueIDManager *ICore::uniqueIDManager() const \brief Returns the application's id manager. The unique ID manager transforms strings in unique integers and the other way round. */ /*! \fn MessageManager *ICore::messageManager() const \brief Returns the application's message manager. The message manager is the interface to the "General" output pane for general application debug messages. */ /*! \fn ExtensionSystem::PluginManager *ICore::pluginManager() const \brief Returns the application's plugin manager. The plugin manager handles the plugin life cycles and manages the common object pool. */ /*! \fn EditorManager *ICore::editorManager() const \brief Returns the application's editor manager. The editor manager handles all editor related tasks like opening documents, the stack of currently open documents and the currently active document. */ /*! \fn ProgressManager *ICore::progressManager() const \brief Returns the application's progress manager. Use the progress manager to register a concurrent task to show a progress bar the way Qt Creator does it. */ /*! \fn ScriptManager *ICore::scriptManager() const \internal */ /*! \fn VariableManager *ICore::variableManager() const \brief Returns the application's variable manager. The variable manager is used to register application wide string variables like \c MY_PROJECT_DIR such that strings like \c{somecommand ${MY_PROJECT_DIR}/sub} can be resolved/expanded from anywhere in the application. */ /*! \fn VCSManager *ICore::vcsManager() const \brief Returns the application's vcs manager. The vcs manager can be used to e.g. retrieve information about the version control system used for a directory on hard disk. The actual functionality for a specific version control system must be implemented in a IVersionControl object and registered in the plugin manager's object pool. */ /*! \fn ModeManager *ICore::modeManager() const \brief Returns the application's mode manager. The mode manager handles everything related to the instances of IMode that were added to the plugin manager's object pool as well as their buttons and the tool bar with the round buttons in the lower left corner of Qt Creator. */ /*! \fn MimeDatabase *ICore::mimeDatabase() const \brief Returns the application's mime database. Use the mime database to manage mime types. */ /*! \fn QSettings *ICore::settings(QSettings::UserScope scope) const \brief Returns the application's main settings object. You can use it to retrieve or set application wide settings (in contrast to session or project specific settings). If \a scope is QSettings::UserScope (the default), the users settings will be read from the users settings, with a fallback to global settings provided with Qt Creator. If \a scope is QSettings::SystemScope, only the system settings shipped with the current version of Qt Creator will be read. This functionality exists for internal purposes only. \see settingsDatabase() */ /*! \fn SettingsDatabase *ICore::settingsDatabase() const \brief Returns the application's settings database. The settings database is meant as an alternative to the regular settings object. It is more suitable for storing large amounts of data. The settings are application wide. \see SettingsDatabase */ /*! \fn QPrinter *ICore::printer() const \brief Returns the application's printer object. Always use this printer object for printing, so the different parts of the application re-use its settings. */ /*! \fn QString ICore::resourcePath() const \brief Returns the absolute path that is used for resources like project templates and the debugger macros. This abstraction is needed to avoid platform-specific code all over the place, since e.g. on Mac the resources are part of the application bundle. */ /*! \fn QMainWindow *ICore::mainWindow() const \brief Returns the main application window. For use as dialog parent etc. */ /*! \fn IContext *ICore::currentContextObject() const \brief Returns the context object of the current main context. \sa ICore::updateAdditionalContexts() \sa ICore::addContextObject() */ /*! \fn void ICore::updateAdditionalContexts(const QList<int> &remove, const QList<int> &add) \brief Change the currently active additional contexts. Removes the list of additional contexts specified by \a remove and adds the list of additional contexts specified by \a add. \sa ICore::hasContext() */ /*! \fn bool ICore::hasContext(int context) const \brief Returns if the given \a context is currently one of the active contexts. \sa ICore::updateAdditionalContexts() \sa ICore::addContextObject() */ /*! \fn void ICore::addContextObject(IContext *context) \brief Registers an additional \a context object. After registration this context object gets automatically the current context object whenever its widget gets focus. \sa ICore::removeContextObject() \sa ICore::updateAdditionalContexts() \sa ICore::currentContextObject() */ /*! \fn void ICore::removeContextObject(IContext *context) \brief Unregisters a \a context object from the list of know contexts. \sa ICore::addContextObject() \sa ICore::updateAdditionalContexts() \sa ICore::currentContextObject() } */ /*! \fn void ICore::openFiles(const QStringList &fileNames) \brief Open all files from a list of \a fileNames like it would be done if they were given to Qt Creator on the command line, or they were opened via \gui{File|Open}. */ /*! \fn ICore::ICore() \internal */ /*! \fn ICore::~ICore() \internal */ /*! \fn void ICore::coreOpened() \brief Emitted after all plugins have been loaded and the main window shown. */ /*! \fn void ICore::saveSettingsRequested() \brief Emitted to signal that the user has requested that the global settings should be saved to disk. At the moment that happens when the application is closed, and on \gui{Save All}. */ /*! \fn void ICore::optionsDialogRequested() \brief Signal that allows plugins to perform actions just before the \gui{Tools|Options} dialog is shown. */ /*! \fn void ICore::coreAboutToClose() \brief Plugins can do some pre-end-of-life actions when they get this signal. The application is guaranteed to shut down after this signal is emitted. It's there as an addition to the usual plugin lifecycle methods, namely IPlugin::shutdown(), just for convenience. */ /*! \fn void ICore::contextAboutToChange(Core::IContext *context) \brief Sent just before a new \a context becomes the current context (meaning that its widget got focus). */ /*! \fn void ICore::contextChanged(Core::IContext *context, const QList<int> &additionalContexts) \brief Sent just after a new \a context became the current context (meaning that its widget got focus), or if the additional context ids changed. */ <|endoftext|>
<commit_before>/* Copyright (C) 2016, BogDan Vatra <[email protected]> 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 Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <getodac/abstract_server_session.h> #include <getodac/abstract_service_session.h> #include <getodac/restful.h> #include <iostream> #include <mutex> namespace { const std::string test100response("100XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); Getodac::SpinLock test50mresponse_lock; std::string test50mresponse; Getodac::RESTful<std::shared_ptr<Getodac::AbstractServiceSession>> s_testResful("/test/rest/v1/"); class Test0 : public Getodac::AbstractServiceSession { public: Test0(Getodac::AbstractServerSession *serverSession, const std::string &url, const std::string &method) : Getodac::AbstractServiceSession(serverSession) { std::cout << url << std::endl << method << std::endl; } // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(0); m_serverSession->responseComplete(); } void writeResponse(Getodac::AbstractServerSession::Yield &/*yield*/) override { assert(false); } }; class Test100 : public Getodac::AbstractServiceSession { public: Test100(Getodac::AbstractServerSession *serverSession) : Getodac::AbstractServiceSession(serverSession) {} // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(test100response.size()); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { try { m_serverSession->write(yield, test100response.c_str(), test100response.size()); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } catch (...) { } m_serverSession->responseComplete(); } }; class Test50M : public Getodac::AbstractServiceSession { public: Test50M(Getodac::AbstractServerSession *serverSession) : Getodac::AbstractServiceSession(serverSession) { std::unique_lock<Getodac::SpinLock> lock(test50mresponse_lock); if (test50mresponse.empty()) for (int i = 0; i < 500000; ++i) test50mresponse += test100response; } // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(test50mresponse.size()); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { try { m_serverSession->write(yield, test50mresponse.c_str(), test50mresponse.size()); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } catch (...) { } m_serverSession->responseComplete(); } }; class Test50MS : public Getodac::AbstractServiceSession { public: Test50MS(Getodac::AbstractServerSession *serverSession) : Getodac::AbstractServiceSession(serverSession) { std::unique_lock<Getodac::SpinLock> lock(test50mresponse_lock); if (test50mresponse.empty()) for (int i = 0; i < 500000; ++i) test50mresponse += test100response; } // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(50000000); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { try { iovec vec[500]; for (int i = 0; i < 500; ++i) { vec[i].iov_base = (void*)test50mresponse.c_str(); vec[i].iov_len = 100000; } m_serverSession->writev(yield, vec, 500); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } catch (...) { } m_serverSession->responseComplete(); } }; class TestRESTGET : public Getodac::AbstractServiceSession { public: TestRESTGET(Getodac::AbstractServerSession *serverSession, Getodac::Resources &&resources) : Getodac::AbstractServiceSession(serverSession) , m_resources(std::move(resources)) {} // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(Getodac::ChuckedData); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { std::stringstream stream; stream << "Got " << m_resources.size() << " resources\n"; writeChunkedData(yield, stream.str()); stream.str({}); for (const auto &resource : m_resources) { stream << "Resource name: " << resource .name << " \nResource value: " << resource.value << std::endl; for (const auto &query : resource.queryStrings) stream << " " << query.first << " = " << query.second << std::endl; writeChunkedData(yield, stream.str()); stream.str({}); } writeChunkedData(yield, nullptr, 0); m_serverSession->responseComplete(); } private: Getodac::Resources m_resources; }; } // namespace PLUGIN_EXPORT std::shared_ptr<Getodac::AbstractServiceSession> createSession(Getodac::AbstractServerSession *serverSession, const std::string &url, const std::string &method) { if (url == "/test100") return std::make_shared<Test100>(serverSession); if (url == "/test50m") return std::make_shared<Test50M>(serverSession); if (url == "/test50ms") return std::make_shared<Test50MS>(serverSession); if (url == "/test0") return std::make_shared<Test0>(serverSession, url, method); if (s_testResful.canHanldle(url, method)) return s_testResful.parse(serverSession, url, method); return std::shared_ptr<Getodac::AbstractServiceSession>(); } PLUGIN_EXPORT bool initPlugin() { auto getMethod = [](Getodac::AbstractServerSession *serverSession, Getodac::Resources &&resources) { return std::make_shared<TestRESTGET>(serverSession, std::move(resources)); }; s_testResful.setMethodCallback("GET", getMethod, {"customers", "orders"}); return true; } PLUGIN_EXPORT void destoryPlugin() { } <commit_msg>Be smart<commit_after>/* Copyright (C) 2016, BogDan Vatra <[email protected]> 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 Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <getodac/abstract_server_session.h> #include <getodac/abstract_service_session.h> #include <getodac/restful.h> #include <iostream> #include <mutex> namespace { const std::string test100response("100XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); std::string test50mresponse; Getodac::RESTful<std::shared_ptr<Getodac::AbstractServiceSession>> s_testResful("/test/rest/v1/"); class Test0 : public Getodac::AbstractServiceSession { public: Test0(Getodac::AbstractServerSession *serverSession, const std::string &url, const std::string &method) : Getodac::AbstractServiceSession(serverSession) { std::cout << url << std::endl << method << std::endl; } // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(0); m_serverSession->responseComplete(); } void writeResponse(Getodac::AbstractServerSession::Yield &/*yield*/) override { assert(false); } }; class Test100 : public Getodac::AbstractServiceSession { public: Test100(Getodac::AbstractServerSession *serverSession) : Getodac::AbstractServiceSession(serverSession) {} // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(test100response.size()); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { try { m_serverSession->write(yield, test100response.c_str(), test100response.size()); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } catch (...) { } m_serverSession->responseComplete(); } }; class Test50M : public Getodac::AbstractServiceSession { public: Test50M(Getodac::AbstractServerSession *serverSession) : Getodac::AbstractServiceSession(serverSession) {} // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(test50mresponse.size()); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { try { m_serverSession->write(yield, test50mresponse.c_str(), test50mresponse.size()); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } catch (...) { } m_serverSession->responseComplete(); } }; class Test50MS : public Getodac::AbstractServiceSession { public: Test50MS(Getodac::AbstractServerSession *serverSession) : Getodac::AbstractServiceSession(serverSession) {} // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(50000000); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { try { iovec vec[500]; for (int i = 0; i < 500; ++i) { vec[i].iov_base = (void*)test50mresponse.c_str(); vec[i].iov_len = 100000; } m_serverSession->writev(yield, vec, 500); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } catch (...) { } m_serverSession->responseComplete(); } }; class TestRESTGET : public Getodac::AbstractServiceSession { public: TestRESTGET(Getodac::AbstractServerSession *serverSession, Getodac::Resources &&resources) : Getodac::AbstractServiceSession(serverSession) , m_resources(std::move(resources)) {} // ServiceSession interface void headerFieldValue(const std::string &, const std::string &) override {} void headersComplete() override {} void body(const char *, size_t) override {} void requestComplete() override { m_serverSession->responseStatus(200); m_serverSession->responseEndHeader(Getodac::ChuckedData); } void writeResponse(Getodac::AbstractServerSession::Yield &yield) override { std::stringstream stream; stream << "Got " << m_resources.size() << " resources\n"; writeChunkedData(yield, stream.str()); stream.str({}); for (const auto &resource : m_resources) { stream << "Resource name: " << resource .name << " \nResource value: " << resource.value << std::endl; for (const auto &query : resource.queryStrings) stream << " " << query.first << " = " << query.second << std::endl; writeChunkedData(yield, stream.str()); stream.str({}); } writeChunkedData(yield, nullptr, 0); m_serverSession->responseComplete(); } private: Getodac::Resources m_resources; }; } // namespace PLUGIN_EXPORT std::shared_ptr<Getodac::AbstractServiceSession> createSession(Getodac::AbstractServerSession *serverSession, const std::string &url, const std::string &method) { if (url == "/test100") return std::make_shared<Test100>(serverSession); if (url == "/test50m") return std::make_shared<Test50M>(serverSession); if (url == "/test50ms") return std::make_shared<Test50MS>(serverSession); if (url == "/test0") return std::make_shared<Test0>(serverSession, url, method); if (s_testResful.canHanldle(url, method)) return s_testResful.parse(serverSession, url, method); return std::shared_ptr<Getodac::AbstractServiceSession>(); } PLUGIN_EXPORT bool initPlugin() { test50mresponse.reserve(100 * 500000); for (int i = 0; i < 500000; ++i) test50mresponse += test100response; auto getMethod = [](Getodac::AbstractServerSession *serverSession, Getodac::Resources &&resources) { return std::make_shared<TestRESTGET>(serverSession, std::move(resources)); }; s_testResful.setMethodCallback("GET", getMethod, {"customers", "orders"}); return true; } PLUGIN_EXPORT void destoryPlugin() { } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <wincodec.h> #include "SkAutoCoInitialize.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkIStream.h" #include "SkMovie.h" #include "SkStream.h" #include "SkTScopedComPtr.h" class SkImageDecoder_WIC : public SkImageDecoder { protected: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode mode); }; bool SkImageDecoder_WIC::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) { //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert SkStream to IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkIStream::CreateFromSkStream(stream, false, &piStream); } //Make sure we're at the beginning of the stream. if (SUCCEEDED(hr)) { LARGE_INTEGER liBeginning = { 0 }; hr = piStream->Seek(liBeginning, STREAM_SEEK_SET, NULL); } //Create the decoder from the stream content. SkTScopedComPtr<IWICBitmapDecoder> piBitmapDecoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateDecoderFromStream( piStream.get() //Image to be decoded , NULL //No particular vendor , WICDecodeMetadataCacheOnDemand //Cache metadata when needed , &piBitmapDecoder //Pointer to the decoder ); } //Get the first frame from the decoder. SkTScopedComPtr<IWICBitmapFrameDecode> piBitmapFrameDecode; if (SUCCEEDED(hr)) { hr = piBitmapDecoder->GetFrame(0, &piBitmapFrameDecode); } //Get the BitmapSource interface of the frame. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceOriginal; if (SUCCEEDED(hr)) { hr = piBitmapFrameDecode->QueryInterface( IID_PPV_ARGS(&piBitmapSourceOriginal) ); } //Get the size of the bitmap. UINT width; UINT height; if (SUCCEEDED(hr)) { hr = piBitmapSourceOriginal->GetSize(&width, &height); } //Exit early if we're only looking for the bitmap bounds. if (SUCCEEDED(hr)) { bm->setConfig(SkBitmap::kARGB_8888_Config, width, height); if (SkImageDecoder::kDecodeBounds_Mode == mode) { return true; } if (!this->allocPixelRef(bm, NULL)) { return false; } } //Create a format converter. SkTScopedComPtr<IWICFormatConverter> piFormatConverter; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateFormatConverter(&piFormatConverter); } if (SUCCEEDED(hr)) { hr = piFormatConverter->Initialize( piBitmapSourceOriginal.get() //Input bitmap to convert , GUID_WICPixelFormat32bppPBGRA //Destination pixel format , WICBitmapDitherTypeNone //Specified dither patterm , NULL //Specify a particular palette , 0.f //Alpha threshold , WICBitmapPaletteTypeCustom //Palette translation type ); } //Get the BitmapSource interface of the format converter. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceConverted; if (SUCCEEDED(hr)) { hr = piFormatConverter->QueryInterface( IID_PPV_ARGS(&piBitmapSourceConverted) ); } //Copy the pixels into the bitmap. if (SUCCEEDED(hr)) { bm->lockPixels(); bm->eraseColor(0); const int stride = bm->rowBytes(); hr = piBitmapSourceConverted->CopyPixels( NULL, //Get all the pixels stride, stride * height, reinterpret_cast<BYTE *>(bm->getPixels()) ); bm->unlockPixels(); } return SUCCEEDED(hr); } ///////////////////////////////////////////////////////////////////////// SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) { return SkNEW(SkImageDecoder_WIC); } ///////////////////////////////////////////////////////////////////////// SkMovie* SkMovie::DecodeStream(SkStream* stream) { return NULL; } ///////////////////////////////////////////////////////////////////////// class SkImageEncoder_WIC : public SkImageEncoder { public: SkImageEncoder_WIC(Type t) : fType(t) {} protected: virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality); private: Type fType; }; bool SkImageEncoder_WIC::onEncode(SkWStream* stream , const SkBitmap& bm , int quality) { GUID type; switch (fType) { case kJPEG_Type: type = GUID_ContainerFormatJpeg; break; case kPNG_Type: type = GUID_ContainerFormatPng; break; default: return false; } //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert the SkWStream to an IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkWIStream::CreateFromSkWStream(stream, &piStream); } //Create an encode of the appropriate type. SkTScopedComPtr<IWICBitmapEncoder> piEncoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateEncoder(type, NULL, &piEncoder); } if (SUCCEEDED(hr)) { hr = piEncoder->Initialize(piStream.get(), WICBitmapEncoderNoCache); } //Create a the frame. SkTScopedComPtr<IWICBitmapFrameEncode> piBitmapFrameEncode; SkTScopedComPtr<IPropertyBag2> piPropertybag; if (SUCCEEDED(hr)) { hr = piEncoder->CreateNewFrame(&piBitmapFrameEncode, &piPropertybag); } if (SUCCEEDED(hr)) { PROPBAG2 name = { 0 }; name.dwType = PROPBAG2_TYPE_DATA; name.vt = VT_R4; name.pstrName = L"ImageQuality"; VARIANT value; VariantInit(&value); value.vt = VT_R4; value.fltVal = (FLOAT)(quality / 100.0); //Ignore result code. // This returns E_FAIL if the named property is not in the bag. //TODO(bungeman) enumerate the properties, // write and set hr iff property exists. piPropertybag->Write(1, &name, &value); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Initialize(piPropertybag.get()); } //Set the size of the frame. const UINT width = bm.width(); const UINT height = bm.height(); if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetSize(width, height); } //Set the pixel format of the frame. const WICPixelFormatGUID formatDesired = GUID_WICPixelFormat32bppBGRA; WICPixelFormatGUID formatGUID = formatDesired; if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetPixelFormat(&formatGUID); } if (SUCCEEDED(hr)) { //Be sure the image format is the one requested. hr = IsEqualGUID(formatGUID, formatDesired) ? S_OK : E_FAIL; } //Write the pixels into the frame. if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->WritePixels( height , bm.rowBytes() , bm.rowBytes()*height , reinterpret_cast<BYTE*>(bm.getPixels())); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Commit(); } if (SUCCEEDED(hr)) { hr = piEncoder->Commit(); } return SUCCEEDED(hr); } SkImageEncoder* SkImageEncoder::Create(Type t) { switch (t) { case kJPEG_Type: case kPNG_Type: break; default: return NULL; } return SkNEW_ARGS(SkImageEncoder_WIC, (t)); } <commit_msg>Windows image decoder should handle all bitmap formats. http://codereview.appspot.com/4801070/<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <wincodec.h> #include "SkAutoCoInitialize.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkIStream.h" #include "SkMovie.h" #include "SkStream.h" #include "SkTScopedComPtr.h" class SkImageDecoder_WIC : public SkImageDecoder { protected: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode mode); }; bool SkImageDecoder_WIC::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) { //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert SkStream to IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkIStream::CreateFromSkStream(stream, false, &piStream); } //Make sure we're at the beginning of the stream. if (SUCCEEDED(hr)) { LARGE_INTEGER liBeginning = { 0 }; hr = piStream->Seek(liBeginning, STREAM_SEEK_SET, NULL); } //Create the decoder from the stream content. SkTScopedComPtr<IWICBitmapDecoder> piBitmapDecoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateDecoderFromStream( piStream.get() //Image to be decoded , NULL //No particular vendor , WICDecodeMetadataCacheOnDemand //Cache metadata when needed , &piBitmapDecoder //Pointer to the decoder ); } //Get the first frame from the decoder. SkTScopedComPtr<IWICBitmapFrameDecode> piBitmapFrameDecode; if (SUCCEEDED(hr)) { hr = piBitmapDecoder->GetFrame(0, &piBitmapFrameDecode); } //Get the BitmapSource interface of the frame. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceOriginal; if (SUCCEEDED(hr)) { hr = piBitmapFrameDecode->QueryInterface( IID_PPV_ARGS(&piBitmapSourceOriginal) ); } //Get the size of the bitmap. UINT width; UINT height; if (SUCCEEDED(hr)) { hr = piBitmapSourceOriginal->GetSize(&width, &height); } //Exit early if we're only looking for the bitmap bounds. if (SUCCEEDED(hr)) { bm->setConfig(SkBitmap::kARGB_8888_Config, width, height); if (SkImageDecoder::kDecodeBounds_Mode == mode) { return true; } if (!this->allocPixelRef(bm, NULL)) { return false; } } //Create a format converter. SkTScopedComPtr<IWICFormatConverter> piFormatConverter; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateFormatConverter(&piFormatConverter); } if (SUCCEEDED(hr)) { hr = piFormatConverter->Initialize( piBitmapSourceOriginal.get() //Input bitmap to convert , GUID_WICPixelFormat32bppPBGRA //Destination pixel format , WICBitmapDitherTypeNone //Specified dither patterm , NULL //Specify a particular palette , 0.f //Alpha threshold , WICBitmapPaletteTypeCustom //Palette translation type ); } //Get the BitmapSource interface of the format converter. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceConverted; if (SUCCEEDED(hr)) { hr = piFormatConverter->QueryInterface( IID_PPV_ARGS(&piBitmapSourceConverted) ); } //Copy the pixels into the bitmap. if (SUCCEEDED(hr)) { bm->lockPixels(); bm->eraseColor(0); const int stride = bm->rowBytes(); hr = piBitmapSourceConverted->CopyPixels( NULL, //Get all the pixels stride, stride * height, reinterpret_cast<BYTE *>(bm->getPixels()) ); bm->unlockPixels(); } return SUCCEEDED(hr); } ///////////////////////////////////////////////////////////////////////// SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) { return SkNEW(SkImageDecoder_WIC); } ///////////////////////////////////////////////////////////////////////// SkMovie* SkMovie::DecodeStream(SkStream* stream) { return NULL; } ///////////////////////////////////////////////////////////////////////// class SkImageEncoder_WIC : public SkImageEncoder { public: SkImageEncoder_WIC(Type t) : fType(t) {} protected: virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality); private: Type fType; }; bool SkImageEncoder_WIC::onEncode(SkWStream* stream , const SkBitmap& bitmapOrig , int quality) { GUID type; switch (fType) { case kJPEG_Type: type = GUID_ContainerFormatJpeg; break; case kPNG_Type: type = GUID_ContainerFormatPng; break; default: return false; } //Convert to 8888 if needed. const SkBitmap* bitmap; SkBitmap bitmapCopy; if (SkBitmap::kARGB_8888_Config == bitmapOrig.config()) { bitmap = &bitmapOrig; } else { if (!bitmapOrig.copyTo(&bitmapCopy, SkBitmap::kARGB_8888_Config)) { return false; } bitmap = &bitmapCopy; } //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert the SkWStream to an IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkWIStream::CreateFromSkWStream(stream, &piStream); } //Create an encode of the appropriate type. SkTScopedComPtr<IWICBitmapEncoder> piEncoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateEncoder(type, NULL, &piEncoder); } if (SUCCEEDED(hr)) { hr = piEncoder->Initialize(piStream.get(), WICBitmapEncoderNoCache); } //Create a the frame. SkTScopedComPtr<IWICBitmapFrameEncode> piBitmapFrameEncode; SkTScopedComPtr<IPropertyBag2> piPropertybag; if (SUCCEEDED(hr)) { hr = piEncoder->CreateNewFrame(&piBitmapFrameEncode, &piPropertybag); } if (SUCCEEDED(hr)) { PROPBAG2 name = { 0 }; name.dwType = PROPBAG2_TYPE_DATA; name.vt = VT_R4; name.pstrName = L"ImageQuality"; VARIANT value; VariantInit(&value); value.vt = VT_R4; value.fltVal = (FLOAT)(quality / 100.0); //Ignore result code. // This returns E_FAIL if the named property is not in the bag. //TODO(bungeman) enumerate the properties, // write and set hr iff property exists. piPropertybag->Write(1, &name, &value); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Initialize(piPropertybag.get()); } //Set the size of the frame. const UINT width = bitmap->width(); const UINT height = bitmap->height(); if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetSize(width, height); } //Set the pixel format of the frame. const WICPixelFormatGUID formatDesired = GUID_WICPixelFormat32bppBGRA; WICPixelFormatGUID formatGUID = formatDesired; if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetPixelFormat(&formatGUID); } if (SUCCEEDED(hr)) { //Be sure the image format is the one requested. hr = IsEqualGUID(formatGUID, formatDesired) ? S_OK : E_FAIL; } //Write the pixels into the frame. if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->WritePixels( height , bitmap->rowBytes() , bitmap->rowBytes()*height , reinterpret_cast<BYTE*>(bitmap->getPixels())); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Commit(); } if (SUCCEEDED(hr)) { hr = piEncoder->Commit(); } return SUCCEEDED(hr); } SkImageEncoder* SkImageEncoder::Create(Type t) { switch (t) { case kJPEG_Type: case kPNG_Type: break; default: return NULL; } return SkNEW_ARGS(SkImageEncoder_WIC, (t)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #include "dynamic_string.h" #include "filesystem.h" #include "memory.h" #include "path.h" #include "queue.h" #include "resource_loader.h" #include "temp_allocator.h" namespace crown { ResourceLoader::ResourceLoader(Filesystem& fs) : _fs(fs) , _requests(default_allocator()) , _loaded(default_allocator()) , _exit(false) { _thread.start(ResourceLoader::thread_proc, this); } ResourceLoader::~ResourceLoader() { _exit = true; _thread.stop(); } bool ResourceLoader::can_load(StringId64 type, StringId64 name) { TempAllocator128 ta; DynamicString type_str(ta); DynamicString name_str(ta); type.to_string(type_str); name.to_string(name_str); DynamicString res_path(ta); res_path += type_str; res_path += '-'; res_path += name_str; DynamicString path(ta); path::join(CROWN_DATA_DIRECTORY, res_path.c_str(), path); return _fs.exists(path.c_str()); } void ResourceLoader::add_request(const ResourceRequest& rr) { ScopedMutex sm(_mutex); queue::push_back(_requests, rr); } void ResourceLoader::flush() { while (num_requests()) {} } u32 ResourceLoader::num_requests() { ScopedMutex sm(_mutex); return queue::size(_requests); } void ResourceLoader::add_loaded(ResourceRequest rr) { ScopedMutex sm(_loaded_mutex); queue::push_back(_loaded, rr); } void ResourceLoader::get_loaded(Array<ResourceRequest>& loaded) { ScopedMutex sm(_loaded_mutex); const u32 num = queue::size(_loaded); array::reserve(loaded, num); for (u32 i = 0; i < num; ++i) { array::push_back(loaded, queue::front(_loaded)); queue::pop_front(_loaded); } } s32 ResourceLoader::run() { while (!_exit) { _mutex.lock(); if (queue::empty(_requests)) { _mutex.unlock(); continue; } ResourceRequest rr = queue::front(_requests); _mutex.unlock(); TempAllocator128 ta; DynamicString type_str(ta); DynamicString name_str(ta); rr.type.to_string(type_str); rr.name.to_string(name_str); DynamicString res_path(ta); res_path += type_str; res_path += '-'; res_path += name_str; DynamicString path(ta); path::join(CROWN_DATA_DIRECTORY, res_path.c_str(), path); File* file = _fs.open(path.c_str(), FileOpenMode::READ); rr.data = rr.load_function(*file, *rr.allocator); _fs.close(*file); add_loaded(rr); _mutex.lock(); queue::pop_front(_requests); _mutex.unlock(); } return 0; } s32 ResourceLoader::thread_proc(void* thiz) { return ((ResourceLoader*)thiz)->run(); } } // namespace crown <commit_msg>Waste less CPU time<commit_after>/* * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #include "dynamic_string.h" #include "filesystem.h" #include "memory.h" #include "os.h" #include "path.h" #include "queue.h" #include "resource_loader.h" #include "temp_allocator.h" namespace crown { ResourceLoader::ResourceLoader(Filesystem& fs) : _fs(fs) , _requests(default_allocator()) , _loaded(default_allocator()) , _exit(false) { _thread.start(ResourceLoader::thread_proc, this); } ResourceLoader::~ResourceLoader() { _exit = true; _thread.stop(); } bool ResourceLoader::can_load(StringId64 type, StringId64 name) { TempAllocator128 ta; DynamicString type_str(ta); DynamicString name_str(ta); type.to_string(type_str); name.to_string(name_str); DynamicString res_path(ta); res_path += type_str; res_path += '-'; res_path += name_str; DynamicString path(ta); path::join(CROWN_DATA_DIRECTORY, res_path.c_str(), path); return _fs.exists(path.c_str()); } void ResourceLoader::add_request(const ResourceRequest& rr) { ScopedMutex sm(_mutex); queue::push_back(_requests, rr); } void ResourceLoader::flush() { while (num_requests()) {} } u32 ResourceLoader::num_requests() { ScopedMutex sm(_mutex); return queue::size(_requests); } void ResourceLoader::add_loaded(ResourceRequest rr) { ScopedMutex sm(_loaded_mutex); queue::push_back(_loaded, rr); } void ResourceLoader::get_loaded(Array<ResourceRequest>& loaded) { ScopedMutex sm(_loaded_mutex); const u32 num = queue::size(_loaded); array::reserve(loaded, num); for (u32 i = 0; i < num; ++i) { array::push_back(loaded, queue::front(_loaded)); queue::pop_front(_loaded); } } s32 ResourceLoader::run() { while (!_exit) { _mutex.lock(); if (queue::empty(_requests)) { _mutex.unlock(); os::sleep(16); continue; } ResourceRequest rr = queue::front(_requests); _mutex.unlock(); TempAllocator128 ta; DynamicString type_str(ta); DynamicString name_str(ta); rr.type.to_string(type_str); rr.name.to_string(name_str); DynamicString res_path(ta); res_path += type_str; res_path += '-'; res_path += name_str; DynamicString path(ta); path::join(CROWN_DATA_DIRECTORY, res_path.c_str(), path); File* file = _fs.open(path.c_str(), FileOpenMode::READ); rr.data = rr.load_function(*file, *rr.allocator); _fs.close(*file); add_loaded(rr); _mutex.lock(); queue::pop_front(_requests); _mutex.unlock(); } return 0; } s32 ResourceLoader::thread_proc(void* thiz) { return ((ResourceLoader*)thiz)->run(); } } // namespace crown <|endoftext|>
<commit_before>/* * This file is part of Clockwork. * * Copyright (c) 2014-2016 Jeremy Othieno. * * The MIT License (MIT) * 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. */ #ifndef CLOCKWORK_SCENE_OBJECT_PROPERTY_HH #define CLOCKWORK_SCENE_OBJECT_PROPERTY_HH #include "SceneNode.hh" namespace clockwork { /** * @see SceneObject.hh */ class SceneObject; /** * A SceneObjectProperty defines a characteristic or behavior of a SceneObject. */ class SceneObjectProperty : public SceneNode { public: /** * An enumeration of the available types of properties. */ enum class Type { Appearance, //LightEmission, }; /** * */ SceneObjectProperty(const SceneObjectProperty&) = delete; /** * */ SceneObjectProperty(SceneObjectProperty&&) = delete; /** * */ SceneObjectProperty& operator=(const SceneObjectProperty&) = delete; /** * */ SceneObjectProperty& operator=(SceneObjectProperty&&) = delete; /** * Returns the property's owner. */ SceneObject& getOwner(); /** * Returns the property's type. */ Type getType() const; protected: /** * Instantiates a named SceneObjectProperty object attached to a given SceneObject instance. * @param owner the scene object that is characterized by this property. * @param type the property's internal type. */ SceneObjectProperty(SceneObject& owner, const Type type); private: /** * The property's owner, i.e. the object that is characterized by this property. */ SceneObject& owner_; /** * The property's type. */ const Type type_; }; /** * Returns the specified type's hash. * @param type the SceneObjectProperty type to hash. */ uint qHash(SceneObjectProperty::Type type); } // namespace clockwork #endif // CLOCKWORK_SCENE_OBJECT_PROPERTY_HH <commit_msg>Update the SceneObjectProperty class' documentation<commit_after>/* * This file is part of Clockwork. * * Copyright (c) 2014-2016 Jeremy Othieno. * * The MIT License (MIT) * 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. */ #ifndef CLOCKWORK_SCENE_OBJECT_PROPERTY_HH #define CLOCKWORK_SCENE_OBJECT_PROPERTY_HH #include "SceneNode.hh" namespace clockwork { /** * @see SceneObject.hh */ class SceneObject; /** * A SceneObjectProperty defines a characteristic or behavior of a SceneObject. * A SceneObject may have at most one property of a given type. */ class SceneObjectProperty : public SceneNode { public: /** * An enumeration of the available types of properties. */ enum class Type { Appearance, //LightEmission, }; /** * */ SceneObjectProperty(const SceneObjectProperty&) = delete; /** * */ SceneObjectProperty(SceneObjectProperty&&) = delete; /** * */ SceneObjectProperty& operator=(const SceneObjectProperty&) = delete; /** * */ SceneObjectProperty& operator=(SceneObjectProperty&&) = delete; /** * Returns the property's owner. */ SceneObject& getOwner(); /** * Returns the property's type. */ Type getType() const; protected: /** * Instantiates a named SceneObjectProperty object attached to a given SceneObject instance. * @param owner the scene object that is characterized by this property. * @param type the property's internal type. */ SceneObjectProperty(SceneObject& owner, const Type type); private: /** * The property's owner, i.e. the object that is characterized by this property. */ SceneObject& owner_; /** * The property's type. */ const Type type_; }; /** * Returns the specified type's hash. * @param type the SceneObjectProperty type to hash. */ uint qHash(SceneObjectProperty::Type type); } // namespace clockwork #endif // CLOCKWORK_SCENE_OBJECT_PROPERTY_HH <|endoftext|>
<commit_before>///////////////////////////////////////// // // OpenLieroX // // code under LGPL, based on JasonBs work, // enhanced by Dark Charlie and Albert Zeyer // // ///////////////////////////////////////// // Client class // Created 28/6/02 // Jason Boettcher #include "LieroX.h" #include "ProfileSystem.h" #include "CServerConnection.h" #include "CBonus.h" #include "CWorm.h" #include "Error.h" #include "Protocol.h" #include "StringUtils.h" #include "MathLib.h" #include "EndianSwap.h" #include "Version.h" #include "CServer.h" #include "AuxLib.h" #include "Networking.h" #include "CServerNetEngine.h" #include "CChannel.h" #include <iostream> using namespace std; CServerConnection::CServerConnection( GameServer * _server ) { server = _server ? _server : cServer; cRemoteWorms = NULL; iNumWorms = 0; cNetChan = NULL; bsUnreliable.Clear(); iNetSpeed = 3; fLastUpdateSent = -9999; bLocalClient = false; fSendWait = 0; bMuted = false; bGameReady = false; fLastFileRequest = fConnectTime = tLX->fCurTime; cNetEngine = new CServerNetEngine( server, this ); } /////////////////// // Clear the client details void CServerConnection::Clear(void) { iNumWorms = 0; int i; for(i=0;i<MAX_PLAYERS;i++) cLocalWorms[i] = NULL; cRemoteWorms = NULL; if( cNetChan ) delete cNetChan; cNetChan = NULL; iNetStatus = NET_DISCONNECTED; bsUnreliable.Clear(); bLocalClient = false; fLastReceived = 99999; fSendWait = 0; fLastUpdateSent = -9999; cShootList.Shutdown(); fLastFileRequest = fLastFileRequestPacketReceived = tLX->fCurTime; getUdpFileDownloader()->reset(); } /////////////////// // Clear the client for another game void CServerConnection::MinorClear(void) { iNetStatus = NET_CONNECTED; fLastReceived = 99999; fSendWait = 0; int i; for(i=0; i<MAX_WORMS; i++) { cRemoteWorms[i].Unprepare(); } fLastFileRequest = fLastFileRequestPacketReceived = tLX->fCurTime; getUdpFileDownloader()->reset(); } /////////////////// // Initialize the client int CServerConnection::Initialize(void) { // TODO: where is this function used? it's totally messed up and does not make much sense at various places assert(false); uint i; // Shutdown & clear any old client data Shutdown(); Clear(); iNetSpeed = tLXOptions->iNetworkSpeed; // Local/host games use instant speed if(tGameInfo.iGameType != GME_JOIN) iNetSpeed = NST_LOCAL; // Initialize the local worms iNumWorms = tGameInfo.iNumPlayers; // TODO: wtf? for(i=0;i<iNumWorms;i++) { cLocalWorms[i] = NULL; } // Initialize the remote worms cRemoteWorms = new CWorm[MAX_WORMS]; if(cRemoteWorms == NULL) { SetError("Error: Out of memory!\ncl::Initialize() " + itoa(__LINE__)); return false; } // Set id's for(i=0;i<MAX_WORMS;i++) { cRemoteWorms[i].Init(); cRemoteWorms[i].setID(i); cRemoteWorms[i].setTagIT(false); cRemoteWorms[i].setTagTime(0); cRemoteWorms[i].setTeam(0); cRemoteWorms[i].setFlag(false); cRemoteWorms[i].setUsed(false); cRemoteWorms[i].setClient(NULL); // Local worms won't get server connection owner } // Initialize the shooting list cShootList.Initialize(); return true; } /////////////////// // Return true if we own the worm int CServerConnection::OwnsWorm(int id) { for(uint i=0;i<iNumWorms;i++) { if(id == cLocalWorms[i]->getID()) return true; } return false; } ////////////////// // Remove the worm void CServerConnection::RemoveWorm(int id) { if(iNumWorms == 0) { cout << "WARNING: cannot remove worm because this client has no worms" << endl; return; } bool found = false; for (uint i=0;i<iNumWorms;i++) { if (cLocalWorms[i]) { if (cLocalWorms[i]->getID() == id) { cLocalWorms[i] = NULL; for (uint j=i; j<MAX_PLAYERS-1; j++) { cLocalWorms[j] = cLocalWorms[j+1]; } found = true; break; } } else cout << "WARNING: cLocalWorms[" << i << "/" << iNumWorms << "] == NULL" << endl; } if(found) --iNumWorms; else cout << "WARNING: cannot find worm " << id << " for removal" << endl; if (cRemoteWorms) { for (uint i=0;i<MAX_WORMS;i++) { if (cRemoteWorms[i].getID() == id) { cRemoteWorms[i].Unprepare(); // TODO: why not a Clear() here? cRemoteWorms[i].setUsed(false); cRemoteWorms[i].setAlive(false); cRemoteWorms[i].setKills(0); cRemoteWorms[i].setLives(WRM_OUT); cRemoteWorms[i].setProfile(NULL); cRemoteWorms[i].setType(PRF_HUMAN); cRemoteWorms[i].setLocal(false); cRemoteWorms[i].setTagIT(false); cRemoteWorms[i].setTagTime(0); } } } } /////////////////// // Shutdown the client void CServerConnection::Shutdown(void) { int i; iNumWorms = 0; for(int i = 0; i < MAX_PLAYERS; ++i) cLocalWorms[i] = NULL; // Remote worms if(cRemoteWorms) { for(i=0;i<MAX_WORMS;i++) cRemoteWorms[i].Shutdown(); delete[] cRemoteWorms; cRemoteWorms = NULL; } // Shooting list cShootList.Shutdown(); } void CServerConnection::setClientVersion(const Version& v) { cClientVersion = v; printf(this->debugName() + " is using " + cClientVersion.asString() + "\n"); } void CServerConnection::setNetEngineFromClientVersion() { if(cNetEngine) delete cNetEngine; cNetEngine = NULL; if( getClientVersion() >= OLXBetaVersion(7) ) { cNetEngine = new CServerNetEngineBeta7( server, this ); } else { cNetEngine = new CServerNetEngine( server, this ); } } CChannel * CServerConnection::createChannel(const Version& v) { if( cNetChan ) delete cNetChan; if( v >= OLXBetaVersion(6) ) cNetChan = new CChannel_UberPwnyReliable(); else cNetChan = new CChannel_056b(); return cNetChan; } std::string CServerConnection::debugName() { std::string adr = "?.?.?.?"; if(isLocalClient()) adr = "local"; else if(!getChannel()) { printf("WARNING: CServerConnection::debugName(): getChannel() == NULL\n"); } else if(!NetAddrToString(getChannel()->getAddress(), adr)) { printf("WARNING: CServerConnection::debugName(): NetAddrToString failed\n"); } std::string worms = "no worms"; if(getNumWorms() > 0) { worms = ""; for(int i = 0; i < getNumWorms(); ++i) { if(i > 0) worms += ", "; if(getWorm(i)) { worms += itoa(getWorm(i)->getID()); worms += " '"; worms += getWorm(i)->getName(); worms += "'"; } else { worms += "BAD"; } } } return "CServerConnection(" + adr +") with " + worms; } int CServerConnection::getPing() { return cNetChan->getPing(); } void CServerConnection::setPing(int _p) { cNetChan->setPing(_p); } <commit_msg>Fixed net engine not freed in CServerConnection (pretty important leak, i got about 100 leaks in 5 minutes of hosting)<commit_after>///////////////////////////////////////// // // OpenLieroX // // code under LGPL, based on JasonBs work, // enhanced by Dark Charlie and Albert Zeyer // // ///////////////////////////////////////// // Client class // Created 28/6/02 // Jason Boettcher #include "LieroX.h" #include "ProfileSystem.h" #include "CServerConnection.h" #include "CBonus.h" #include "CWorm.h" #include "Error.h" #include "Protocol.h" #include "StringUtils.h" #include "MathLib.h" #include "EndianSwap.h" #include "Version.h" #include "CServer.h" #include "AuxLib.h" #include "Networking.h" #include "CServerNetEngine.h" #include "CChannel.h" #include <iostream> using namespace std; CServerConnection::CServerConnection( GameServer * _server ) { server = _server ? _server : cServer; cRemoteWorms = NULL; iNumWorms = 0; cNetChan = NULL; bsUnreliable.Clear(); iNetSpeed = 3; fLastUpdateSent = -9999; bLocalClient = false; fSendWait = 0; bMuted = false; bGameReady = false; fLastFileRequest = fConnectTime = tLX->fCurTime; cNetEngine = new CServerNetEngine( server, this ); } /////////////////// // Clear the client details void CServerConnection::Clear(void) { iNumWorms = 0; int i; for(i=0;i<MAX_PLAYERS;i++) cLocalWorms[i] = NULL; cRemoteWorms = NULL; if( cNetChan ) delete cNetChan; cNetChan = NULL; iNetStatus = NET_DISCONNECTED; bsUnreliable.Clear(); bLocalClient = false; fLastReceived = 99999; fSendWait = 0; fLastUpdateSent = -9999; cShootList.Shutdown(); fLastFileRequest = fLastFileRequestPacketReceived = tLX->fCurTime; getUdpFileDownloader()->reset(); } /////////////////// // Clear the client for another game void CServerConnection::MinorClear(void) { iNetStatus = NET_CONNECTED; fLastReceived = 99999; fSendWait = 0; int i; for(i=0; i<MAX_WORMS; i++) { cRemoteWorms[i].Unprepare(); } fLastFileRequest = fLastFileRequestPacketReceived = tLX->fCurTime; getUdpFileDownloader()->reset(); } /////////////////// // Initialize the client int CServerConnection::Initialize(void) { // TODO: where is this function used? it's totally messed up and does not make much sense at various places assert(false); uint i; // Shutdown & clear any old client data Shutdown(); Clear(); iNetSpeed = tLXOptions->iNetworkSpeed; // Local/host games use instant speed if(tGameInfo.iGameType != GME_JOIN) iNetSpeed = NST_LOCAL; // Initialize the local worms iNumWorms = tGameInfo.iNumPlayers; // TODO: wtf? for(i=0;i<iNumWorms;i++) { cLocalWorms[i] = NULL; } // Initialize the remote worms cRemoteWorms = new CWorm[MAX_WORMS]; if(cRemoteWorms == NULL) { SetError("Error: Out of memory!\ncl::Initialize() " + itoa(__LINE__)); return false; } // Set id's for(i=0;i<MAX_WORMS;i++) { cRemoteWorms[i].Init(); cRemoteWorms[i].setID(i); cRemoteWorms[i].setTagIT(false); cRemoteWorms[i].setTagTime(0); cRemoteWorms[i].setTeam(0); cRemoteWorms[i].setFlag(false); cRemoteWorms[i].setUsed(false); cRemoteWorms[i].setClient(NULL); // Local worms won't get server connection owner } // Initialize the shooting list cShootList.Initialize(); return true; } /////////////////// // Return true if we own the worm int CServerConnection::OwnsWorm(int id) { for(uint i=0;i<iNumWorms;i++) { if(id == cLocalWorms[i]->getID()) return true; } return false; } ////////////////// // Remove the worm void CServerConnection::RemoveWorm(int id) { if(iNumWorms == 0) { cout << "WARNING: cannot remove worm because this client has no worms" << endl; return; } bool found = false; for (uint i=0;i<iNumWorms;i++) { if (cLocalWorms[i]) { if (cLocalWorms[i]->getID() == id) { cLocalWorms[i] = NULL; for (uint j=i; j<MAX_PLAYERS-1; j++) { cLocalWorms[j] = cLocalWorms[j+1]; } found = true; break; } } else cout << "WARNING: cLocalWorms[" << i << "/" << iNumWorms << "] == NULL" << endl; } if(found) --iNumWorms; else cout << "WARNING: cannot find worm " << id << " for removal" << endl; if (cRemoteWorms) { for (uint i=0;i<MAX_WORMS;i++) { if (cRemoteWorms[i].getID() == id) { cRemoteWorms[i].Unprepare(); // TODO: why not a Clear() here? cRemoteWorms[i].setUsed(false); cRemoteWorms[i].setAlive(false); cRemoteWorms[i].setKills(0); cRemoteWorms[i].setLives(WRM_OUT); cRemoteWorms[i].setProfile(NULL); cRemoteWorms[i].setType(PRF_HUMAN); cRemoteWorms[i].setLocal(false); cRemoteWorms[i].setTagIT(false); cRemoteWorms[i].setTagTime(0); } } } } /////////////////// // Shutdown the client void CServerConnection::Shutdown(void) { int i; iNumWorms = 0; for(int i = 0; i < MAX_PLAYERS; ++i) cLocalWorms[i] = NULL; // Remote worms if(cRemoteWorms) { for(i=0;i<MAX_WORMS;i++) cRemoteWorms[i].Shutdown(); delete[] cRemoteWorms; cRemoteWorms = NULL; } // Shooting list cShootList.Shutdown(); // Net engine if (cNetEngine) delete cNetEngine; cNetEngine = NULL; } void CServerConnection::setClientVersion(const Version& v) { cClientVersion = v; printf(this->debugName() + " is using " + cClientVersion.asString() + "\n"); } void CServerConnection::setNetEngineFromClientVersion() { if(cNetEngine) delete cNetEngine; cNetEngine = NULL; if( getClientVersion() >= OLXBetaVersion(7) ) { cNetEngine = new CServerNetEngineBeta7( server, this ); } else { cNetEngine = new CServerNetEngine( server, this ); } } CChannel * CServerConnection::createChannel(const Version& v) { if( cNetChan ) delete cNetChan; if( v >= OLXBetaVersion(6) ) cNetChan = new CChannel_UberPwnyReliable(); else cNetChan = new CChannel_056b(); return cNetChan; } std::string CServerConnection::debugName() { std::string adr = "?.?.?.?"; if(isLocalClient()) adr = "local"; else if(!getChannel()) { printf("WARNING: CServerConnection::debugName(): getChannel() == NULL\n"); } else if(!NetAddrToString(getChannel()->getAddress(), adr)) { printf("WARNING: CServerConnection::debugName(): NetAddrToString failed\n"); } std::string worms = "no worms"; if(getNumWorms() > 0) { worms = ""; for(int i = 0; i < getNumWorms(); ++i) { if(i > 0) worms += ", "; if(getWorm(i)) { worms += itoa(getWorm(i)->getID()); worms += " '"; worms += getWorm(i)->getName(); worms += "'"; } else { worms += "BAD"; } } } return "CServerConnection(" + adr +") with " + worms; } int CServerConnection::getPing() { return cNetChan->getPing(); } void CServerConnection::setPing(int _p) { cNetChan->setPing(_p); } <|endoftext|>
<commit_before>#ifndef DICT_KEY_VALUE_HPP #define DICT_KEY_VALUE_HPP #include <utility> namespace io { namespace detail { // inspired/taken from libc++ template <class Key, class Value> union key_value { typedef Key key_type; typedef Value mapped_type; typedef std::pair<const key_type, mapped_type> value_type; typedef std::pair<key_type, mapped_type> internal_value_type; value_type const_view; internal_value_type view; template <typename... Args> key_value(Args&&... args) : const_view(std::forward<Args>(args)...) {} // The following version in comparison to the variadic above also allows // clang 3.5 to compile the code in c++1y mode. gcc49 is fine without it. // Not sure whether this is a bug or not // key_value() : const_view() {} // key_value(value_type&& other) : const_view(std::move(other)) {} // key_value(const value_type& other) : const_view(other) {} // template<typename K, typename V> // key_value(K&& k, V&& v) : const_view(std::forward<K>(k), // std::forward<V>(v)) {} template <typename dummy = value_type, typename = typename std::enable_if< std::is_copy_constructible<dummy>::value>::type> key_value(const key_value& other) : const_view(other.const_view) {} key_value(key_value&& other) noexcept(std::is_nothrow_move_constructible<internal_value_type>::value) : view(std::move(other.view)) {} template <typename dummy = value_type, typename = typename std::enable_if< std::is_copy_assignable<dummy>::value>::type> key_value& operator=(const key_value& other) { view = other.const_view; return *this; } key_value& operator=(key_value&& other) noexcept( std::is_nothrow_move_assignable<internal_value_type>::value) { view = std::move(other.view); return *this; } ~key_value() { const_view.~value_type(); } }; } // detail } // namespace io #endif <commit_msg>removed bugged conditional copy ctor/assignment<commit_after>#ifndef DICT_KEY_VALUE_HPP #define DICT_KEY_VALUE_HPP #include <utility> namespace io { namespace detail { // inspired/taken from libc++ template <class Key, class Value> union key_value { typedef Key key_type; typedef Value mapped_type; typedef std::pair<const key_type, mapped_type> value_type; typedef std::pair<key_type, mapped_type> internal_value_type; value_type const_view; internal_value_type view; template <typename... Args> key_value(Args&&... args) : const_view(std::forward<Args>(args)...) {} // The following version in comparison to the variadic above also allows // clang 3.5 to compile the code in c++1y mode. gcc49 is fine without it. // Not sure whether this is a bug or not // key_value() : const_view() {} // key_value(value_type&& other) : const_view(std::move(other)) {} // key_value(const value_type& other) : const_view(other) {} // template<typename K, typename V> // key_value(K&& k, V&& v) : const_view(std::forward<K>(k), // std::forward<V>(v)) {} key_value(const key_value& other) : const_view(other.const_view) {} key_value(key_value&& other) noexcept(std::is_nothrow_move_constructible<internal_value_type>::value) : view(std::move(other.view)) {} key_value& operator=(const key_value& other) { view = other.const_view; return *this; } key_value& operator=(key_value&& other) noexcept( std::is_nothrow_move_assignable<internal_value_type>::value) { view = std::move(other.view); return *this; } ~key_value() { const_view.~value_type(); } }; } // detail } // namespace io #endif <|endoftext|>
<commit_before>#pragma once #include <atomic> #include <dsnutil/observable.hpp> #include <dsnutil/observer.hpp> namespace dsn { template <typename T> class observing_ptr : public observer { static_assert(is_observable<T>::value, "observing_ptr<T> only works with subclasses of dsn::observable!"); private: std::atomic<T*> m_object{ nullptr }; virtual void observable_destroyed(observable& o) override; public: observing_ptr() = default; observing_ptr(T* obj); observing_ptr(T& obj); ~observing_ptr(); observing_ptr(const observing_ptr& other); observing_ptr& operator=(const observing_ptr& other); observing_ptr(observing_ptr&& other) noexcept; observing_ptr& operator=(observing_ptr&& other) noexcept; void reset(T* obj = nullptr); void reset(T& obj); T* get(); T& operator*(); const T& operator*() const; T* operator->(); const T* operator->() const; operator bool() const; void swap(observing_ptr& other) noexcept; bool operator==(const observing_ptr& other) const; bool operator!=(const observing_ptr& other) const; }; /// \brief Construct from pointer /// /// \param obj Pointer to the \p Observable that shall be tracked template <typename T> observing_ptr<T>::observing_ptr(T* obj) : m_object(obj) { if (m_object != nullptr) { m_object.load()->addObserver(*this); } } /// \brief Construct from reference /// /// \param obj Reference to the \p Observable that shall be tracked template <typename T> observing_ptr<T>::observing_ptr(T& obj) : m_object(&obj) { m_object.load()->addObserver(*this); } /// \brief Remove observing pointer /// /// Unregisters ourself from the pointed-to \p Observable template <typename T> observing_ptr<T>::~observing_ptr() { if (m_object != nullptr) { m_object.load()->removeObserver(*this); } } /// \brief Copy-construct from other observing_ptr /// /// \param other Reference to another \p observing_ptr that shall be copied template <typename T> observing_ptr<T>::observing_ptr(const observing_ptr<T>& other) : m_object(other.m_object.load()) { if (m_object != nullptr) { m_object.load()->addObserver(*this); } } /// \brief Copy-assign from other observing_ptr /// /// \param other Reference to another \p observing_ptr that shall be copied template <typename T> observing_ptr<T>& observing_ptr<T>::operator=(const observing_ptr<T>& other) { reset(other.m_object); return *this; } /// \brief Move-construct from another observing_ptr /// /// \param other rvalue reference to another \p observing_ptr that we shall take over template <typename T> observing_ptr<T>::observing_ptr(observing_ptr<T>&& other) noexcept : m_object(other.m_object.load()) { if (m_object != nullptr) { m_object.load()->moveObserver(other, *this); } other.m_object = nullptr; } /// \brief Move-assign from another observing_ptr /// /// \param other rvalue reference to another \p observing_ptr that we shall take over template <typename T> observing_ptr<T>& observing_ptr<T>::operator=(observing_ptr<T>&& other) noexcept { reset(); m_object = other.m_object.load(); if (m_object != nullptr) { m_object.load()->moveObserver(other, *this); } other.m_object = nullptr; return *this; } /// \brief Reset from pointer /// /// Sets the pointed-to object to \a obj and registers/unregisters ourself as an observer as needed. /// /// \param obj Pointer to the new \p Observable that shall be tracked template <typename T> void observing_ptr<T>::reset(T* obj) { if (obj != nullptr) { obj->addObserver(*this); } if (m_object != nullptr) { m_object.load()->removeObserver(*this); } m_object = obj; } /// \brief Reset from reference /// /// Sets the pointed-to object to \a obj and registers/unregisters ourself as an observer as needed. /// /// \param obj Reference to the new \p Observable that shall be tracked template <typename T> void observing_ptr<T>::reset(T& obj) { obj.addObserver(*this); if (m_object != nullptr) { m_object.load()->removeObserver(*this); } m_object = &obj; } /// \brief Access by raw pointer template <typename T> T* observing_ptr<T>::get() { return m_object.load(); } /// \brief Reference access template <typename T> T& observing_ptr<T>::operator*() { return *m_object.load(); } /// \brief Constant reference access template <typename T> const T& observing_ptr<T>::operator*() const { return *m_object.load(); } /// \brief Dereference operator template <typename T> T* observing_ptr<T>::operator->() { return m_object.load(); } /// \brief Const dereference operator template <typename T> const T* observing_ptr<T>::operator->() const { return m_object.load(); } /// \brief Cast to boolean value /// /// \return true if the object we're pointing to is still alive or false if it has been destroyed template <typename T> observing_ptr<T>::operator bool() const { return (m_object != nullptr); } template <typename T> void observing_ptr<T>::swap(observing_ptr<T>& other) noexcept { if (m_object != nullptr) { m_object.load()->moveObserver(*this, other); } if (other.m_object) { other.m_object.load()->moveObserver(other, *this); } std::swap(m_object, other.m_object); } /// \brief Comparison operator (equality) template <typename T> bool observing_ptr<T>::operator==(const observing_ptr<T>& other) const { return (m_object == other.m_object); } /// \brief Comparison operator (inequality) template <typename T> bool observing_ptr<T>::operator!=(const observing_ptr<T>& other) const { return (m_object != other.m_object); } template <typename T> void observing_ptr<T>::observable_destroyed(observable& o) { m_object = nullptr; } } <commit_msg>observing_ptr: Add implementation for default ctor<commit_after>#pragma once #include <atomic> #include <dsnutil/observable.hpp> #include <dsnutil/observer.hpp> namespace dsn { template <typename T> class observing_ptr : public observer { static_assert(is_observable<T>::value, "observing_ptr<T> only works with subclasses of dsn::observable!"); private: std::atomic<T*> m_object{ nullptr }; virtual void observable_destroyed(observable& o) override; public: observing_ptr() { m_object = nullptr; } observing_ptr(T* obj); observing_ptr(T& obj); ~observing_ptr(); observing_ptr(const observing_ptr& other); observing_ptr& operator=(const observing_ptr& other); observing_ptr(observing_ptr&& other) noexcept; observing_ptr& operator=(observing_ptr&& other) noexcept; void reset(T* obj = nullptr); void reset(T& obj); T* get(); T& operator*(); const T& operator*() const; T* operator->(); const T* operator->() const; operator bool() const; void swap(observing_ptr& other) noexcept; bool operator==(const observing_ptr& other) const; bool operator!=(const observing_ptr& other) const; }; /// \brief Construct from pointer /// /// \param obj Pointer to the \p Observable that shall be tracked template <typename T> observing_ptr<T>::observing_ptr(T* obj) : m_object(obj) { if (m_object != nullptr) { m_object.load()->addObserver(*this); } } /// \brief Construct from reference /// /// \param obj Reference to the \p Observable that shall be tracked template <typename T> observing_ptr<T>::observing_ptr(T& obj) : m_object(&obj) { m_object.load()->addObserver(*this); } /// \brief Remove observing pointer /// /// Unregisters ourself from the pointed-to \p Observable template <typename T> observing_ptr<T>::~observing_ptr() { if (m_object != nullptr) { m_object.load()->removeObserver(*this); } } /// \brief Copy-construct from other observing_ptr /// /// \param other Reference to another \p observing_ptr that shall be copied template <typename T> observing_ptr<T>::observing_ptr(const observing_ptr<T>& other) : m_object(other.m_object.load()) { if (m_object != nullptr) { m_object.load()->addObserver(*this); } } /// \brief Copy-assign from other observing_ptr /// /// \param other Reference to another \p observing_ptr that shall be copied template <typename T> observing_ptr<T>& observing_ptr<T>::operator=(const observing_ptr<T>& other) { reset(other.m_object); return *this; } /// \brief Move-construct from another observing_ptr /// /// \param other rvalue reference to another \p observing_ptr that we shall take over template <typename T> observing_ptr<T>::observing_ptr(observing_ptr<T>&& other) noexcept : m_object(other.m_object.load()) { if (m_object != nullptr) { m_object.load()->moveObserver(other, *this); } other.m_object = nullptr; } /// \brief Move-assign from another observing_ptr /// /// \param other rvalue reference to another \p observing_ptr that we shall take over template <typename T> observing_ptr<T>& observing_ptr<T>::operator=(observing_ptr<T>&& other) noexcept { reset(); m_object = other.m_object.load(); if (m_object != nullptr) { m_object.load()->moveObserver(other, *this); } other.m_object = nullptr; return *this; } /// \brief Reset from pointer /// /// Sets the pointed-to object to \a obj and registers/unregisters ourself as an observer as needed. /// /// \param obj Pointer to the new \p Observable that shall be tracked template <typename T> void observing_ptr<T>::reset(T* obj) { if (obj != nullptr) { obj->addObserver(*this); } if (m_object != nullptr) { m_object.load()->removeObserver(*this); } m_object = obj; } /// \brief Reset from reference /// /// Sets the pointed-to object to \a obj and registers/unregisters ourself as an observer as needed. /// /// \param obj Reference to the new \p Observable that shall be tracked template <typename T> void observing_ptr<T>::reset(T& obj) { obj.addObserver(*this); if (m_object != nullptr) { m_object.load()->removeObserver(*this); } m_object = &obj; } /// \brief Access by raw pointer template <typename T> T* observing_ptr<T>::get() { return m_object.load(); } /// \brief Reference access template <typename T> T& observing_ptr<T>::operator*() { return *m_object.load(); } /// \brief Constant reference access template <typename T> const T& observing_ptr<T>::operator*() const { return *m_object.load(); } /// \brief Dereference operator template <typename T> T* observing_ptr<T>::operator->() { return m_object.load(); } /// \brief Const dereference operator template <typename T> const T* observing_ptr<T>::operator->() const { return m_object.load(); } /// \brief Cast to boolean value /// /// \return true if the object we're pointing to is still alive or false if it has been destroyed template <typename T> observing_ptr<T>::operator bool() const { return (m_object != nullptr); } template <typename T> void observing_ptr<T>::swap(observing_ptr<T>& other) noexcept { if (m_object != nullptr) { m_object.load()->moveObserver(*this, other); } if (other.m_object) { other.m_object.load()->moveObserver(other, *this); } std::swap(m_object, other.m_object); } /// \brief Comparison operator (equality) template <typename T> bool observing_ptr<T>::operator==(const observing_ptr<T>& other) const { return (m_object == other.m_object); } /// \brief Comparison operator (inequality) template <typename T> bool observing_ptr<T>::operator!=(const observing_ptr<T>& other) const { return (m_object != other.m_object); } template <typename T> void observing_ptr<T>::observable_destroyed(observable& o) { m_object = nullptr; } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * 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 * *****************************************************************************/ #ifndef MAPNIK_AGG_RASTERIZER_HPP #define MAPNIK_AGG_RASTERIZER_HPP // mapnik #include <mapnik/noncopyable.hpp> // agg #include "agg_rasterizer_scanline_aa.h" namespace mapnik { struct rasterizer : agg::rasterizer_scanline_aa<>, mapnik::noncopyable {}; } #endif // MAPNIK_AGG_RASTERIZER_HPP <commit_msg>avoid integer overflows in agg by using clamping in agg:iround with agg::rasterizer_sl_clip_int_sat - closes #2000<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * 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 * *****************************************************************************/ #ifndef MAPNIK_AGG_RASTERIZER_HPP #define MAPNIK_AGG_RASTERIZER_HPP // mapnik #include <mapnik/noncopyable.hpp> // agg #include "agg_rasterizer_scanline_aa.h" namespace mapnik { struct rasterizer : agg::rasterizer_scanline_aa<agg::rasterizer_sl_clip_int_sat>, mapnik::noncopyable {}; } #endif // MAPNIK_AGG_RASTERIZER_HPP <|endoftext|>
<commit_before>#pragma once #include <vector> template <typename MoeType> Moether<MoeType>::Moether() { distrib_char = std::uniform_int_distribution<unsigned int>(32, 255); } template <typename MoeType> Moether<MoeType>::~Moether() { } template <typename MoeType> void Moether<MoeType>::init( unsigned int _moesPerGen, unsigned int _eliteCopies, float _mutationRate, float _crossoverRate ) { m_moesPerGen = _moesPerGen; m_eliteCopies = _eliteCopies; m_mutationRate = _mutationRate; m_crossoverRate = _crossoverRate; } template <typename MoeType> void Moether<MoeType>::run( unsigned int _generations ) { m_generations = _generations; // Algorithm: // 1) Generate random population // for each generation // 2) Compute fitnesses // 3) Keep the best as "elite" // 4) put m_eliteCopies times elite in the new generation // 5) for each 2 free slots // 6) Choose 2 candidates from past generation // 7) Generate 2 offsprings with crossover // 8) Mutate offsprings // 9) Put the 2 offsprings in the new generation // 10) Set the new generation as actual // 11) Step 2 std::vector<MoeType> population( m_moesPerGen ); std::vector<double> fitnesses ( m_moesPerGen ); // 1) for(unsigned int i = 0; i < m_moesPerGen; i++) { population[i].setGenotype( randomizeGenotype() ); } for(unsigned int i = 0; i < m_generations; i++) { // 2) double max = 0.0, min = m_fitnessFunction(population[0]); unsigned int maxIndex = 0; for(unsigned int j = 0; j < m_moesPerGen; j++) { fitnesses[j] = m_fitnessFunction( population[j] ); population[j].setFitness( fitnesses[j] ); if(m_mode) { if(max < fitnesses[j]) { max = fitnesses[j]; maxIndex = j; } } else { if(min > fitnesses[j]) { min = fitnesses[j]; maxIndex = j; } } } // 3) m_bestMoe = population[maxIndex]; // 4) std::vector<MoeType> new_population( m_eliteCopies, m_bestMoe ); // 5) while(new_population.size() + 2 <= m_moesPerGen) { // 6) std::uniform_int_distribution<unsigned int> distrib_roulette(0, m_moesPerGen-1); unsigned int a = distrib_roulette( gen ), b = distrib_roulette( gen ); MoeType selected1 = population[ a ], selected2 = population[ b ]; // 7) // One Point, Two point and Uniform crossover done MoeType offspring1, offspring2; crossover(selected1, selected2, offspring1, offspring2); // 8) std::uniform_real_distribution<float> distrib_mutation(0.0f, 1.0f); if( distrib_mutation( gen ) <= m_mutationRate ) { mutate(offspring1); mutate(offspring2); } // 9) new_population.push_back( offspring1 ); new_population.push_back( offspring2 ); } // 10) population = new_population; } } template <typename MoeType> void Moether<MoeType>::setFitnessFunction( std::function<double( const MoeType&)> _fitnessFunction) { m_fitnessFunction = _fitnessFunction; } template <typename MoeType> void Moether<MoeType>::setFitnessMode(bool _mode) { m_mode = _mode; } template <typename MoeType> void Moether<MoeType>::setMaxGenotypeSize(unsigned int _size) { m_maxGenotypeSize = _size; } template <typename MoeType> void Moether<MoeType>::setCrossover(unsigned int _type) { m_crossover = _type; } template <typename MoeType> void Moether<MoeType>::setMutation(unsigned int _type) { m_mutation = _type; } template <typename MoeType> void Moether<MoeType>::setGenotypeAscii( unsigned int _a, unsigned int _b ) { distrib_char = std::uniform_int_distribution<unsigned int>(_a, _b); } template <typename MoeType> const MoeType& Moether<MoeType>::getBestMoe() const { return m_bestMoe; } template <typename MoeType> std::string Moether<MoeType>::randomizeGenotype() { std::string randomized = ""; for(unsigned int i = 0; i < m_maxGenotypeSize; i++) randomized += (unsigned char)distrib_char(gen); return randomized; } template <typename MoeType> void Moether<MoeType>::crossover( MoeType& _parent1, MoeType& _parent2, MoeType& _offspring1, MoeType& _offspring2 ) { std::string offspring1_genotype = _parent1.getGenotype(), offspring2_genotype = _parent2.getGenotype(); unsigned int min = std::min( offspring1_genotype.size(), offspring2_genotype.size() ); std::uniform_real_distribution<float> distrib_index; float indexCoef; switch( m_crossover ) { default: case moe::Crossover::NONE: // it does nothing, but NEEDED // in this case, _offspring1 becomes _parent1, same thing for _offspring2 break; case moe::Crossover::OnePoint: { distrib_index = std::uniform_real_distribution<float>(0.05f, 0.95f); indexCoef = distrib_index( gen ); unsigned int index = min * indexCoef; offspring1_genotype = offspring1_genotype.substr(0, index) + offspring2_genotype.substr(index, offspring2_genotype.size() - index); offspring2_genotype = offspring2_genotype.substr(0, index) + offspring1_genotype.substr(index, offspring1_genotype.size() - index); } break; case moe::Crossover::TwoPoint: { distrib_index = std::uniform_real_distribution<float>(0.05f, 0.45f); indexCoef = distrib_index( gen ); unsigned int index1 = min * indexCoef; distrib_index = std::uniform_real_distribution<float>(0.55f, 0.95f); indexCoef = distrib_index( gen ); unsigned int index2 = min * indexCoef; for(unsigned int i = index1; i < index2; i++) { char cs = offspring1_genotype[i]; offspring1_genotype[i] = offspring2_genotype[i]; offspring2_genotype[i] = cs; } } break; case moe::Crossover::Uniform: { distrib_index = std::uniform_real_distribution<float>(0.0f, 1.0f); for(unsigned int i = 0; i < min; i++) { float prob = distrib_index( gen ); if( prob <= m_crossoverRate ) { char cs = offspring1_genotype[i]; offspring1_genotype[i] = offspring2_genotype[i]; offspring2_genotype[i] = cs; } } } break; } _offspring1.setGenotype(offspring1_genotype); _offspring2.setGenotype(offspring2_genotype); } template <typename MoeType> void Moether<MoeType>::mutate(MoeType& _moe) { //TODO: assert to check m_mutation unsigned int choosenMutation; std::vector<unsigned int> available; if( m_mutation != moe::Mutation::NONE ) { if( m_mutation & moe::Mutation::Substitution ) available.push_back( moe::Mutation::Substitution ); if( m_mutation & moe::Mutation::Insertion ) available.push_back( moe::Mutation::Insertion ); if( m_mutation & moe::Mutation::Deletion ) available.push_back( moe::Mutation::Deletion ); if( m_mutation & moe::Mutation::Translocation ) available.push_back( moe::Mutation::Translocation ); std::uniform_int_distribution<unsigned int> dist_mutation(0, available.size()-1); choosenMutation = available[ dist_mutation( gen ) ]; } else choosenMutation = moe::Mutation::NONE; std::string moe_genotype = _moe.getGenotype(); std::uniform_int_distribution<unsigned int> dist_genotype(0, moe_genotype.size()-1); switch( choosenMutation ) { default: case moe::Mutation::NONE: { // needed } break; case moe::Mutation::Substitution: { char mutation = (unsigned char)distrib_char( gen ); moe_genotype[ dist_genotype(gen) ] = mutation; } break; case moe::Mutation::Insertion: { char mutation = (unsigned char)distrib_char( gen ); moe_genotype.insert( moe_genotype.begin()+dist_genotype(gen), mutation ); } break; case moe::Mutation::Deletion: { if(moe_genotype.size() > 2) { moe_genotype.erase( moe_genotype.begin()+ dist_genotype(gen) ); } } break; case moe::Mutation::Translocation: { unsigned int a = dist_genotype(gen), b = dist_genotype(gen); char tmp = moe_genotype[a]; moe_genotype[a] = moe_genotype[b]; moe_genotype[b] = tmp; } break; } _moe.setGenotype( moe_genotype ); }<commit_msg>Fixed segfault<commit_after>#pragma once #include <vector> template <typename MoeType> Moether<MoeType>::Moether() { distrib_char = std::uniform_int_distribution<unsigned int>(32, 255); } template <typename MoeType> Moether<MoeType>::~Moether() { } template <typename MoeType> void Moether<MoeType>::init( unsigned int _moesPerGen, unsigned int _eliteCopies, float _mutationRate, float _crossoverRate ) { m_moesPerGen = _moesPerGen; m_eliteCopies = _eliteCopies; m_mutationRate = _mutationRate; m_crossoverRate = _crossoverRate; if(m_eliteCopies & 1) m_eliteCopies += 1; } template <typename MoeType> void Moether<MoeType>::run( unsigned int _generations ) { m_generations = _generations; std::vector<MoeType> population( m_moesPerGen ); std::vector<double> fitnesses ( m_moesPerGen ); // 1) Generate random population for(unsigned int i = 0; i < m_moesPerGen; i++) { population[i].setGenotype( randomizeGenotype() ); } for(unsigned int i = 0; i < m_generations; i++) { // 2) Compute fitnesses double max = 0.0, min = m_fitnessFunction(population[0]); unsigned int maxIndex = 0; for(unsigned int j = 0; j < m_moesPerGen; j++) { fitnesses[j] = m_fitnessFunction( population[j] ); population[j].setFitness( fitnesses[j] ); if(m_mode) { if(max < fitnesses[j]) { max = fitnesses[j]; maxIndex = j; } } else { if(min > fitnesses[j]) { min = fitnesses[j]; maxIndex = j; } } } // 3) keep the best as "elite" m_bestMoe = population[maxIndex]; // 4) put m_eliteCopies times elite in the new generation std::vector<MoeType> new_population( m_eliteCopies, m_bestMoe ); // 5) for each 2 free slots while(new_population.size() + 2 <= m_moesPerGen) { // 6) Choose 2 candidates from past generation std::uniform_int_distribution<unsigned int> distrib_roulette(0, m_moesPerGen-1); unsigned int a = distrib_roulette( gen ), b = distrib_roulette( gen ); MoeType selected1 = population[ a ], selected2 = population[ b ]; // 7) Generate 2 offsprings with crossover MoeType offspring1, offspring2; crossover(selected1, selected2, offspring1, offspring2); // 8) Mutate offsprings std::bernoulli_distribution distrib_mutation( m_mutationRate ); if( distrib_mutation( gen ) ) { mutate(offspring1); mutate(offspring2); } // 9) Put the 2 offsprings in the new generation new_population.push_back( offspring1 ); new_population.push_back( offspring2 ); } // 10) Set the new generation as actual population = new_population; } } template <typename MoeType> void Moether<MoeType>::setFitnessFunction( std::function<double( const MoeType&)> _fitnessFunction) { m_fitnessFunction = _fitnessFunction; } template <typename MoeType> void Moether<MoeType>::setFitnessMode(bool _mode) { m_mode = _mode; } template <typename MoeType> void Moether<MoeType>::setMaxGenotypeSize(unsigned int _size) { m_maxGenotypeSize = _size; } template <typename MoeType> void Moether<MoeType>::setCrossover(unsigned int _type) { m_crossover = _type; } template <typename MoeType> void Moether<MoeType>::setMutation(unsigned int _type) { m_mutation = _type; } template <typename MoeType> void Moether<MoeType>::setGenotypeAscii( unsigned int _a, unsigned int _b ) { distrib_char = std::uniform_int_distribution<unsigned int>(_a, _b); } template <typename MoeType> const MoeType& Moether<MoeType>::getBestMoe() const { return m_bestMoe; } template <typename MoeType> std::string Moether<MoeType>::randomizeGenotype() { std::string randomized = ""; for(unsigned int i = 0; i < m_maxGenotypeSize; i++) randomized += (unsigned char)distrib_char(gen); return randomized; } template <typename MoeType> void Moether<MoeType>::crossover( MoeType& _parent1, MoeType& _parent2, MoeType& _offspring1, MoeType& _offspring2 ) { std::string offspring1_genotype = _parent1.getGenotype(), offspring2_genotype = _parent2.getGenotype(); unsigned int min = std::min( offspring1_genotype.size(), offspring2_genotype.size() ); std::uniform_real_distribution<float> distrib_index; float indexCoef; switch( m_crossover ) { default: case moe::Crossover::NONE: // it does nothing, but NEEDED // in this case, _offspring1 becomes _parent1, same thing for _offspring2 break; case moe::Crossover::OnePoint: { distrib_index = std::uniform_real_distribution<float>(0.05f, 0.95f); indexCoef = distrib_index( gen ); unsigned int index = min * indexCoef; offspring1_genotype = offspring1_genotype.substr(0, index) + offspring2_genotype.substr(index, offspring2_genotype.size() - index); offspring2_genotype = offspring2_genotype.substr(0, index) + offspring1_genotype.substr(index, offspring1_genotype.size() - index); } break; case moe::Crossover::TwoPoint: { distrib_index = std::uniform_real_distribution<float>(0.05f, 0.45f); indexCoef = distrib_index( gen ); unsigned int index1 = min * indexCoef; distrib_index = std::uniform_real_distribution<float>(0.55f, 0.95f); indexCoef = distrib_index( gen ); unsigned int index2 = min * indexCoef; for(unsigned int i = index1; i < index2; i++) { char cs = offspring1_genotype[i]; offspring1_genotype[i] = offspring2_genotype[i]; offspring2_genotype[i] = cs; } } break; case moe::Crossover::Uniform: { std::bernoulli_distribution distrib_uniform = std::bernoulli_distribution( m_crossoverRate ); for(unsigned int i = 0; i < min; i++) { if( distrib_uniform( gen ) ) { char cs = offspring1_genotype[i]; offspring1_genotype[i] = offspring2_genotype[i]; offspring2_genotype[i] = cs; } } } break; } _offspring1.setGenotype(offspring1_genotype); _offspring2.setGenotype(offspring2_genotype); } template <typename MoeType> void Moether<MoeType>::mutate(MoeType& _moe) { //TODO: assert to check m_mutation unsigned int choosenMutation; std::vector<unsigned int> available; if( m_mutation != moe::Mutation::NONE ) { if( m_mutation & moe::Mutation::Substitution ) available.push_back( moe::Mutation::Substitution ); if( m_mutation & moe::Mutation::Insertion ) available.push_back( moe::Mutation::Insertion ); if( m_mutation & moe::Mutation::Deletion ) available.push_back( moe::Mutation::Deletion ); if( m_mutation & moe::Mutation::Translocation ) available.push_back( moe::Mutation::Translocation ); std::uniform_int_distribution<unsigned int> dist_mutation(0, available.size()-1); choosenMutation = available[ dist_mutation( gen ) ]; } else choosenMutation = moe::Mutation::NONE; std::string moe_genotype = _moe.getGenotype(); std::uniform_int_distribution<unsigned int> dist_genotype(0, moe_genotype.size()-1); switch( choosenMutation ) { default: case moe::Mutation::NONE: { // needed } break; case moe::Mutation::Substitution: { char mutation = (unsigned char)distrib_char( gen ); moe_genotype[ dist_genotype(gen) ] = mutation; } break; case moe::Mutation::Insertion: { char mutation = (unsigned char)distrib_char( gen ); moe_genotype.insert( moe_genotype.begin()+dist_genotype(gen), mutation ); } break; case moe::Mutation::Deletion: { if(moe_genotype.size() > 2) { moe_genotype.erase( moe_genotype.begin()+ dist_genotype(gen) ); } } break; case moe::Mutation::Translocation: { unsigned int a = dist_genotype(gen), b = dist_genotype(gen); char tmp = moe_genotype[a]; moe_genotype[a] = moe_genotype[b]; moe_genotype[b] = tmp; } break; } _moe.setGenotype( moe_genotype ); }<|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_CAMERA_HPP #define RJ_GAME_CAMERA_HPP #include <rectojump/core/game_window.hpp> namespace rj { class camera { game_window& m_gamewindow; sf::RenderWindow& m_renderwindow; const sf::View& m_default_window_view{m_renderwindow.getDefaultView()}; sf::View m_userview; vec2f m_startcenter; float m_reset_zoomfactor{1.f}; public: camera(game_window& gw, const sf::View& v = {}, const sf::FloatRect& viewport = {0.f, 0.f, 1.f, 1.f}) : m_gamewindow{gw}, m_renderwindow{m_gamewindow.get_renderwindow()}, m_userview{v}, m_startcenter{m_userview.getCenter()} {m_userview.setViewport(viewport);} void update(dur duration) { } void move(const vec2f& offset) noexcept {m_userview.move(offset);} void zoom(float factor) noexcept {m_userview.zoom(factor); m_reset_zoomfactor *= factor;} void reset_zoom() noexcept {m_userview.zoom(1.f / m_reset_zoomfactor); m_reset_zoomfactor = 1.f;} void activate() noexcept {m_gamewindow.set_view(m_userview);} void set_center(const vec2f& center) noexcept {m_userview.setCenter(center);} void set_view(const sf::View& v) noexcept {m_userview = v; m_startcenter = m_userview.getCenter();} bool is_centered() const noexcept {return m_userview.getCenter() == m_startcenter;} bool has_moved_left() const noexcept {return m_userview.getCenter().x > m_startcenter.x;} bool has_moved_right() const noexcept {return m_userview.getCenter().x < m_startcenter.x;} const vec2f& get_center() noexcept {return m_userview.getCenter();} const vec2f& get_startcenter() const noexcept {return m_startcenter;} const sf::View& get_view() const noexcept {return m_userview;} vec2f get_mapped_mousepos() const noexcept {return get_mousepos(m_renderwindow, m_userview);} float get_zoomfactor() const noexcept {return m_reset_zoomfactor;} }; } #endif // RJ_GAME_CAMERA_HPP <commit_msg>camera: added reset_center()<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_CAMERA_HPP #define RJ_GAME_CAMERA_HPP #include <rectojump/core/game_window.hpp> namespace rj { class camera { game_window& m_gamewindow; sf::RenderWindow& m_renderwindow; const sf::View& m_default_window_view{m_renderwindow.getDefaultView()}; sf::View m_userview; vec2f m_startcenter; float m_reset_zoomfactor{1.f}; public: camera(game_window& gw, const sf::View& v = {}, const sf::FloatRect& viewport = {0.f, 0.f, 1.f, 1.f}) : m_gamewindow{gw}, m_renderwindow{m_gamewindow.get_renderwindow()}, m_userview{v}, m_startcenter{m_userview.getCenter()} {m_userview.setViewport(viewport);} void update(dur duration) { } void move(const vec2f& offset) noexcept {m_userview.move(offset);} void zoom(float factor) noexcept {m_userview.zoom(factor); m_reset_zoomfactor *= factor;} void reset_center() noexcept {m_userview.setCenter(m_startcenter);} void reset_zoom() noexcept {m_userview.zoom(1.f / m_reset_zoomfactor); m_reset_zoomfactor = 1.f;} void activate() noexcept {m_gamewindow.set_view(m_userview);} void set_center(const vec2f& center) noexcept {m_userview.setCenter(center);} void set_view(const sf::View& v) noexcept {m_userview = v; m_startcenter = m_userview.getCenter();} bool is_centered() const noexcept {return m_userview.getCenter() == m_startcenter;} bool has_moved_left() const noexcept {return m_userview.getCenter().x > m_startcenter.x;} bool has_moved_right() const noexcept {return m_userview.getCenter().x < m_startcenter.x;} const vec2f& get_center() noexcept {return m_userview.getCenter();} const vec2f& get_startcenter() const noexcept {return m_startcenter;} const sf::View& get_view() const noexcept {return m_userview;} vec2f get_mapped_mousepos() const noexcept {return get_mousepos(m_renderwindow, m_userview);} float get_zoomfactor() const noexcept {return m_reset_zoomfactor;} }; } #endif // RJ_GAME_CAMERA_HPP <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_CAMERA_HPP #define RJ_GAME_CAMERA_HPP #include <rectojump/core/game_window.hpp> namespace rj { class camera { game_window& m_gamewindow; sf::RenderWindow& m_renderwindow; const sf::View& m_default_window_view{m_renderwindow.getDefaultView()}; sf::View m_userview; vec2f m_startcenter; public: camera(game_window& gw, const sf::View& v = {}) : m_gamewindow{gw}, m_renderwindow{m_gamewindow.get_renderwindow()}, m_userview{v}, m_startcenter{m_userview.getCenter()} { } void update(dur duration) { } void move(const vec2f& offset) noexcept {m_userview.move(offset);} void zoom(float factor) noexcept {m_userview.zoom(factor);} void set_changes() noexcept { m_gamewindow.set_view(m_userview); } void set_view(const sf::View& v) noexcept {m_userview = v; m_startcenter = m_userview.getCenter();} bool is_centered() const noexcept {return m_userview.getCenter() == m_startcenter;} bool has_moved_left() const noexcept {return m_userview.getCenter().x > m_startcenter.x;} bool has_moved_right() const noexcept {return m_userview.getCenter().x < m_startcenter.x;} const vec2f& get_center() noexcept {return m_userview.getCenter();} const sf::View& get_view() const noexcept {return m_userview;} vec2f get_mapped_mousepos() const noexcept {return get_mousepos(m_renderwindow, m_userview);} }; } #endif // RJ_GAME_CAMERA_HPP <commit_msg>camera: taking viewport<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GAME_CAMERA_HPP #define RJ_GAME_CAMERA_HPP #include <rectojump/core/game_window.hpp> namespace rj { class camera { game_window& m_gamewindow; sf::RenderWindow& m_renderwindow; const sf::View& m_default_window_view{m_renderwindow.getDefaultView()}; sf::View m_userview; vec2f m_startcenter; public: camera(game_window& gw, const sf::View& v = {}, const sf::FloatRect& viewport = {0.f, 0.f, 1.f, 1.f}) : m_gamewindow{gw}, m_renderwindow{m_gamewindow.get_renderwindow()}, m_userview{v}, m_startcenter{m_userview.getCenter()} {m_userview.setViewport(viewport);} void update(dur duration) { } void move(const vec2f& offset) noexcept {m_userview.move(offset);} void zoom(float factor) noexcept {m_userview.zoom(factor);} void set_changes() noexcept { m_gamewindow.set_view(m_userview); } void set_view(const sf::View& v) noexcept {m_userview = v; m_startcenter = m_userview.getCenter();} bool is_centered() const noexcept {return m_userview.getCenter() == m_startcenter;} bool has_moved_left() const noexcept {return m_userview.getCenter().x > m_startcenter.x;} bool has_moved_right() const noexcept {return m_userview.getCenter().x < m_startcenter.x;} const vec2f& get_center() noexcept {return m_userview.getCenter();} const vec2f& get_startcenter() const noexcept {return m_startcenter;} const sf::View& get_view() const noexcept {return m_userview;} vec2f get_mapped_mousepos() const noexcept {return get_mousepos(m_renderwindow, m_userview);} }; } #endif // RJ_GAME_CAMERA_HPP <|endoftext|>
<commit_before>// This file is a part of Simdee, see homepage at http://github.com/tufak/simdee // This file is distributed under the MIT license. #ifndef SIMDEE_UTIL_MALLOC_HPP #define SIMDEE_UTIL_MALLOC_HPP #include <type_traits> #include <exception> #include <cstdlib> #include <cstdint> #include "noexcept.hpp" namespace sd { namespace detail { #if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803) // type_traits is buggered in libstdc++ up until GCC 5 template <typename T> using is_trivially_default_constructible = std::has_trivial_default_constructor<T>; #else template <typename T> using is_trivially_default_constructible = std::is_trivially_default_constructible<T>; #endif inline constexpr bool is_pow2(std::size_t x) { return x && (x & (x - 1)) == 0; } } template <typename T, std::size_t Align = alignof(T)> T* aligned_malloc(std::size_t bytes) { static_assert(detail::is_pow2(Align), "alignment must be a power of 2"); auto size = bytes + sizeof(void*) + Align - 1; auto orig = std::malloc(size); if (orig == nullptr) return nullptr; auto aligned = reinterpret_cast<T*>((reinterpret_cast<std::uintptr_t>(orig) + sizeof(void*) + Align - 1) & ~(Align - 1)); reinterpret_cast<void**>(aligned)[-1] = orig; // save orig right before the start of user data return aligned; } template <typename T> void aligned_free(T* aligned) { if (aligned == nullptr) return; auto orig = reinterpret_cast<void**>(aligned)[-1]; // restore orig from right before the start of user data std::free(orig); } struct aligned_deleter { template <typename T> void operator()(T* ptr) { sd::aligned_free(ptr); } }; template <typename T, std::size_t Align = alignof(T)> struct aligned_allocator { using value_type = T; aligned_allocator() = default; template <typename S> aligned_allocator(const aligned_allocator<S, Align>&) {} T* allocate(std::size_t count) const SIMDEE_NOEXCEPT { return sd::aligned_malloc<T, Align>(sizeof(T) * count); } void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT { sd::aligned_free(ptr); } void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) { if (!std::is_trivially_destructible<T>::value) { ptr->~T(); } else { no_op(ptr); // just to suppress MSVC warning "ptr not referenced" } } static void no_op(T*) {} void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) { if (!detail::is_trivially_default_constructible<T>::value) { new (ptr)T; } } template <typename A1, typename... A> void construct(T* ptr, A1&& a1, A&&... a2) const { new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...); } // default rebind should do just this, doesn't seem to work in MSVC though template <typename S> struct rebind { using other = aligned_allocator<S, Align>; }; }; template <typename T, typename U, std::size_t TS, std::size_t US> bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; } template <typename T, typename U, std::size_t TS, std::size_t US> bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; } } #endif // SIMDEE_UTIL_MALLOC_HPP <commit_msg>Rewrite aligned_malloc, aligned_free #7<commit_after>// This file is a part of Simdee, see homepage at http://github.com/tufak/simdee // This file is distributed under the MIT license. #ifndef SIMDEE_UTIL_MALLOC_HPP #define SIMDEE_UTIL_MALLOC_HPP #include <type_traits> #include <exception> #include <cstdlib> #include <cstdint> #include "noexcept.hpp" namespace sd { namespace detail { #if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803) // type_traits is buggered in libstdc++ up until GCC 5 template <typename T> using is_trivially_default_constructible = std::has_trivial_default_constructor<T>; #else template <typename T> using is_trivially_default_constructible = std::is_trivially_default_constructible<T>; #endif inline constexpr bool is_pow2(std::size_t x) { return x && (x & (x - 1)) == 0; } } template <typename T, std::size_t Align = alignof(T)> T* aligned_malloc(std::size_t bytes) { static_assert(detail::is_pow2(Align), "alignment must be a power of 2"); static_assert(Align <= 128, "alignment is too large"); auto orig = (uintptr_t)std::malloc(bytes + Align); if (orig == 0) return nullptr; auto aligned = (orig + Align) & ~(Align - 1); auto offset = int8_t(orig - aligned); ((int8_t*)aligned)[-1] = offset; return (T*)aligned; } template <typename T> void aligned_free(T* aligned) { if (aligned == nullptr) return; auto offset = ((int8_t*)aligned)[-1]; auto orig = uintptr_t(aligned) + offset; std::free((void*)orig); } struct aligned_deleter { template <typename T> void operator()(T* ptr) { sd::aligned_free(ptr); } }; template <typename T, std::size_t Align = alignof(T)> struct aligned_allocator { using value_type = T; aligned_allocator() = default; template <typename S> aligned_allocator(const aligned_allocator<S, Align>&) {} T* allocate(std::size_t count) const SIMDEE_NOEXCEPT { return sd::aligned_malloc<T, Align>(sizeof(T) * count); } void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT { sd::aligned_free(ptr); } void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) { if (!std::is_trivially_destructible<T>::value) { ptr->~T(); } else { no_op(ptr); // just to suppress MSVC warning "ptr not referenced" } } static void no_op(T*) {} void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) { if (!detail::is_trivially_default_constructible<T>::value) { new (ptr)T; } } template <typename A1, typename... A> void construct(T* ptr, A1&& a1, A&&... a2) const { new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...); } // default rebind should do just this, doesn't seem to work in MSVC though template <typename S> struct rebind { using other = aligned_allocator<S, Align>; }; }; template <typename T, typename U, std::size_t TS, std::size_t US> bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; } template <typename T, typename U, std::size_t TS, std::size_t US> bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; } } #endif // SIMDEE_UTIL_MALLOC_HPP <|endoftext|>
<commit_before>// Copyright (c) 2021 Daniel Deptford // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_PEG_HPP #define TAO_PEGTL_CONTRIB_PEG_HPP #include <tao/pegtl.hpp> namespace TAO_PEGTL_NAMESPACE { namespace peg { // PEG grammar from https://pdos.csail.mit.edu/~baford/packrat/popl04/peg-popl04.pdf namespace grammar { // clang-format off struct AND; struct Char; struct Class; struct CLOSE; struct Comment; struct Definition; struct DOT; struct EndOfFile; struct EndOfLine; struct Expression; struct QUESTION; struct IdentCont; struct Identifier; struct IdentStart; struct LEFTARROW; struct Literal; struct NOT; struct OPEN; struct PLUS; struct Prefix; struct Primary; struct Range; struct Sequence; struct SLASH; struct Space; struct Spacing; struct STAR; struct Suffix; struct Grammar : tao::pegtl::seq<Spacing, tao::pegtl::plus<Definition>, EndOfFile> {}; struct Definition : tao::pegtl::seq<Identifier, LEFTARROW, Expression> {}; struct Expression : tao::pegtl::seq< Sequence, tao::pegtl::star< tao::pegtl::seq< SLASH, Sequence > > > {}; struct Sequence : tao::pegtl::star<Prefix> {}; struct Prefix : tao::pegtl::seq< tao::pegtl::opt< tao::pegtl::sor< AND, NOT > >, Suffix > {}; struct Suffix : tao::pegtl::seq< Primary, tao::pegtl::opt< tao::pegtl::sor< QUESTION, STAR, PLUS > > > {}; struct Primary : tao::pegtl::sor< tao::pegtl::seq<Identifier, tao::pegtl::not_at<LEFTARROW> >, tao::pegtl::seq<OPEN, Expression, CLOSE>, Literal, Class, DOT> {}; struct Identifier : tao::pegtl::seq<IdentStart, tao::pegtl::star<IdentCont>, Spacing> {}; struct IdentStart : tao::pegtl::ranges< 'a', 'z', 'A', 'Z', '_' > {}; struct IdentCont : tao::pegtl::sor< IdentStart, tao::pegtl::range<'0','9'> > {}; struct Literal : tao::pegtl::sor< tao::pegtl::seq< tao::pegtl::one<'\''>, tao::pegtl::star< tao::pegtl::seq< tao::pegtl::not_at< tao::pegtl::one<'\''> >, Char > >, tao::pegtl::one<'\''>, Spacing >, tao::pegtl::seq< tao::pegtl::one<'\"'>, tao::pegtl::star< tao::pegtl::seq< tao::pegtl::not_at<tao::pegtl::one<'\"'> >, Char > >, tao::pegtl::one<'\"'>, Spacing > > {}; struct Class : tao::pegtl::seq< tao::pegtl::one<'['>, tao::pegtl::star< tao::pegtl::seq< tao::pegtl::not_at<tao::pegtl::one<']'> >, Range > >, tao::pegtl::one<']'>, Spacing > {}; struct Range : tao::pegtl::sor< tao::pegtl::seq< Char, tao::pegtl::one<'-'>, Char>, Char > {}; struct Char : tao::pegtl::sor< tao::pegtl::seq< tao::pegtl::one<'\\'>, tao::pegtl::one<'n','r','t','\'','\"','[',']','\\'> >, tao::pegtl::seq< tao::pegtl::one<'\\'>, tao::pegtl::range<'0','2'>, tao::pegtl::range<'0','7'>, tao::pegtl::range<'0','7'> >, tao::pegtl::seq< tao::pegtl::one<'\\'>, tao::pegtl::range<'0','7'>, tao::pegtl::opt<tao::pegtl::range<'0','7'> > >, tao::pegtl::seq< tao::pegtl::not_at<tao::pegtl::one<'\\'> >, tao::pegtl::any> > {}; struct LEFTARROW : tao::pegtl::seq<tao::pegtl::string<'<','-'>, Spacing> {}; struct SLASH : tao::pegtl::seq<tao::pegtl::one<'/'>, Spacing> {}; struct AND : tao::pegtl::seq<tao::pegtl::one<'&'>, Spacing> {}; struct NOT : tao::pegtl::seq<tao::pegtl::one<'!'>, Spacing> {}; struct QUESTION : tao::pegtl::seq<tao::pegtl::one<'?'>, Spacing> {}; struct STAR : tao::pegtl::seq<tao::pegtl::one<'*'>, Spacing> {}; struct PLUS : tao::pegtl::seq<tao::pegtl::one<'+'>, Spacing> {}; struct OPEN : tao::pegtl::seq<tao::pegtl::one<'('>, Spacing> {}; struct CLOSE : tao::pegtl::seq<tao::pegtl::one<')'>, Spacing> {}; struct DOT : tao::pegtl::seq<tao::pegtl::one<'.'>, Spacing> {}; struct Spacing : tao::pegtl::star<tao::pegtl::sor<Space, Comment> > {}; struct Comment : tao::pegtl::seq< tao::pegtl::one<'#'>, tao::pegtl::star< tao::pegtl::seq< tao::pegtl::not_at<EndOfLine>, tao::pegtl::any > >, EndOfLine > {}; struct Space : tao::pegtl::sor<tao::pegtl::one<' '>, tao::pegtl::one<'\t'>, EndOfLine> {}; struct EndOfLine : tao::pegtl::sor<tao::pegtl::string<'\r','\n'>, tao::pegtl::one<'\n'>, tao::pegtl::one<'\r'> > {}; struct EndOfFile : tao::pegtl::eof {}; // clang-format on } // namespace grammar } // namespace peg } // namespace TAO_PEGTL_NAMESPACE #endif // TAO_PEGTL_CONTRIB_PEG_HPP <commit_msg>Some fixes, simplifications<commit_after>// Copyright (c) 2021 Daniel Deptford // Copyright (c) 2021 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_PEG_HPP #define TAO_PEGTL_CONTRIB_PEG_HPP #include <tao/pegtl.hpp> namespace TAO_PEGTL_NAMESPACE { namespace peg { // PEG grammar from https://pdos.csail.mit.edu/~baford/packrat/popl04/peg-popl04.pdf namespace grammar { // clang-format off struct AND; struct Char; struct Class; struct CLOSE; struct Comment; struct Definition; struct DOT; struct EndOfFile; struct EndOfLine; struct Expression; struct QUESTION; struct IdentCont; struct Identifier; struct IdentStart; struct LEFTARROW; struct Literal; struct NOT; struct OPEN; struct PLUS; struct Prefix; struct Primary; struct Range; struct Sequence; struct SLASH; struct Space; struct Spacing; struct STAR; struct Suffix; struct Grammar : seq< Spacing, plus< Definition >, EndOfFile > {}; struct Definition : seq< Identifier, LEFTARROW, Expression > {}; struct Expression : list< Sequence, SLASH > {}; struct Sequence : star< Prefix > {}; struct Prefix : seq< opt< sor< AND, NOT > >, Suffix > {}; struct Suffix : seq< Primary, opt< sor< QUESTION, STAR, PLUS > > > {}; struct Primary : sor< seq< Identifier, not_at< LEFTARROW > >, seq< OPEN, Expression, CLOSE >, Literal, Class, DOT > {}; struct Identifier : seq< IdentStart, star< IdentCont >, Spacing > {}; struct IdentStart : identifier_first {}; struct IdentCont : identifier_other {}; struct Literal : sor< seq< one< '\'' >, until< one< '\'' >, Char >, Spacing >, seq< one< '"' >, until< one< '"' >, Char >, Spacing > > {}; struct Class : seq< one< '[' >, until< one< ']' >, Range >, Spacing > {}; struct Range : sor< seq< Char, one< '-' >, Char >, Char > {}; struct Char : sor< seq< one< '\\' >, one< 'n', 'r', 't', '\'', '"', '[', ']', '\\' > >, seq< one< '\\' >, range< '0', '2' >, range< '0', '7' >, range< '0', '7' > >, seq< one< '\\' >, range< '0','7' >, opt< range< '0','7' > > >, seq< not_at< one< '\\' > >, any > > {}; struct LEFTARROW : seq< string< '<','-' >, Spacing > {}; struct SLASH : seq< one< '/' >, Spacing > {}; struct AND : seq< one< '&' >, Spacing > {}; struct NOT : seq< one< '!' >, Spacing > {}; struct QUESTION : seq< one< '?' >, Spacing > {}; struct STAR : seq< one< '*' >, Spacing > {}; struct PLUS : seq< one< '+' >, Spacing > {}; struct OPEN : seq< one< '(' >, Spacing > {}; struct CLOSE : seq< one< ')' >, Spacing > {}; struct DOT : seq< one< '.' >, Spacing > {}; struct Spacing : star< sor< Space, Comment > > {}; struct Comment : seq< one< '#' >, until< EndOfLine > > {}; struct Space : sor< one< ' ', '\t' >, EndOfLine > {}; struct EndOfLine : sor< string< '\r', '\n' >, one< '\n' >, one< '\r' > > {}; struct EndOfFile : eof {}; // clang-format on } // namespace grammar } // namespace peg } // namespace TAO_PEGTL_NAMESPACE #endif // TAO_PEGTL_CONTRIB_PEG_HPP <|endoftext|>
<commit_before>// The Art of C++ / Sequences // Copyright (c) 2015 Daniel Frey #ifndef TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #define TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #include <cstddef> #include <type_traits> namespace tao { namespace seq { namespace impl { // This is not very elegant, but it works and has O(log N) instantiation depth template< std::size_t, typename, typename... > struct type_by_index; template< typename T, typename... Ts > struct type_by_index< 0, void, T, Ts... > { using type = T; }; template< std::size_t I, typename T0, typename... Ts> struct type_by_index< I, typename std::enable_if< ( I == 1 ) >::type, T0, Ts... > : type_by_index< I - 1, void, Ts... > {}; template< std::size_t I, typename T0, typename T1, typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 2 ) && ( I < 4 ) ) >::type, T0, T1, Ts... > : type_by_index< I - 2, void, Ts... > {}; template< std::size_t I, typename T0, typename T1, typename T2, typename T3, typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 4 ) && ( I < 8 ) ) >::type, T0, T1, T2, T3, Ts... > : type_by_index< I - 4, void, Ts... > {}; template< std::size_t I, typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 8 ) && ( I < 16 ) ) >::type, T0, T1, T2, T3, T4, T5, T6, T7, Ts... > : type_by_index< I - 8, void, Ts... > {}; #define TAOCPP_HEXPAND(X) X##0, X##1, X##2, X##3, X##4, X##5, X##6, X##7, X##8, X##9, X##a, X##b, X##c, X##d, X##e, X##f template< std::size_t I, TAOCPP_HEXPAND(typename T0), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 16 ) && ( I < 32 ) ) >::type, TAOCPP_HEXPAND(T0), Ts... > : type_by_index< I - 16, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND(typename T0), TAOCPP_HEXPAND(typename T1), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 32 ) && ( I < 64 ) ) >::type, TAOCPP_HEXPAND(T0), TAOCPP_HEXPAND(T1), Ts... > : type_by_index< I - 32, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND(typename T0), TAOCPP_HEXPAND(typename T1), TAOCPP_HEXPAND(typename T2), TAOCPP_HEXPAND(typename T3), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 64 ) && ( I < 128 ) ) >::type, TAOCPP_HEXPAND(T0), TAOCPP_HEXPAND(T1), TAOCPP_HEXPAND(T2), TAOCPP_HEXPAND(T3), Ts... > : type_by_index< I - 64, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND(typename T0), TAOCPP_HEXPAND(typename T1), TAOCPP_HEXPAND(typename T2), TAOCPP_HEXPAND(typename T3), TAOCPP_HEXPAND(typename T4), TAOCPP_HEXPAND(typename T5), TAOCPP_HEXPAND(typename T6), TAOCPP_HEXPAND(typename T7), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 128 ) && ( I < 256 ) ) >::type, TAOCPP_HEXPAND(T0), TAOCPP_HEXPAND(T1), TAOCPP_HEXPAND(T2), TAOCPP_HEXPAND(T3), TAOCPP_HEXPAND(T4), TAOCPP_HEXPAND(T5), TAOCPP_HEXPAND(T6), TAOCPP_HEXPAND(T7), Ts... > : type_by_index< I - 128, void, Ts... > {}; #define TAOCPP_HEXPAND2(X) TAOCPP_HEXPAND(X) template< std::size_t I, TAOCPP_HEXPAND2(typename T0), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 256 ) && ( I < 512 ) ) >::type, TAOCPP_HEXPAND2(T0), Ts... > : type_by_index< I - 256, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND2(typename T0), TAOCPP_HEXPAND2(typename T1), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 512 ) && ( I < 1024 ) ) >::type, TAOCPP_HEXPAND2(T0), TAOCPP_HEXPAND2(T1), Ts... > : type_by_index< I - 512, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND2(typename T0), TAOCPP_HEXPAND2(typename T1), TAOCPP_HEXPAND2(typename T2), TAOCPP_HEXPAND2(typename T3), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 1024 ) && ( I < 2048 ) ) >::type, TAOCPP_HEXPAND2(T0), TAOCPP_HEXPAND2(T1), TAOCPP_HEXPAND2(T2), TAOCPP_HEXPAND2(T3), Ts... > : type_by_index< I - 1024, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND2(typename T0), TAOCPP_HEXPAND2(typename T1), TAOCPP_HEXPAND2(typename T2), TAOCPP_HEXPAND2(typename T3), TAOCPP_HEXPAND2(typename T4), TAOCPP_HEXPAND2(typename T5), TAOCPP_HEXPAND2(typename T6), TAOCPP_HEXPAND2(typename T7), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 2048 ) && ( I < 4096 ) ) >::type, TAOCPP_HEXPAND2(T0), TAOCPP_HEXPAND2(T1), TAOCPP_HEXPAND2(T2), TAOCPP_HEXPAND2(T3), TAOCPP_HEXPAND2(T4), TAOCPP_HEXPAND2(T5), TAOCPP_HEXPAND2(T6), TAOCPP_HEXPAND2(T7), Ts... > : type_by_index< I - 2048, void, Ts... > {}; #define TAOCPP_HEXPAND3(X) TAOCPP_HEXPAND2(X) template< std::size_t I, TAOCPP_HEXPAND3(typename T0), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x1000 ) && ( I < 0x2000 ) ) >::type, TAOCPP_HEXPAND3(T0), Ts... > : type_by_index< I - 0x1000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND3(typename T0), TAOCPP_HEXPAND3(typename T1), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x2000 ) && ( I < 0x4000 ) ) >::type, TAOCPP_HEXPAND3(T0), TAOCPP_HEXPAND3(T1), Ts... > : type_by_index< I - 0x2000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND3(typename T0), TAOCPP_HEXPAND3(typename T1), TAOCPP_HEXPAND3(typename T2), TAOCPP_HEXPAND3(typename T3), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x4000 ) && ( I < 0x8000 ) ) >::type, TAOCPP_HEXPAND3(T0), TAOCPP_HEXPAND3(T1), TAOCPP_HEXPAND3(T2), TAOCPP_HEXPAND3(T3), Ts... > : type_by_index< I - 0x4000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND3(typename T0), TAOCPP_HEXPAND3(typename T1), TAOCPP_HEXPAND3(typename T2), TAOCPP_HEXPAND3(typename T3), TAOCPP_HEXPAND3(typename T4), TAOCPP_HEXPAND3(typename T5), TAOCPP_HEXPAND3(typename T6), TAOCPP_HEXPAND3(typename T7), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x8000 ) && ( I < 0x10000 ) ) >::type, TAOCPP_HEXPAND3(T0), TAOCPP_HEXPAND3(T1), TAOCPP_HEXPAND3(T2), TAOCPP_HEXPAND3(T3), TAOCPP_HEXPAND3(T4), TAOCPP_HEXPAND3(T5), TAOCPP_HEXPAND3(T6), TAOCPP_HEXPAND3(T7), Ts... > : type_by_index< I - 0x8000, void, Ts... > {}; #define TAOCPP_HEXPAND4(X) TAOCPP_HEXPAND3(X) template< std::size_t I, TAOCPP_HEXPAND4(typename T0), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x10000 ) && ( I < 0x20000 ) ) >::type, TAOCPP_HEXPAND4(T0), Ts... > : type_by_index< I - 0x10000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND4(typename T0), TAOCPP_HEXPAND4(typename T1), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x20000 ) && ( I < 0x40000 ) ) >::type, TAOCPP_HEXPAND4(T0), TAOCPP_HEXPAND4(T1), Ts... > : type_by_index< I - 0x20000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND4(typename T0), TAOCPP_HEXPAND4(typename T1), TAOCPP_HEXPAND4(typename T2), TAOCPP_HEXPAND4(typename T3), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x40000 ) && ( I < 0x80000 ) ) >::type, TAOCPP_HEXPAND4(T0), TAOCPP_HEXPAND4(T1), TAOCPP_HEXPAND4(T2), TAOCPP_HEXPAND4(T3), Ts... > : type_by_index< I - 0x40000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND4(typename T0), TAOCPP_HEXPAND4(typename T1), TAOCPP_HEXPAND4(typename T2), TAOCPP_HEXPAND4(typename T3), TAOCPP_HEXPAND4(typename T4), TAOCPP_HEXPAND4(typename T5), TAOCPP_HEXPAND4(typename T6), TAOCPP_HEXPAND4(typename T7), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x80000 ) && ( I < 0x100000 ) ) >::type, TAOCPP_HEXPAND4(T0), TAOCPP_HEXPAND4(T1), TAOCPP_HEXPAND4(T2), TAOCPP_HEXPAND4(T3), TAOCPP_HEXPAND4(T4), TAOCPP_HEXPAND4(T5), TAOCPP_HEXPAND4(T6), TAOCPP_HEXPAND4(T7), Ts... > : type_by_index< I - 0x80000, void, Ts... > {}; #define TAOCPP_HEXPAND5(X) TAOCPP_HEXPAND4(X) template< std::size_t I, TAOCPP_HEXPAND5(typename T0), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x100000 ) && ( I < 0x200000 ) ) >::type, TAOCPP_HEXPAND5(T0), Ts... > : type_by_index< I - 0x100000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND5(typename T0), TAOCPP_HEXPAND5(typename T1), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x200000 ) && ( I < 0x400000 ) ) >::type, TAOCPP_HEXPAND5(T0), TAOCPP_HEXPAND5(T1), Ts... > : type_by_index< I - 0x200000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND5(typename T0), TAOCPP_HEXPAND5(typename T1), TAOCPP_HEXPAND5(typename T2), TAOCPP_HEXPAND5(typename T3), typename... Ts> struct type_by_index< I, typename std::enable_if< ( ( I >= 0x400000 ) && ( I < 0x800000 ) ) >::type, TAOCPP_HEXPAND5(T0), TAOCPP_HEXPAND5(T1), TAOCPP_HEXPAND5(T2), TAOCPP_HEXPAND5(T3), Ts... > : type_by_index< I - 0x400000, void, Ts... > {}; template< std::size_t I, TAOCPP_HEXPAND5(typename T0), TAOCPP_HEXPAND5(typename T1), TAOCPP_HEXPAND5(typename T2), TAOCPP_HEXPAND5(typename T3), TAOCPP_HEXPAND5(typename T4), TAOCPP_HEXPAND5(typename T5), TAOCPP_HEXPAND5(typename T6), TAOCPP_HEXPAND5(typename T7), typename... Ts> struct type_by_index< I, typename std::enable_if< ( I >= 0x800000 ) >::type, TAOCPP_HEXPAND5(T0), TAOCPP_HEXPAND5(T1), TAOCPP_HEXPAND5(T2), TAOCPP_HEXPAND5(T3), TAOCPP_HEXPAND5(T4), TAOCPP_HEXPAND5(T5), TAOCPP_HEXPAND5(T6), TAOCPP_HEXPAND5(T7), Ts... > : type_by_index< I - 0x800000, void, Ts... > {}; #undef TAOCPP_HEXPAND5 #undef TAOCPP_HEXPAND4 #undef TAOCPP_HEXPAND3 #undef TAOCPP_HEXPAND2 #undef TAOCPP_HEXPAND } template< std::size_t I, typename... Ts > using type_by_index = impl::type_by_index< I, void, Ts... >; template< std::size_t I, typename... Ts > using type_by_index_t = typename type_by_index< I, Ts... >::type; } } #endif // TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP <commit_msg>Much better implementation based on user dyp's answer on StackOverflow<commit_after>// The Art of C++ / Sequences // Copyright (c) 2015 Daniel Frey #ifndef TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #define TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP #include <cstddef> #include <type_traits> #include "make_integer_sequence.hpp" namespace tao { namespace seq { // based on http://stackoverflow.com/questions/18942322 namespace impl { template< std::size_t > struct any { template< typename T > any( T&& ) {} }; template< typename > struct wrapper {}; template< std::size_t... Is > struct get_nth_helper { template< typename T, typename... Ts > static T deduce( any< Is >..., wrapper< T >, Ts&&... ); }; template< typename... Ts, std::size_t... Is > auto deduce( index_sequence< Is... > ) -> decltype( get_nth_helper< Is... >::deduce( wrapper< Ts >()... ) ); } template< std::size_t I, typename... Ts > struct type_by_index { using type = decltype( impl::deduce< Ts... >( make_index_sequence< I >() ) ); }; template< std::size_t I, typename... Ts > using type_by_index_t = typename type_by_index< I, Ts... >::type; } } #endif // TAOCPP_SEQUENCES_INCLUDE_TYPE_BY_INDEX_HPP <|endoftext|>
<commit_before>#ifndef TWISTEDCPP_LINE_RECEIVER #define TWISTEDCPP_LINE_RECEIVER #include "basic_protocol.hpp" #include "protocol_core.hpp" #include <vector> #include <boost/range/iterator_range.hpp> namespace twisted { template <typename ChildProtocol> class byte_receiver : public twisted::protocol_core<ChildProtocol, boost::iterator_range<std::vector<char>::iterator>> { public: typedef std::vector<char> internal_buffer_type; typedef internal_buffer_type::size_type size_type; typedef boost::iterator_range<internal_buffer_type::iterator> buffer_type; typedef boost::iterator_range<internal_buffer_type::const_iterator> const_buffer_type; byte_receiver(int start_bytes_size) : _next_bytes_size(start_bytes_size), _current_begin(0), _current_count(0), _read_buffer(calculate_buffer_size(start_bytes_size)) {} template <typename Iter> void on_message(Iter begin, Iter end) { _current_count += std::distance(begin, end); while(_current_count >= _next_bytes_size) { /* protocol user can change package size in between calls we need to cache the old package-size for the _current_* updates */ size_type old_package_size = _next_bytes_size; this->this_protocol().bytes_received( std::next(_read_buffer.begin(), _current_begin), std::next(_read_buffer.begin(), _current_begin + _next_bytes_size)); _current_count -= old_package_size; _current_begin += old_package_size; } if(_current_begin + _current_count == _read_buffer.size()) { std::copy( std::next(_read_buffer.begin(), _current_begin), _read_buffer.end(), _read_buffer.begin()); _current_begin = 0; } } buffer_type read_buffer() { return boost::make_iterator_range( std::next(_read_buffer.begin(), _current_begin + _current_count), _read_buffer.end()); } const const_buffer_type& read_buffer() const { return boost::make_iterator_range( std::next(_read_buffer.begin(), _current_begin + _current_count), _read_buffer.end()); } void set_package_size(size_type package_size) { if(_next_bytes_size < package_size) { _read_buffer.resize(calculate_buffer_size(package_size)); } _next_bytes_size = package_size; } private: constexpr size_type calculate_buffer_size(size_type new_min_size) const { return 3 * new_min_size; } size_type _next_bytes_size; // size per block size_type _current_begin; // start-position of not processed data in buffer size_type _current_count; // current amount of not processed data internal_buffer_type _read_buffer; }; } #endif <commit_msg>added check for unfragmented data to avoid unneeded<commit_after>#ifndef TWISTEDCPP_LINE_RECEIVER #define TWISTEDCPP_LINE_RECEIVER #include "basic_protocol.hpp" #include "protocol_core.hpp" #include <vector> #include <boost/range/iterator_range.hpp> namespace twisted { template <typename ChildProtocol> class byte_receiver : public twisted::protocol_core<ChildProtocol, boost::iterator_range<std::vector<char>::iterator>> { public: typedef std::vector<char> internal_buffer_type; typedef internal_buffer_type::size_type size_type; typedef boost::iterator_range<internal_buffer_type::iterator> buffer_type; typedef boost::iterator_range<internal_buffer_type::const_iterator> const_buffer_type; byte_receiver(int start_bytes_size) : _next_bytes_size(start_bytes_size), _current_begin(0), _current_count(0), _read_buffer(calculate_buffer_size(start_bytes_size)) {} template <typename Iter> void on_message(Iter begin, Iter end) { _current_count += std::distance(begin, end); while(_current_count >= _next_bytes_size) { /* protocol user can change package size in between calls -> we need to cache the old package-size for the _current_* updates */ size_type old_package_size = _next_bytes_size; this->this_protocol().bytes_received( std::next(_read_buffer.begin(), _current_begin), std::next(_read_buffer.begin(), _current_begin + _next_bytes_size)); _current_count -= old_package_size; _current_begin += old_package_size; } // un-fragmented data if(_current_count == 0) { _current_begin = 0; } /* fragmented data and buffer is full -> we need to copy the existing data to the beginning to make space for a full packet size */ else if(_current_begin + _current_count == _read_buffer.size()) { std::copy( std::next(_read_buffer.begin(), _current_begin), _read_buffer.end(), _read_buffer.begin()); _current_begin = 0; } } buffer_type read_buffer() { return boost::make_iterator_range( std::next(_read_buffer.begin(), _current_begin + _current_count), _read_buffer.end()); } const const_buffer_type& read_buffer() const { return boost::make_iterator_range( std::next(_read_buffer.begin(), _current_begin + _current_count), _read_buffer.end()); } void set_package_size(size_type package_size) { if(_next_bytes_size < package_size) { _read_buffer.resize(calculate_buffer_size(package_size)); } _next_bytes_size = package_size; } private: constexpr size_type calculate_buffer_size(size_type new_min_size) const { return 3 * new_min_size; } size_type _next_bytes_size; // size per block size_type _current_begin; // start-position of not processed data in buffer size_type _current_count; // current amount of not processed data internal_buffer_type _read_buffer; }; } #endif <|endoftext|>
<commit_before>//============================================================================ // include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #include <iostream> #include <string> namespace vsmc { /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. template <typename ThreadType, typename ThisThread> class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), iter_(0), total_(0), interval_(0), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), display_progress_(), display_percent_(), display_time_(), display_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param message A (short) discreptive message /// \param interval The sleep interval in seconds void start (unsigned total, const std::string &message = std::string(), double interval = 0.1) { iter_ = 0; total_ = total; interval_ = interval; print_first_ = true; in_progress_ = true; message_ = message; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = false) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(static_cast<void *>(this)); watch_.stop(); } /// \brief Increment the iteration count void increment (unsigned step = 1) {iter_ += step;} private : StopWatch watch_; thread_type *thread_ptr_; unsigned iter_; unsigned total_; double interval_; bool print_first_; bool in_progress_; unsigned num_equal_; unsigned percent_; unsigned seconds_; unsigned last_iter_; std::string message_; char display_progress_[128]; char display_percent_[32]; char display_time_[32]; char display_iter_[64]; std::ostream &os_; static VSMC_CONSTEXPR const unsigned num_equal_max_ = 60; static VSMC_CONSTEXPR const unsigned num_dash_max_ = 1; static VSMC_CONSTEXPR const unsigned percent_max_ = 100; void fork () { join(); thread_ptr_ = new thread_type(print_start_, static_cast<void *>(this)); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const unsigned seconds = static_cast<unsigned>(ptr->watch_.seconds()); const unsigned iter = ptr->iter_; const unsigned total = ptr->total_; const unsigned display_iter = iter <= total ? iter : total; unsigned num_equal = total == 0 ? num_equal_max_ : static_cast<unsigned>( static_cast<double>(num_equal_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); num_equal = num_equal <= num_equal_max_ ? num_equal : num_equal_max_; unsigned percent = total == 0 ? percent_max_ : static_cast<unsigned>( static_cast<double>(percent_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); percent = percent <= percent_max_ ? percent : percent_max_; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = iter + 1; } if (ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; unsigned num_space = num_equal_max_ - num_equal; unsigned num_dash = 0; while (num_space > num_dash) { if (num_dash == num_dash_max_) break; --num_space; ++num_dash; } char *cstr = ptr->display_progress_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (unsigned i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const unsigned num_space = 3 - uint_digit(percent); char *cstr = ptr->display_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const unsigned display_second = seconds % 60; const unsigned display_minute = (seconds / 60) % 60; const unsigned display_hour = seconds / 3600; char *cstr = ptr->display_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->last_iter_ != iter) { ptr->last_iter_ = iter; const unsigned dtotal = uint_digit(total); const unsigned diter = uint_digit(iter); const unsigned num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->display_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(iter, cstr, offset); cstr[offset++] = '/'; uint_to_char(total, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ' ' << ptr->message_ << ' '; ptr->os_ << ptr->display_progress_; ptr->os_ << ptr->display_percent_; ptr->os_ << ptr->display_time_; ptr->os_ << ptr->display_iter_; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static unsigned uint_digit (UIntType num) { if (num == 0) return 1; unsigned digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP <commit_msg>move message to the end<commit_after>//============================================================================ // include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #include <iostream> #include <string> namespace vsmc { /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. template <typename ThreadType, typename ThisThread> class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), iter_(0), total_(0), interval_(0), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), display_progress_(), display_percent_(), display_time_(), display_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param message A (short) discreptive message /// \param interval The sleep interval in seconds void start (unsigned total, const std::string &message = std::string(), double interval = 0.1) { iter_ = 0; total_ = total; interval_ = interval; print_first_ = true; in_progress_ = true; message_ = message; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = false) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(static_cast<void *>(this)); watch_.stop(); } /// \brief Increment the iteration count void increment (unsigned step = 1) {iter_ += step;} private : StopWatch watch_; thread_type *thread_ptr_; unsigned iter_; unsigned total_; double interval_; bool print_first_; bool in_progress_; unsigned num_equal_; unsigned percent_; unsigned seconds_; unsigned last_iter_; std::string message_; char display_progress_[128]; char display_percent_[32]; char display_time_[32]; char display_iter_[64]; std::ostream &os_; static VSMC_CONSTEXPR const unsigned num_equal_max_ = 60; static VSMC_CONSTEXPR const unsigned num_dash_max_ = 1; static VSMC_CONSTEXPR const unsigned percent_max_ = 100; void fork () { join(); thread_ptr_ = new thread_type(print_start_, static_cast<void *>(this)); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const unsigned seconds = static_cast<unsigned>(ptr->watch_.seconds()); const unsigned iter = ptr->iter_; const unsigned total = ptr->total_; const unsigned display_iter = iter <= total ? iter : total; unsigned num_equal = total == 0 ? num_equal_max_ : static_cast<unsigned>( static_cast<double>(num_equal_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); num_equal = num_equal <= num_equal_max_ ? num_equal : num_equal_max_; unsigned percent = total == 0 ? percent_max_ : static_cast<unsigned>( static_cast<double>(percent_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); percent = percent <= percent_max_ ? percent : percent_max_; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = iter + 1; } if (ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; unsigned num_space = num_equal_max_ - num_equal; unsigned num_dash = 0; while (num_space > num_dash) { if (num_dash == num_dash_max_) break; --num_space; ++num_dash; } char *cstr = ptr->display_progress_; std::size_t offset = 0; cstr[offset++] = ' '; cstr[offset++] = '['; for (unsigned i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (unsigned i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const unsigned num_space = 3 - uint_digit(percent); char *cstr = ptr->display_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const unsigned display_second = seconds % 60; const unsigned display_minute = (seconds / 60) % 60; const unsigned display_hour = seconds / 3600; char *cstr = ptr->display_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->last_iter_ != iter) { ptr->last_iter_ = iter; const unsigned dtotal = uint_digit(total); const unsigned diter = uint_digit(iter); const unsigned num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->display_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(iter, cstr, offset); cstr[offset++] = '/'; uint_to_char(total, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ptr->display_progress_; ptr->os_ << ptr->display_percent_; ptr->os_ << ptr->display_time_; ptr->os_ << ptr->display_iter_; ptr->os_ << '[' << ptr->message_ << ']'; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static unsigned uint_digit (UIntType num) { if (num == 0) return 1; unsigned digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP <|endoftext|>
<commit_before>#ifndef STAN__MATH__FUNCTIONS__SIGN_HPP #define STAN__MATH__FUNCTIONS__SIGN_HPP namespace stan { namespace math { template<typename T> inline int sign(const T& z) { return (z == 0) ? 0 : z < 0 ? -1 : 1; } } } #endif <commit_msg>added doc in code for sign<commit_after>#ifndef STAN__MATH__FUNCTIONS__SIGN_HPP #define STAN__MATH__FUNCTIONS__SIGN_HPP namespace stan { namespace math { // returns 1 if NaN is passed in. template<typename T> inline int sign(const T& z) { return (z == 0) ? 0 : z < 0 ? -1 : 1; } } } #endif <|endoftext|>
<commit_before>// Copyright (C) 2018 Egor Pugin <[email protected]> // // 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/. #include "primitives/sw/settings.h" #define YAML_SETTINGS_FILENAME "settings.yml" #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> #else #include <dlfcn.h> #endif namespace sw { #if defined(_WIN32)// && defined(CPPAN_SHARED_BUILD) std::string getProgramName() { auto h = GetModuleHandle(0); //auto f = (String(*)())GetProcAddress(h, "?getProgramName@sw@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ"); auto f = (String(*)())GetProcAddress(h, "?getProgramName@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ"); if (!f) { std::cerr << "sw.settings: calling getProgramName(), but function is not defined; result is unknown" << std::endl; return "unk"; } return f(); } #else std::string getProgramName() { auto h = dlopen(0, RTLD_LAZY); if (!h) { std::cerr << "sw.settings: dlopen error" << std::endl; return "unk"; } //auto f = (String(*)())dlsym(h, "_ZN2sw14getProgramNameB5cxx11Ev"); auto f = (String(*)())dlsym(h, "_Z14getProgramNameB5cxx11v"); if (!f) { dlclose(h); std::cerr << "sw.settings: calling getProgramName(), but function is not defined; result is unknown" << std::endl; return "unk"; } auto s = f(); dlclose(h); return s; } #endif path getSettingsDir() { return get_home_directory() / ".sw_settings" / getProgramName(); } template <class T> SettingStorage<T>::~SettingStorage() { base::getUserSettings().save(base::userConfigFilename); } #if defined(_WIN32) || defined(__APPLE__) template struct SettingStorage<::primitives::Settings>; #endif primitives::SettingStorage<primitives::Settings> &getSettingStorage() { static auto &settings = []() -> primitives::SettingStorage<primitives::Settings> & { static SettingStorage<primitives::Settings> s; primitives::getSettingStorage(&s); // save to common storage s.userConfigFilename = getSettingsDir() / YAML_SETTINGS_FILENAME; path local_name = getProgramName() + ".settings"; if (fs::exists(local_name)) s.getLocalSettings().load(local_name); return s; }(); return settings; } primitives::Settings &getSettings(SettingsType type) { return getSettingStorage().get(type); } } <commit_msg>Show warning during settings load.<commit_after>// Copyright (C) 2018 Egor Pugin <[email protected]> // // 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/. #include "primitives/sw/settings.h" #define YAML_SETTINGS_FILENAME "settings.yml" #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> #else #include <dlfcn.h> #endif namespace sw { #if defined(_WIN32)// && defined(CPPAN_SHARED_BUILD) std::string getProgramName() { auto h = GetModuleHandle(0); //auto f = (String(*)())GetProcAddress(h, "?getProgramName@sw@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ"); auto f = (String(*)())GetProcAddress(h, "?getProgramName@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ"); if (!f) { //std::cerr << "sw.settings: calling getProgramName(), but function is not defined; result is unknown" << std::endl; return {}; } return f(); } #else std::string getProgramName() { auto h = dlopen(0, RTLD_LAZY); if (!h) { std::cerr << "sw.settings: dlopen error" << std::endl; return {}; } //auto f = (String(*)())dlsym(h, "_ZN2sw14getProgramNameB5cxx11Ev"); auto f = (String(*)())dlsym(h, "_Z14getProgramNameB5cxx11v"); if (!f) { dlclose(h); //std::cerr << "sw.settings: calling getProgramName(), but function is not defined; result is unknown" << std::endl; return {}; } auto s = f(); dlclose(h); return s; } #endif path getSettingsDir() { return get_home_directory() / ".sw_settings" / getProgramName(); } template <class T> SettingStorage<T>::~SettingStorage() { base::getUserSettings().save(base::userConfigFilename); } #if defined(_WIN32) || defined(__APPLE__) template struct SettingStorage<::primitives::Settings>; #endif primitives::SettingStorage<primitives::Settings> &getSettingStorage() { static auto &settings = []() -> primitives::SettingStorage<primitives::Settings> & { static SettingStorage<primitives::Settings> s; primitives::getSettingStorage(&s); // save to common storage s.userConfigFilename = getSettingsDir() / YAML_SETTINGS_FILENAME; auto prog = getProgramName(); auto sfile = prog + ".settings"; if (prog.empty()) { //LOG_TRACE(logger, "load settings: getProgramName() returned nothing. Trying to load " + sfile); std::cerr << "sw.settings: calling getProgramName(), but function returned nothing; result is unknown" << std::endl; } path local_name = sfile; if (fs::exists(local_name)) s.getLocalSettings().load(local_name); return s; }(); return settings; } primitives::Settings &getSettings(SettingsType type) { return getSettingStorage().get(type); } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 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 * *****************************************************************************/ #include <mapnik/config.hpp> // boost #include "boost_std_shared_shim.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/image_data.hpp> #include <mapnik/image_view.hpp> #include <mapnik/image_util.hpp> #include <mapnik/palette.hpp> #include <sstream> using mapnik::image_view_rgba8; using mapnik::save_to_file; // output 'raw' pixels PyObject* view_tostring1(image_view_rgba8 const& view) { std::ostringstream ss(std::ios::out|std::ios::binary); for (unsigned i=0;i<view.height();i++) { ss.write(reinterpret_cast<const char*>(view.getRow(i)), view.width() * sizeof(image_view_rgba8::pixel_type)); } return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif ((const char*)ss.str().c_str(),ss.str().size()); } // encode (png,jpeg) PyObject* view_tostring2(image_view_rgba8 const & view, std::string const& format) { std::string s = save_to_string(view, format); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } PyObject* view_tostring3(image_view_rgba8 const & view, std::string const& format, mapnik::rgba_palette const& pal) { std::string s = save_to_string(view, format, pal); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } bool is_solid(image_view_rgba8 const& view) { mapnik::is_solid(view); } void save_view1(image_view_rgba8 const& view, std::string const& filename) { save_to_file(view,filename); } void save_view2(image_view_rgba8 const& view, std::string const& filename, std::string const& type) { save_to_file(view,filename,type); } void save_view3(image_view_rgba8 const& view, std::string const& filename, std::string const& type, mapnik::rgba_palette const& pal) { save_to_file(view,filename,type,pal); } void export_image_view() { using namespace boost::python; class_<image_view_rgba8>("ImageView","A view into an image.",no_init) .def("width",&image_view_rgba8::width) .def("height",&image_view_rgba8::height) .def("is_solid",&is_solid) .def("tostring",&view_tostring1) .def("tostring",&view_tostring2) .def("tostring",&view_tostring3) .def("save",&save_view1) .def("save",&save_view2) .def("save",&save_view3) ; } <commit_msg>fix is_solid return<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 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 * *****************************************************************************/ #include <mapnik/config.hpp> // boost #include "boost_std_shared_shim.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/image_data.hpp> #include <mapnik/image_view.hpp> #include <mapnik/image_util.hpp> #include <mapnik/palette.hpp> #include <sstream> using mapnik::image_view_rgba8; using mapnik::save_to_file; // output 'raw' pixels PyObject* view_tostring1(image_view_rgba8 const& view) { std::ostringstream ss(std::ios::out|std::ios::binary); for (unsigned i=0;i<view.height();i++) { ss.write(reinterpret_cast<const char*>(view.getRow(i)), view.width() * sizeof(image_view_rgba8::pixel_type)); } return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif ((const char*)ss.str().c_str(),ss.str().size()); } // encode (png,jpeg) PyObject* view_tostring2(image_view_rgba8 const & view, std::string const& format) { std::string s = save_to_string(view, format); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } PyObject* view_tostring3(image_view_rgba8 const & view, std::string const& format, mapnik::rgba_palette const& pal) { std::string s = save_to_string(view, format, pal); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } bool is_solid(image_view_rgba8 const& view) { return mapnik::is_solid(view); } void save_view1(image_view_rgba8 const& view, std::string const& filename) { save_to_file(view,filename); } void save_view2(image_view_rgba8 const& view, std::string const& filename, std::string const& type) { save_to_file(view,filename,type); } void save_view3(image_view_rgba8 const& view, std::string const& filename, std::string const& type, mapnik::rgba_palette const& pal) { save_to_file(view,filename,type,pal); } void export_image_view() { using namespace boost::python; class_<image_view_rgba8>("ImageView","A view into an image.",no_init) .def("width",&image_view_rgba8::width) .def("height",&image_view_rgba8::height) .def("is_solid",&is_solid) .def("tostring",&view_tostring1) .def("tostring",&view_tostring2) .def("tostring",&view_tostring3) .def("save",&save_view1) .def("save",&save_view2) .def("save",&save_view3) ; } <|endoftext|>
<commit_before>// see [A multi-threaded Producer Consumer with C++11](http://codereview.stackexchange.com/questions/84109/a-multi-threaded-producer-consumer-with-c11) // note that `lock_guard` is recommended instead of `unique_lock` as it releases lock automatically follow RAII leaving the lock scope. // see also [](http://www.boost.org/doc/libs/1_54_0/doc/html/lockfree/examples.html) for atomics instead of locks. // #include <iostream> #include <thread> #include <vector> // for creating an equivalent to `boost::thread_group` #include <mutex> #include <condition_variable> #include <deque> #include <random> class Buffer { public: void add(int num) { while (true) { std::unique_lock<std::mutex> locker(mu); cond.wait(locker, [this](){return buffer_.size() < size_;}); std::cout << "add(): pushed " << num << "\n"; buffer_.push_back(num); //locker.unlock(); cond.notify_all(); return; } } int remove() { while (true) { std::unique_lock<std::mutex> locker(mu); cond.wait(locker, [this](){return buffer_.size() > 0;}); int back = buffer_.back(); buffer_.pop_back(); std::cout << "remove(): popped " << back << "\n"; //locker.unlock(); cond.notify_all(); return back; } } Buffer() {} private: std::mutex mu; std::condition_variable cond; std::deque<int> buffer_; const unsigned int size_ = 10; }; void join_all(std::vector<std::thread>& grp) { for (auto& thr : grp) if (thr.joinable()) thr.join(); } main() { // Non-deterministic pseudo-random numbers generator thread_local std::random_device rd; // Pseudo-random engine thread_local std::mt19937 engine(rd()); // Linear distribution in [0, 100[ thread_local std::uniform_int_distribution<int> dist(0, 99); std::vector<std::thread> producer_grp, consumer_grp; const int producer_thread_count = 12; const int consumer_thread_count = 12; Buffer buffer; for (int i = 0; i < producer_thread_count; i++) { int num = dist(engine); producer_grp.emplace_back(&Buffer::add, &buffer, num); } for (int i = 0; i < consumer_thread_count; i++) { consumer_grp.emplace_back(&Buffer::remove, &buffer); } join_all(producer_grp); join_all(consumer_grp); } <commit_msg>update producer-consumer sample.<commit_after>// see [A multi-threaded Producer Consumer with C++11](http://codereview.stackexchange.com/questions/84109/a-multi-threaded-producer-consumer-with-c11) // note that `lock_guard` is recommended instead of `unique_lock` as it releases lock automatically follow RAII leaving the lock scope. // see also [](http://www.boost.org/doc/libs/1_54_0/doc/html/lockfree/examples.html) for atomics instead of locks. // #include <iostream> #include <thread> #include <vector> // for creating an equivalent to `boost::thread_group` #include <mutex> #include <condition_variable> #include <deque> #include <random> template<class T> auto operator<<(std::ostream& os, const T& t) -> decltype(t.print(os), os) { t.print(os); return os; } // to store robot commands template <typename T> class Buffer { public: void add(T&& item) { std::unique_lock<std::mutex> locker(mu_); cond_.wait(locker, [this] { return buffer_.size() < size_; } ); std::cout << "add(): pushed " << item << "\n"; buffer_.push_back(item); cond_.notify_all(); return; } T remove() { std::unique_lock<std::mutex> locker(mu_); cond_.wait(locker, [this] { return !buffer_.empty(); } ); auto back = buffer_.back(); buffer_.pop_back(); std::cout << "remove(): popped " << back << "\n"; cond_.notify_all(); return back; } bool empty() const { return buffer_.empty(); } Buffer() {} private: std::mutex mu_; std::condition_variable cond_; std::deque<T> buffer_; const unsigned size_ = 128; }; struct RobotCommand { int task_id, sequence_id, command_type; void print(std::ostream& strm) const { strm << "task_id: " << task_id << " sequence_id: " << sequence_id << " command_type: " << command_type; } }; void join_all(std::vector<std::thread>& grp) { for (auto& thr : grp) if (thr.joinable()) thr.join(); } main() { // Non-deterministic pseudo-random numbers generator thread_local std::random_device rd; // Pseudo-random engine thread_local std::mt19937 engine(rd()); // Linear distribution in [0, 100[ thread_local std::uniform_int_distribution<int> dist(0, 99); std::vector<std::thread> producer_grp, consumer_grp; const int producer_thread_count = 12; const int consumer_thread_count = 12; Buffer<int> buffer; for (int i = 0; i < producer_thread_count; i++) { int num = dist(engine); producer_grp.emplace_back(&Buffer<int>::add, &buffer, num); } for (int i = 0; i < consumer_thread_count; i++) { consumer_grp.emplace_back(&Buffer<int>::remove, &buffer); } join_all(producer_grp); join_all(consumer_grp); } <|endoftext|>
<commit_before>// Copyright (c) 2009 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 <string> #include "app/l10n_util.h" #include "base/sys_info.h" #include "chrome/browser/app_modal_dialog.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/page_transition_types.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" const std::string BEFORE_UNLOAD_HTML = "<html><head><title>beforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){return 'foo'}</script>" "</body></html>"; const std::wstring OPEN_NEW_BEFOREUNLOAD_PAGE = L"w=window.open(); w.onbeforeunload=function(e){return 'foo'};"; namespace { // Given a page title, returns the expected window caption string. std::wstring WindowCaptionFromPageTitle(std::wstring page_title) { #if defined(OS_WIN) || defined(OS_LINUX) if (page_title.empty()) return l10n_util::GetString(IDS_PRODUCT_NAME); return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title); #elif defined(OS_MACOSX) // On Mac, we don't want to suffix the page title with the application name. if (page_title.empty()) return l10n_util::GetString(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED); return page_title; #endif } // Returns the number of active RenderProcessHosts. int CountRenderProcessHosts() { int result = 0; for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) ++result; return result; } } // namespace class BrowserTest : public InProcessBrowserTest { protected: // In RTL locales wrap the page title with RTL embedding characters so that it // matches the value returned by GetWindowTitle(). std::wstring LocaleWindowCaptionFromPageTitle( const std::wstring& expected_title) { std::wstring page_title = WindowCaptionFromPageTitle(expected_title); #if defined(OS_WIN) std::string locale = g_browser_process->GetApplicationLocale(); if (l10n_util::GetTextDirectionForLocale(locale.c_str()) == l10n_util::RIGHT_TO_LEFT) { l10n_util::WrapStringWithLTRFormatting(&page_title); } return page_title; #else // Do we need to use the above code on POSIX as well? return page_title; #endif } }; // Launch the app on a page with no title, check that the app title was set // correctly. IN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) { ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(L".", L"title1.html")); EXPECT_EQ(LocaleWindowCaptionFromPageTitle(L"title1.html"), UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab())); string16 tab_title; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title)); EXPECT_EQ(ASCIIToUTF16("title1.html"), tab_title); } // Launch the app, navigate to a page with a title, check that the app title // was set correctly. IN_PROC_BROWSER_TEST_F(BrowserTest, Title) { ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(L".", L"title2.html")); const std::wstring test_title(L"Title Of Awesomeness"); EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title), UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab())); string16 tab_title; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title)); EXPECT_EQ(WideToUTF16(test_title), tab_title); } #if !defined(OS_MACOSX) // TODO(port): BUG16322 IN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) { GURL url(ui_test_utils::GetTestUrl(L".", L"title1.html")); ui_test_utils::NavigateToURL(browser(), url); browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, 0, false, NULL); EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(0, browser()->selected_index()); TabContents* second_tab = browser()->GetTabContentsAt(1); ASSERT_TRUE(second_tab); second_tab->render_view_host()->ExecuteJavascriptInWebFrame(L"", L"alert('Activate!');"); AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog(); alert->CloseModalDialog(); EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->selected_index()); } #endif // !defined(OS_MACOSX) // Create 34 tabs and verify that a lot of processes have been created. The // exact number of processes depends on the amount of memory. Previously we // had a hard limit of 31 processes and this test is mainly directed at // verifying that we don't crash when we pass this limit. IN_PROC_BROWSER_TEST_F(BrowserTest, ThirtyFourTabs) { GURL url(ui_test_utils::GetTestUrl(L".", L"title2.html")); // There is one initial tab. for (int ix = 0; ix != 33; ++ix) { browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, 0, false, NULL); } EXPECT_EQ(34, browser()->tab_count()); // See browser\renderer_host\render_process_host.cc for the algorithm to // decide how many processes to create. if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) { EXPECT_GE(CountRenderProcessHosts(), 24); } else { EXPECT_LE(CountRenderProcessHosts(), 23); } } // Test for crbug.com/22004. Reloading a page with a before unload handler and // then canceling the dialog should not leave the throbber spinning. IN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) { GURL url("data:text/html," + BEFORE_UNLOAD_HTML); ui_test_utils::NavigateToURL(browser(), url); // Navigate to another page, but click cancel in the dialog. Make sure that // the throbber stops spinning. browser()->Reload(); AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog(); alert->CloseModalDialog(); EXPECT_FALSE(browser()->GetSelectedTabContents()->is_loading()); // Clear the beforeunload handler so the test can easily exit. browser()->GetSelectedTabContents()->render_view_host()-> ExecuteJavascriptInWebFrame(L"", L"onbeforeunload=null;"); } // Test for crbug.com/11647. A page closed with window.close() should not have // two beforeunload dialogs shown. IN_PROC_BROWSER_TEST_F(BrowserTest, SingleBeforeUnloadAfterWindowClose) { browser()->GetSelectedTabContents()->render_view_host()-> ExecuteJavascriptInWebFrame(L"", OPEN_NEW_BEFOREUNLOAD_PAGE); // Close the new window with JavaScript, which should show a single // beforeunload dialog. Then show another alert, to make it easy to verify // that a second beforeunload dialog isn't shown. browser()->GetTabContentsAt(0)->render_view_host()-> ExecuteJavascriptInWebFrame(L"", L"w.close(); alert('bar');"); AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog(); alert->AcceptWindow(); alert = ui_test_utils::WaitForAppModalDialog(); EXPECT_FALSE(alert->is_before_unload_dialog()); alert->AcceptWindow(); } // Test that get_process_idle_time() returns reasonable values when compared // with time deltas measured locally. IN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) { base::TimeTicks start = base::TimeTicks::Now(); ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(L".", L"title1.html")); RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator()); for (; !it.IsAtEnd(); it.Advance()) { base::TimeDelta renderer_td = it.GetCurrentValue()->get_child_process_idle_time(); base::TimeDelta browser_td = base::TimeTicks::Now() - start; EXPECT_TRUE(browser_td >= renderer_td); } } <commit_msg>Mark BrowserTest.SingleBeforeUnloadAfterWindowClose as flaky.<commit_after>// Copyright (c) 2009 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 <string> #include "app/l10n_util.h" #include "base/sys_info.h" #include "chrome/browser/app_modal_dialog.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/page_transition_types.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" const std::string BEFORE_UNLOAD_HTML = "<html><head><title>beforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){return 'foo'}</script>" "</body></html>"; const std::wstring OPEN_NEW_BEFOREUNLOAD_PAGE = L"w=window.open(); w.onbeforeunload=function(e){return 'foo'};"; namespace { // Given a page title, returns the expected window caption string. std::wstring WindowCaptionFromPageTitle(std::wstring page_title) { #if defined(OS_WIN) || defined(OS_LINUX) if (page_title.empty()) return l10n_util::GetString(IDS_PRODUCT_NAME); return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title); #elif defined(OS_MACOSX) // On Mac, we don't want to suffix the page title with the application name. if (page_title.empty()) return l10n_util::GetString(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED); return page_title; #endif } // Returns the number of active RenderProcessHosts. int CountRenderProcessHosts() { int result = 0; for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) ++result; return result; } } // namespace class BrowserTest : public InProcessBrowserTest { protected: // In RTL locales wrap the page title with RTL embedding characters so that it // matches the value returned by GetWindowTitle(). std::wstring LocaleWindowCaptionFromPageTitle( const std::wstring& expected_title) { std::wstring page_title = WindowCaptionFromPageTitle(expected_title); #if defined(OS_WIN) std::string locale = g_browser_process->GetApplicationLocale(); if (l10n_util::GetTextDirectionForLocale(locale.c_str()) == l10n_util::RIGHT_TO_LEFT) { l10n_util::WrapStringWithLTRFormatting(&page_title); } return page_title; #else // Do we need to use the above code on POSIX as well? return page_title; #endif } }; // Launch the app on a page with no title, check that the app title was set // correctly. IN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) { ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(L".", L"title1.html")); EXPECT_EQ(LocaleWindowCaptionFromPageTitle(L"title1.html"), UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab())); string16 tab_title; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title)); EXPECT_EQ(ASCIIToUTF16("title1.html"), tab_title); } // Launch the app, navigate to a page with a title, check that the app title // was set correctly. IN_PROC_BROWSER_TEST_F(BrowserTest, Title) { ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(L".", L"title2.html")); const std::wstring test_title(L"Title Of Awesomeness"); EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title), UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab())); string16 tab_title; ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title)); EXPECT_EQ(WideToUTF16(test_title), tab_title); } #if !defined(OS_MACOSX) // TODO(port): BUG16322 IN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) { GURL url(ui_test_utils::GetTestUrl(L".", L"title1.html")); ui_test_utils::NavigateToURL(browser(), url); browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, 0, false, NULL); EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(0, browser()->selected_index()); TabContents* second_tab = browser()->GetTabContentsAt(1); ASSERT_TRUE(second_tab); second_tab->render_view_host()->ExecuteJavascriptInWebFrame(L"", L"alert('Activate!');"); AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog(); alert->CloseModalDialog(); EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(1, browser()->selected_index()); } #endif // !defined(OS_MACOSX) // Create 34 tabs and verify that a lot of processes have been created. The // exact number of processes depends on the amount of memory. Previously we // had a hard limit of 31 processes and this test is mainly directed at // verifying that we don't crash when we pass this limit. IN_PROC_BROWSER_TEST_F(BrowserTest, ThirtyFourTabs) { GURL url(ui_test_utils::GetTestUrl(L".", L"title2.html")); // There is one initial tab. for (int ix = 0; ix != 33; ++ix) { browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, 0, false, NULL); } EXPECT_EQ(34, browser()->tab_count()); // See browser\renderer_host\render_process_host.cc for the algorithm to // decide how many processes to create. if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) { EXPECT_GE(CountRenderProcessHosts(), 24); } else { EXPECT_LE(CountRenderProcessHosts(), 23); } } // Test for crbug.com/22004. Reloading a page with a before unload handler and // then canceling the dialog should not leave the throbber spinning. IN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) { GURL url("data:text/html," + BEFORE_UNLOAD_HTML); ui_test_utils::NavigateToURL(browser(), url); // Navigate to another page, but click cancel in the dialog. Make sure that // the throbber stops spinning. browser()->Reload(); AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog(); alert->CloseModalDialog(); EXPECT_FALSE(browser()->GetSelectedTabContents()->is_loading()); // Clear the beforeunload handler so the test can easily exit. browser()->GetSelectedTabContents()->render_view_host()-> ExecuteJavascriptInWebFrame(L"", L"onbeforeunload=null;"); } // Test for crbug.com/11647. A page closed with window.close() should not have // two beforeunload dialogs shown. IN_PROC_BROWSER_TEST_F(BrowserTest, FLAKY_SingleBeforeUnloadAfterWindowClose) { browser()->GetSelectedTabContents()->render_view_host()-> ExecuteJavascriptInWebFrame(L"", OPEN_NEW_BEFOREUNLOAD_PAGE); // Close the new window with JavaScript, which should show a single // beforeunload dialog. Then show another alert, to make it easy to verify // that a second beforeunload dialog isn't shown. browser()->GetTabContentsAt(0)->render_view_host()-> ExecuteJavascriptInWebFrame(L"", L"w.close(); alert('bar');"); AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog(); alert->AcceptWindow(); alert = ui_test_utils::WaitForAppModalDialog(); EXPECT_FALSE(alert->is_before_unload_dialog()); alert->AcceptWindow(); } // Test that get_process_idle_time() returns reasonable values when compared // with time deltas measured locally. IN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) { base::TimeTicks start = base::TimeTicks::Now(); ui_test_utils::NavigateToURL(browser(), ui_test_utils::GetTestUrl(L".", L"title1.html")); RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator()); for (; !it.IsAtEnd(); it.Advance()) { base::TimeDelta renderer_td = it.GetCurrentValue()->get_child_process_idle_time(); base::TimeDelta browser_td = base::TimeTicks::Now() - start; EXPECT_TRUE(browser_td >= renderer_td); } } <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "chrome/browser/plugin_data_remover.h" #include "base/command_line.h" #include "base/message_loop_proxy.h" #include "base/metrics/histogram.h" #include "base/version.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/plugin_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/plugin_messages.h" #include "webkit/plugins/npapi/plugin_group.h" #include "webkit/plugins/npapi/plugin_list.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #endif namespace { const char* kFlashMimeType = "application/x-shockwave-flash"; // TODO(bauerb): Update minimum required Flash version as soon as there is one // implementing the API. const char* kMinFlashVersion = "100"; const int64 kRemovalTimeoutMs = 10000; const uint64 kClearAllData = 0; } // namespace PluginDataRemover::PluginDataRemover() : mime_type_(kFlashMimeType), is_removing_(false), event_(new base::WaitableEvent(true, false)), channel_(NULL) { } PluginDataRemover::~PluginDataRemover() { DCHECK(!is_removing_); if (channel_) BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, channel_); } base::WaitableEvent* PluginDataRemover::StartRemoving( const base::Time& begin_time) { DCHECK(!is_removing_); remove_start_time_ = base::Time::Now(); begin_time_ = begin_time; is_removing_ = true; AddRef(); PluginService::GetInstance()->OpenChannelToNpapiPlugin( 0, 0, GURL(), mime_type_, this); BrowserThread::PostDelayedTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &PluginDataRemover::OnTimeout), kRemovalTimeoutMs); return event_.get(); } void PluginDataRemover::Wait() { base::Time start_time(base::Time::Now()); bool result = true; if (is_removing_) result = event_->Wait(); UMA_HISTOGRAM_TIMES("ClearPluginData.wait_at_shutdown", base::Time::Now() - start_time); UMA_HISTOGRAM_TIMES("ClearPluginData.time_at_shutdown", base::Time::Now() - remove_start_time_); DCHECK(result) << "Error waiting for plugin process"; } int PluginDataRemover::ID() { // Generate an ID for the browser process. return ChildProcessInfo::GenerateChildProcessUniqueId(); } bool PluginDataRemover::OffTheRecord() { return false; } void PluginDataRemover::SetPluginInfo( const webkit::npapi::WebPluginInfo& info) { } void PluginDataRemover::OnChannelOpened(const IPC::ChannelHandle& handle) { ConnectToChannel(handle); Release(); } void PluginDataRemover::ConnectToChannel(const IPC::ChannelHandle& handle) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // If we timed out, don't bother connecting. if (!is_removing_) return; DCHECK(!channel_); channel_ = new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this); if (!channel_->Connect()) { NOTREACHED() << "Couldn't connect to plugin"; SignalDone(); return; } if (!channel_->Send( new PluginMsg_ClearSiteData(std::string(), kClearAllData, begin_time_))) { NOTREACHED() << "Couldn't send ClearSiteData message"; SignalDone(); return; } } void PluginDataRemover::OnError() { LOG(DFATAL) << "Couldn't open plugin channel"; SignalDone(); Release(); } void PluginDataRemover::OnClearSiteDataResult(bool success) { LOG_IF(DFATAL, !success) << "ClearSiteData returned error"; UMA_HISTOGRAM_TIMES("ClearPluginData.time", base::Time::Now() - remove_start_time_); SignalDone(); } void PluginDataRemover::OnTimeout() { LOG_IF(DFATAL, is_removing_) << "Timed out"; SignalDone(); } bool PluginDataRemover::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(PluginDataRemover, msg) IPC_MESSAGE_HANDLER(PluginHostMsg_ClearSiteDataResult, OnClearSiteDataResult) IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() return true; } void PluginDataRemover::OnChannelError() { if (is_removing_) { NOTREACHED() << "Channel error"; SignalDone(); } } void PluginDataRemover::SignalDone() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!is_removing_) return; is_removing_ = false; event_->Signal(); } // static bool PluginDataRemover::IsSupported() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); bool allow_wildcard = false; webkit::npapi::WebPluginInfo plugin; std::string mime_type; if (!webkit::npapi::PluginList::Singleton()->GetPluginInfo( GURL(), kFlashMimeType, allow_wildcard, &plugin, &mime_type)) { return false; } scoped_ptr<Version> version( webkit::npapi::PluginGroup::CreateVersionFromString(plugin.version)); scoped_ptr<Version> min_version(Version::GetVersionFromString( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kMinClearSiteDataFlashVersion))); if (!min_version.get()) min_version.reset(Version::GetVersionFromString(kMinFlashVersion)); return webkit::npapi::IsPluginEnabled(plugin) && version.get() && min_version->CompareTo(*version) == -1; } <commit_msg>Update minimum Flash version implementing NPP_ClearSiteData.<commit_after>// Copyright (c) 2011 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 "chrome/browser/plugin_data_remover.h" #include "base/command_line.h" #include "base/message_loop_proxy.h" #include "base/metrics/histogram.h" #include "base/version.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/plugin_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/plugin_messages.h" #include "webkit/plugins/npapi/plugin_group.h" #include "webkit/plugins/npapi/plugin_list.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #endif namespace { const char* kFlashMimeType = "application/x-shockwave-flash"; // The minimum Flash Player version that implements NPP_ClearSiteData. const char* kMinFlashVersion = "10.3"; const int64 kRemovalTimeoutMs = 10000; const uint64 kClearAllData = 0; } // namespace PluginDataRemover::PluginDataRemover() : mime_type_(kFlashMimeType), is_removing_(false), event_(new base::WaitableEvent(true, false)), channel_(NULL) { } PluginDataRemover::~PluginDataRemover() { DCHECK(!is_removing_); if (channel_) BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, channel_); } base::WaitableEvent* PluginDataRemover::StartRemoving( const base::Time& begin_time) { DCHECK(!is_removing_); remove_start_time_ = base::Time::Now(); begin_time_ = begin_time; is_removing_ = true; AddRef(); PluginService::GetInstance()->OpenChannelToNpapiPlugin( 0, 0, GURL(), mime_type_, this); BrowserThread::PostDelayedTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &PluginDataRemover::OnTimeout), kRemovalTimeoutMs); return event_.get(); } void PluginDataRemover::Wait() { base::Time start_time(base::Time::Now()); bool result = true; if (is_removing_) result = event_->Wait(); UMA_HISTOGRAM_TIMES("ClearPluginData.wait_at_shutdown", base::Time::Now() - start_time); UMA_HISTOGRAM_TIMES("ClearPluginData.time_at_shutdown", base::Time::Now() - remove_start_time_); DCHECK(result) << "Error waiting for plugin process"; } int PluginDataRemover::ID() { // Generate an ID for the browser process. return ChildProcessInfo::GenerateChildProcessUniqueId(); } bool PluginDataRemover::OffTheRecord() { return false; } void PluginDataRemover::SetPluginInfo( const webkit::npapi::WebPluginInfo& info) { } void PluginDataRemover::OnChannelOpened(const IPC::ChannelHandle& handle) { ConnectToChannel(handle); Release(); } void PluginDataRemover::ConnectToChannel(const IPC::ChannelHandle& handle) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // If we timed out, don't bother connecting. if (!is_removing_) return; DCHECK(!channel_); channel_ = new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this); if (!channel_->Connect()) { NOTREACHED() << "Couldn't connect to plugin"; SignalDone(); return; } if (!channel_->Send( new PluginMsg_ClearSiteData(std::string(), kClearAllData, begin_time_))) { NOTREACHED() << "Couldn't send ClearSiteData message"; SignalDone(); return; } } void PluginDataRemover::OnError() { LOG(DFATAL) << "Couldn't open plugin channel"; SignalDone(); Release(); } void PluginDataRemover::OnClearSiteDataResult(bool success) { LOG_IF(DFATAL, !success) << "ClearSiteData returned error"; UMA_HISTOGRAM_TIMES("ClearPluginData.time", base::Time::Now() - remove_start_time_); SignalDone(); } void PluginDataRemover::OnTimeout() { LOG_IF(DFATAL, is_removing_) << "Timed out"; SignalDone(); } bool PluginDataRemover::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(PluginDataRemover, msg) IPC_MESSAGE_HANDLER(PluginHostMsg_ClearSiteDataResult, OnClearSiteDataResult) IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() return true; } void PluginDataRemover::OnChannelError() { if (is_removing_) { NOTREACHED() << "Channel error"; SignalDone(); } } void PluginDataRemover::SignalDone() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!is_removing_) return; is_removing_ = false; event_->Signal(); } // static bool PluginDataRemover::IsSupported() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); bool allow_wildcard = false; webkit::npapi::WebPluginInfo plugin; std::string mime_type; if (!webkit::npapi::PluginList::Singleton()->GetPluginInfo( GURL(), kFlashMimeType, allow_wildcard, &plugin, &mime_type)) { return false; } scoped_ptr<Version> version( webkit::npapi::PluginGroup::CreateVersionFromString(plugin.version)); scoped_ptr<Version> min_version(Version::GetVersionFromString( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kMinClearSiteDataFlashVersion))); if (!min_version.get()) min_version.reset(Version::GetVersionFromString(kMinFlashVersion)); return webkit::npapi::IsPluginEnabled(plugin) && version.get() && min_version->CompareTo(*version) == -1; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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. // // See the corresponding header file for description of the functions in this // file. #include "install_util.h" #include <algorithm> #include <shellapi.h> #include <shlobj.h> #include "base/logging.h" #include "base/registry.h" #include "base/string_util.h" #include "base/win_util.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/l10n_string_util.h" #include "chrome/installer/util/work_item_list.h" bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe, const std::wstring& params, DWORD* exit_code) { SHELLEXECUTEINFO info = {0}; info.cbSize = sizeof(SHELLEXECUTEINFO); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.lpVerb = L"runas"; info.lpFile = exe.c_str(); info.lpParameters = params.c_str(); info.nShow = SW_SHOW; if (::ShellExecuteEx(&info) == FALSE) return false; ::WaitForSingleObject(info.hProcess, INFINITE); DWORD ret_val = 0; if (!::GetExitCodeProcess(info.hProcess, &ret_val)) return false; if (exit_code) *exit_code = ret_val; return true; } std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); RegKey key(root, dist->GetUninstallRegPath().c_str()); std::wstring uninstall_cmd; key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd); return uninstall_cmd; } installer::Version* InstallUtil::GetChromeVersion(bool system_install) { RegKey key; std::wstring version_str; HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) || !key.ReadValue(google_update::kRegVersionField, &version_str)) { LOG(INFO) << "No existing Chrome install found."; key.Close(); return NULL; } key.Close(); LOG(INFO) << "Existing Chrome version found " << version_str; return installer::Version::GetVersionFromString(version_str); } bool InstallUtil::IsOSSupported() { int major, minor; win_util::WinVersion version = win_util::GetWinVersion(); win_util::GetServicePackLevel(&major, &minor); // We do not support Win2K or older, or XP without service pack 1. LOG(INFO) << "Windows Version: " << version << ", Service Pack: " << major << "." << minor; if ((version == win_util::WINVERSION_VISTA) || (version == win_util::WINVERSION_SERVER_2003) || (version == win_util::WINVERSION_XP && major >= 1)) { return true; } return false; } void InstallUtil::WriteInstallerResult(bool system_install, installer_util::InstallStatus status, int string_resource_id, const std::wstring* const launch_cmd) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring key = dist->GetVersionKey(); int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1; scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList()); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult", installer_result, true); install_list->AddSetRegValueWorkItem(root, key, L"InstallerError", status, true); if (string_resource_id != 0) { std::wstring msg = installer_util::GetLocalizedString(string_resource_id); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString", msg, true); } if (launch_cmd != NULL) { install_list->AddSetRegValueWorkItem(root, key, L"InstallerSuccessLaunchCmdLine", *launch_cmd, true); } if (!install_list->Do()) LOG(ERROR) << "Failed to record installer error information in registry."; } bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) { std::wstring exe_path_copy = exe_path; wchar_t program_files_path[MAX_PATH] = {0}; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, program_files_path))) { std::wstring program_files_path_copy = program_files_path; if (std::equal(program_files_path_copy.begin(), program_files_path_copy.end(), exe_path_copy.begin(), CaseInsensitiveCompare<wchar_t>())) { return false; } } else { NOTREACHED(); } return true; }<commit_msg>Fixes a crash if you put chrome in a very short directory - like c:\bang. - it will crash at startup on a bad iterator use.<commit_after>// Copyright (c) 2006-2008 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. // // See the corresponding header file for description of the functions in this // file. #include "install_util.h" #include <algorithm> #include <shellapi.h> #include <shlobj.h> #include "base/logging.h" #include "base/registry.h" #include "base/string_util.h" #include "base/win_util.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/l10n_string_util.h" #include "chrome/installer/util/work_item_list.h" bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe, const std::wstring& params, DWORD* exit_code) { SHELLEXECUTEINFO info = {0}; info.cbSize = sizeof(SHELLEXECUTEINFO); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.lpVerb = L"runas"; info.lpFile = exe.c_str(); info.lpParameters = params.c_str(); info.nShow = SW_SHOW; if (::ShellExecuteEx(&info) == FALSE) return false; ::WaitForSingleObject(info.hProcess, INFINITE); DWORD ret_val = 0; if (!::GetExitCodeProcess(info.hProcess, &ret_val)) return false; if (exit_code) *exit_code = ret_val; return true; } std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); RegKey key(root, dist->GetUninstallRegPath().c_str()); std::wstring uninstall_cmd; key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd); return uninstall_cmd; } installer::Version* InstallUtil::GetChromeVersion(bool system_install) { RegKey key; std::wstring version_str; HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) || !key.ReadValue(google_update::kRegVersionField, &version_str)) { LOG(INFO) << "No existing Chrome install found."; key.Close(); return NULL; } key.Close(); LOG(INFO) << "Existing Chrome version found " << version_str; return installer::Version::GetVersionFromString(version_str); } bool InstallUtil::IsOSSupported() { int major, minor; win_util::WinVersion version = win_util::GetWinVersion(); win_util::GetServicePackLevel(&major, &minor); // We do not support Win2K or older, or XP without service pack 1. LOG(INFO) << "Windows Version: " << version << ", Service Pack: " << major << "." << minor; if ((version == win_util::WINVERSION_VISTA) || (version == win_util::WINVERSION_SERVER_2003) || (version == win_util::WINVERSION_XP && major >= 1)) { return true; } return false; } void InstallUtil::WriteInstallerResult(bool system_install, installer_util::InstallStatus status, int string_resource_id, const std::wstring* const launch_cmd) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring key = dist->GetVersionKey(); int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1; scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList()); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult", installer_result, true); install_list->AddSetRegValueWorkItem(root, key, L"InstallerError", status, true); if (string_resource_id != 0) { std::wstring msg = installer_util::GetLocalizedString(string_resource_id); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString", msg, true); } if (launch_cmd != NULL) { install_list->AddSetRegValueWorkItem(root, key, L"InstallerSuccessLaunchCmdLine", *launch_cmd, true); } if (!install_list->Do()) LOG(ERROR) << "Failed to record installer error information in registry."; } bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) { wchar_t program_files_path[MAX_PATH] = {0}; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, program_files_path))) { return !StartsWith(exe_path, program_files_path, false); } else { NOTREACHED(); } return true; } <|endoftext|>
<commit_before>//-*- Mode: C++ -*- // $Id: AliHLTJETConeFinder.cxx $ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * ALICE Experiment at CERN, All rights reserved. * * * * Primary Authors: Jochen Thaeder <[email protected]> * * for The ALICE HLT Project. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** @file AliHLTJETConeFinder.cxx @author Jochen Thaeder @date @brief Jet cone finder */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #if __GNUC__ >= 3 using namespace std; #endif #include "AliHLTJETReader.h" #include "AliHLTJETConeGrid.h" #include "AliHLTJETConeFinder.h" #include "AliHLTJETConeHeader.h" #include "AliHLTJETConeJetCandidate.h" #include "AliHLTJETConeEtaPhiCell.h" /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTJETConeFinder) /* * --------------------------------------------------------------------------------- * Constructor / Destructor * --------------------------------------------------------------------------------- */ // ################################################################################# AliHLTJETConeFinder::AliHLTJETConeFinder() : AliJetFinder(), fGrid(NULL), fJets(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } // ################################################################################# AliHLTJETConeFinder::~AliHLTJETConeFinder() { // see header file for class documentation } /* * --------------------------------------------------------------------------------- * Initialize * --------------------------------------------------------------------------------- */ // ################################################################################# Int_t AliHLTJETConeFinder::Initialize() { // see header file for class documentation Int_t iResult = 0; if ( !fHeader || !fReader ) { HLTError("No header or reader set!"); return -EINPROGRESS; } // -- Initialize Reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); iResult = reader->Initialize(); if ( iResult ) { HLTError( "Initializing Reader failed!"); return iResult; } // -- Initialize Header AliHLTJETConeHeader *header = dynamic_cast<AliHLTJETConeHeader*> (fHeader); iResult = header->Initialize(); if ( iResult ) { HLTError( "Initializing Header failed!"); return iResult; } // -- Set ptr to grid fGrid = reader->GetGrid(); if ( ! fGrid ) { HLTError( "Getting ptr to grid failed!"); return -EINPROGRESS; } // -- Check ptr to output container if ( !fJets ) { HLTError( "Ptr to output container not set!"); return -EINPROGRESS; } return iResult; } // ################################################################################# void AliHLTJETConeFinder::Reset() { // see header file for class documentation // -- Reset reader (dynamic_cast<AliHLTJETReader*> (fReader))->ResetEvent(); // -- Reset output container if (fJets) fJets->Reset(); return; } /* * --------------------------------------------------------------------------------- * Process * --------------------------------------------------------------------------------- */ // ################################################################################# Bool_t AliHLTJETConeFinder::ProcessEvent() { // see header file for class documentation // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Reset Reset(); // -- Fill Grid if ( !reader->FillGrid() ){ HLTError("Error filling grid."); return kFALSE; } // -- Find Leading if ( FindConeLeading() ) { HLTError("Error finding leading."); return kFALSE; } // -- Find Jets if ( FindConeJets() ) { HLTError("Error finding jets."); return kFALSE; } // -- Fill Jets and apply jet cuts if ( FillConeJets() ) { HLTError("Error filling jets."); return kFALSE; } return kTRUE; } // ################################################################################# Bool_t AliHLTJETConeFinder::ProcessConeEvent() { // see header file for class documentation // -- Find Leading if ( FindConeLeading() ) { HLTError("Error finding leading."); return kFALSE; } // -- Find Jets if ( FindConeJets() ) { HLTError("Error finding jets."); return kFALSE; } // -- Fill Jets and apply jet cuts if ( FillConeJets() ) { HLTError("Error filling jets."); return kFALSE; } return kTRUE; } /* * --------------------------------------------------------------------------------- * Process - private * --------------------------------------------------------------------------------- */ // ################################################################################# Int_t AliHLTJETConeFinder::FindConeLeading() { // see header file for class documentation // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Pick up jet canidates TClonesArray* jetCandidates = reader->GetJetCandidates(); // -- Sort jet candidates with seed pt jetCandidates->Sort(); // -- Use leading seed only // Keep index 0, remove the others if ( (dynamic_cast<AliHLTJETConeHeader*> (fHeader))->GetUseLeading() ) { for ( Int_t iter = 1; iter < reader->GetNJetCandidates(); iter++ ) jetCandidates->RemoveAt(iter); reader->SetNJetCandidates(1); } // -- Resize the seed TClonesArray jetCandidates->Compress(); return 0; } // ################################################################################# Int_t AliHLTJETConeFinder::FindConeJets() { // see header file for class documentation Int_t iResult = 0; // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Pick up jet canidates TClonesArray* jetCandidates = reader->GetJetCandidates(); // -- Loop over jet candidates for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { AliHLTJETConeJetCandidate* jet = reinterpret_cast<AliHLTJETConeJetCandidate*> ((*jetCandidates)[iter]); // -- Set iterator for cells around seed fGrid->SetCellIter( jet->GetSeedEtaIdx(), jet->GetSeedPhiIdx() ); Int_t cellIdx = 0; // -- Loop over cells around ssed while ( (cellIdx = fGrid->NextCell() ) != -1 && !iResult) { AliHLTJETConeEtaPhiCell* cell = NULL; if ( ! (cell = reinterpret_cast<AliHLTJETConeEtaPhiCell*>(fGrid->UncheckedAt(cellIdx))) ) continue; if ( ( iResult = jet->AddCell(cell) ) ) { HLTError( "Error adding cell %d to jet candiate %d", cellIdx, iter); continue; } } // while ( (cellIdx = fGrid->NextCell() ) != -1 && !iResult) { } // for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { return iResult; } // ################################################################################# Int_t AliHLTJETConeFinder::FillConeJets() { // see header file for class documentation Int_t iResult = 0; // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Pick up jet header AliHLTJETConeHeader *header = dynamic_cast<AliHLTJETConeHeader*> (fHeader); // -- Get jet canidates TClonesArray* jetCandidates = reader->GetJetCandidates(); // -- Get jet cuts AliHLTJETJetCuts* jetCuts = header->GetJetCuts(); // -- Loop over jet candidates for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { AliHLTJETConeJetCandidate* jet = reinterpret_cast<AliHLTJETConeJetCandidate*> ((*jetCandidates)[iter]); // -- Apply jet cuts if ( ! jetCuts->IsSelected(jet) ) continue; // -- Add jet as AliAODJet fJets->AddJet(jet->GetEta(), jet->GetPhi(), jet->GetPt(), jet->GetEt()); } // for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { HLTDebug( "Added %d jets", fJets->GetNAODJets()); return iResult; } <commit_msg>* fixed bug while getting leading jet candidate * better protection for grid indices<commit_after>//-*- Mode: C++ -*- // $Id: AliHLTJETConeFinder.cxx $ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * ALICE Experiment at CERN, All rights reserved. * * * * Primary Authors: Jochen Thaeder <[email protected]> * * for The ALICE HLT Project. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** @file AliHLTJETConeFinder.cxx @author Jochen Thaeder @date @brief Jet cone finder */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #if __GNUC__ >= 3 using namespace std; #endif #include "AliHLTJETReader.h" #include "AliHLTJETConeGrid.h" #include "AliHLTJETConeFinder.h" #include "AliHLTJETConeHeader.h" #include "AliHLTJETConeJetCandidate.h" #include "AliHLTJETConeEtaPhiCell.h" /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTJETConeFinder) /* * --------------------------------------------------------------------------------- * Constructor / Destructor * --------------------------------------------------------------------------------- */ // ################################################################################# AliHLTJETConeFinder::AliHLTJETConeFinder() : AliJetFinder(), fGrid(NULL), fJets(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } // ################################################################################# AliHLTJETConeFinder::~AliHLTJETConeFinder() { // see header file for class documentation } /* * --------------------------------------------------------------------------------- * Initialize * --------------------------------------------------------------------------------- */ // ################################################################################# Int_t AliHLTJETConeFinder::Initialize() { // see header file for class documentation Int_t iResult = 0; if ( !fHeader || !fReader ) { HLTError("No header or reader set!"); return -EINPROGRESS; } // -- Initialize Reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); iResult = reader->Initialize(); if ( iResult ) { HLTError( "Initializing Reader failed!"); return iResult; } // -- Initialize Header AliHLTJETConeHeader *header = dynamic_cast<AliHLTJETConeHeader*> (fHeader); iResult = header->Initialize(); if ( iResult ) { HLTError( "Initializing Header failed!"); return iResult; } // -- Set ptr to grid fGrid = reader->GetGrid(); if ( ! fGrid ) { HLTError( "Getting ptr to grid failed!"); return -EINPROGRESS; } // -- Check ptr to output container if ( !fJets ) { HLTError( "Ptr to output container not set!"); return -EINPROGRESS; } return iResult; } // ################################################################################# void AliHLTJETConeFinder::Reset() { // see header file for class documentation // -- Reset reader (dynamic_cast<AliHLTJETReader*> (fReader))->ResetEvent(); // -- Reset output container if (fJets) fJets->Reset(); return; } /* * --------------------------------------------------------------------------------- * Process * --------------------------------------------------------------------------------- */ // ################################################################################# Bool_t AliHLTJETConeFinder::ProcessEvent() { // see header file for class documentation // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Reset Reset(); // -- Fill Grid if ( !reader->FillGrid() ){ HLTError("Error filling grid."); return kFALSE; } // -- Find Leading if ( FindConeLeading() ) { HLTError("Error finding leading."); return kFALSE; } // -- Find Jets if ( FindConeJets() ) { HLTError("Error finding jets."); return kFALSE; } // -- Fill Jets and apply jet cuts if ( FillConeJets() ) { HLTError("Error filling jets."); return kFALSE; } return kTRUE; } // ################################################################################# Bool_t AliHLTJETConeFinder::ProcessConeEvent() { // see header file for class documentation // -- Find Leading if ( FindConeLeading() ) { HLTError("Error finding leading."); return kFALSE; } // -- Find Jets if ( FindConeJets() ) { HLTError("Error finding jets."); return kFALSE; } // -- Fill Jets and apply jet cuts if ( FillConeJets() ) { HLTError("Error filling jets."); return kFALSE; } return kTRUE; } /* * --------------------------------------------------------------------------------- * Process - private * --------------------------------------------------------------------------------- */ // ################################################################################# Int_t AliHLTJETConeFinder::FindConeLeading() { // see header file for class documentation // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Pick up jet canidates TClonesArray* jetCandidates = reader->GetJetCandidates(); // -- Check for more than 1 jet candidate if ( reader->GetNJetCandidates() > 1 ) { // -- Sort jet candidates with seed pt jetCandidates->Sort(); // -- Use leading seed only // Keep index 0, remove the others if ( (dynamic_cast<AliHLTJETConeHeader*> (fHeader))->GetUseLeading() ) { for ( Int_t iter = 1; iter < reader->GetNJetCandidates(); iter++ ) jetCandidates->RemoveAt(iter); reader->SetNJetCandidates(1); } } // if ( reader->GetNJetCandidates() > 1 ) { // -- Resize the seed TClonesArray jetCandidates->Compress(); return 0; } // ################################################################################# Int_t AliHLTJETConeFinder::FindConeJets() { // see header file for class documentation Int_t iResult = 0; // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Pick up jet canidates TClonesArray* jetCandidates = reader->GetJetCandidates(); // -- Loop over jet candidates for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { AliHLTJETConeJetCandidate* jet = reinterpret_cast<AliHLTJETConeJetCandidate*> ((*jetCandidates)[iter]); // -- Set iterator for cells around seed fGrid->SetCellIter( jet->GetSeedEtaIdx(), jet->GetSeedPhiIdx() ); Int_t cellIdx = 0; // -- Loop over cells around ssed while ( (cellIdx = fGrid->NextCell() ) >= 0 && !iResult) { AliHLTJETConeEtaPhiCell* cell = NULL; if ( ! (cell = reinterpret_cast<AliHLTJETConeEtaPhiCell*>(fGrid->UncheckedAt(cellIdx))) ) continue; if ( ( iResult = jet->AddCell(cell) ) ) { HLTError( "Error adding cell %d to jet candiate %d", cellIdx, iter); continue; } } // while ( (cellIdx = fGrid->NextCell() ) >= 0 && !iResult) { } // for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { return iResult; } // ################################################################################# Int_t AliHLTJETConeFinder::FillConeJets() { // see header file for class documentation Int_t iResult = 0; // -- Pick up jet reader AliHLTJETReader *reader = dynamic_cast<AliHLTJETReader*> (fReader); // -- Pick up jet header AliHLTJETConeHeader *header = dynamic_cast<AliHLTJETConeHeader*> (fHeader); // -- Get jet canidates TClonesArray* jetCandidates = reader->GetJetCandidates(); // -- Get jet cuts AliHLTJETJetCuts* jetCuts = header->GetJetCuts(); // -- Loop over jet candidates for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { AliHLTJETConeJetCandidate* jet = reinterpret_cast<AliHLTJETConeJetCandidate*> ((*jetCandidates)[iter]); // -- Apply jet cuts if ( ! jetCuts->IsSelected(jet) ) continue; // -- Add jet as AliAODJet fJets->AddJet(jet->GetEta(), jet->GetPhi(), jet->GetPt(), jet->GetEt()); } // for ( Int_t iter = 0; iter < reader->GetNJetCandidates(); iter++ ) { HLTDebug( "Added %d jets", fJets->GetNAODJets()); return iResult; } <|endoftext|>
<commit_before>// $Id$ /** * @file print-ESD-HLTdecision.C * @brief Print HLT decisions per event of ESD * * <pre> * Usage: aliroot -b -q print-ESD-HLTdecision.C * </pre> * * The input file can be a file on Grid like e.g. * "alien:///alice/data/2009/LHC09d/000104321/ESDs/pass5/09000104321018.30/AliESDs.root" * In that case you need a valid token in order to connect to the Grid. * Use 'alien-token-init' from your alien installation. * * @author [email protected] * @ingroup alihlt_programs */ int print_ESD_HLTdecision(const char* esdFileName="AliESDs.root", int minEvent=0, int maxEvent=-1) { TString strfile=esdFileName; if (strfile.Contains("://") && !strfile.Contains("local://")) { TGrid::Connect("alien"); } TFile* esdFile=NULL; if (esdFileName && esdFileName[0]!=0) esdFile=TFile::Open(esdFileName); if (!esdFileName || esdFileName[0]==0 || esdFile->IsZombie()) { if (esdFileName && esdFileName[0]!=0) cerr << "can not open esd file " << esdFileName << endl; else cerr << "print-ESD-HLTdecision.C Print HLT decisions per event of ESD" << endl; cerr << "===============================================================" << endl; cerr << "usage: aliroot -b -q -l print-ESD-HLTdecision.C'(\"AliESDs.root\" " << endl; cerr << " minEvent, maxEvent)'" << endl << endl; cerr << " Parameter:" << endl; cerr << " esdFileName default \"AliESDs.root\"" << endl; cerr << " minEvent first event (optional)" << endl; cerr << " maxEvent last event (optional)" << endl; cerr << "===============================================================" << endl; return -1; } TTree* pTree=NULL; esdFile->GetObject("esdTree", pTree); if (!pTree) { cerr << "can not find ESD tree" << endl; return -1; } AliESDEvent* esd=new AliESDEvent; esd->CreateStdContent(); esd->ReadFromTree(pTree); TTree* pHLTTree=NULL; esdFile->GetObject("HLTesdTree", pHLTTree); if (!pHLTTree) { cerr << "can not find HLT ESD tree" << endl; return -1; } if (pTree->GetEntries() != pHLTTree->GetEntries()) { cerr << "entries differ: ESD tree " << pTree->GetEntries() << " HLT ESD tree " << pHLTTree->GetEntries() << endl; } AliESDEvent* HLTesd=new AliESDEvent; HLTesd->CreateStdContent(); HLTesd->ReadFromTree(pHLTTree); for (int event=minEvent; event<pTree->GetEntries() && (maxEvent<minEvent || event<=maxEvent); event++) { pTree->GetEvent(event); pHLTTree->GetEvent(event); cout << "===================== event " << event << " ==========================" << endl; cout << "\t ESD: # in file: " << esd->GetEventNumberInFile() << " time stamp (UCT): " << esd->GetTimeStamp() << endl; cout << "\t orbit no (offline/hlt): " << esd->GetOrbitNumber() << "/" << HLTesd->GetOrbitNumber() << endl; cout << "\t bunch crossing (offline/hlt): " << esd->GetBunchCrossNumber() << "/" << HLTesd->GetBunchCrossNumber() << endl; cout << "\t tracks (offline/hlt):\t " << esd->GetNumberOfTracks() << "/"<< HLTesd->GetNumberOfTracks() << endl; cout << "\t hltESD content:" << endl; cout << "\t fired triggers:\t" << HLTesd->GetFiredTriggerClasses() << endl; cout << "\t trigger mask:\t 0x" << hex << HLTesd->GetTriggerMask() << dec << endl; cout << "\t time stamp (UCT):\t " << HLTesd->GetTimeStamp() << endl; TObject* decision=HLTesd->GetHLTTriggerDecision(); if (decision) decision->Print(); else cout << " no HLT decision found" << endl; } return 0; } <commit_msg>checking for file pointer, documentation update<commit_after>// $Id$ /** * @file print-ESD-HLTdecision.C * @brief Print HLT decisions per event of ESD * * <pre> * Usage: aliroot -b -q print-ESD-HLTdecision.C * </pre> * * The input file can be a file on Grid like e.g. * "alien:///alice/data/2009/LHC09d/000104321/ESDs/pass5/09000104321018.30/AliESDs.root" * In that case you need a valid token in order to connect to the Grid. * Use 'alien-token-init' from your alien installation. * * @author [email protected] * @ingroup alihlt_programs */ int print_ESD_HLTdecision(const char* esdFileName="AliESDs.root", int minEvent=0, int maxEvent=-1) { TString strfile=esdFileName; if (strfile.Contains("://") && !strfile.Contains("local://")) { TGrid::Connect("alien"); } TFile* esdFile=NULL; if (esdFileName && esdFileName[0]!=0) esdFile=TFile::Open(esdFileName); if (!esdFileName || esdFileName[0]==0 || !esdFile || esdFile->IsZombie()) { if (esdFileName && esdFileName[0]!=0) cerr << "can not open esd file " << esdFileName << endl; else cerr << "print-ESD-HLTdecision.C Print HLT decisions per event of ESD" << endl; cerr << "===============================================================" << endl; cerr << "usage: aliroot -b -q -l print-ESD-HLTdecision.C'(\"AliESDs.root\" " << endl; cerr << " minEvent, maxEvent)'" << endl << endl; cerr << " Parameter:" << endl; cerr << " esdFileName default \"AliESDs.root\"" << endl; cerr << " minEvent first event (optional)" << endl; cerr << " maxEvent last event (optional)" << endl << endl; cerr << " The input file can be a file on Grid like e.g." << endl; cerr << " \"alien:///alice/data/2009/LHC09d/000104321/ESDs/pass5/09000104321018.30/AliESDs.root\"" << endl; cerr << "===============================================================" << endl; return -1; } TTree* pTree=NULL; esdFile->GetObject("esdTree", pTree); if (!pTree) { cerr << "can not find ESD tree" << endl; return -1; } AliESDEvent* esd=new AliESDEvent; esd->CreateStdContent(); esd->ReadFromTree(pTree); TTree* pHLTTree=NULL; esdFile->GetObject("HLTesdTree", pHLTTree); if (!pHLTTree) { cerr << "can not find HLT ESD tree" << endl; return -1; } if (pTree->GetEntries() != pHLTTree->GetEntries()) { cerr << "entries differ: ESD tree " << pTree->GetEntries() << " HLT ESD tree " << pHLTTree->GetEntries() << endl; } AliESDEvent* HLTesd=new AliESDEvent; HLTesd->CreateStdContent(); HLTesd->ReadFromTree(pHLTTree); for (int event=minEvent; event<pTree->GetEntries() && (maxEvent<minEvent || event<=maxEvent); event++) { pTree->GetEvent(event); pHLTTree->GetEvent(event); cout << "===================== event " << event << " ==========================" << endl; cout << "\t ESD: # in file: " << esd->GetEventNumberInFile() << " time stamp (UCT): " << esd->GetTimeStamp() << endl; cout << "\t orbit no (offline/hlt): " << esd->GetOrbitNumber() << "/" << HLTesd->GetOrbitNumber() << endl; cout << "\t bunch crossing (offline/hlt): " << esd->GetBunchCrossNumber() << "/" << HLTesd->GetBunchCrossNumber() << endl; cout << "\t tracks (offline/hlt):\t " << esd->GetNumberOfTracks() << "/"<< HLTesd->GetNumberOfTracks() << endl; cout << "\t hltESD content:" << endl; cout << "\t fired triggers:\t" << HLTesd->GetFiredTriggerClasses() << endl; cout << "\t trigger mask:\t 0x" << hex << HLTesd->GetTriggerMask() << dec << endl; cout << "\t time stamp (UCT):\t " << HLTesd->GetTimeStamp() << endl; TObject* decision=HLTesd->GetHLTTriggerDecision(); if (decision) decision->Print(); else cout << " no HLT decision found" << endl; } return 0; } <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <gtest/gtest.h> #include <unordered_set> #include <boost/asio.hpp> #include <boost/filesystem.hpp> #include <boost/io/detail/quoted_manip.hpp> #include <boost/uuid/string_generator.hpp> #include <osquery/core/conversions.h> #include <osquery/tests/integration/tables/helper.h> namespace osquery { namespace fs = boost::filesystem; bool CronValuesCheck::operator()(const std::string& string) const { // Fast asterisk check, its most common if (string == "*") { return true; } // Specific value check auto cast_result = tryTo<int64_t>(string); if (cast_result) { // its int, so we can do easy validation int64_t int_value = cast_result.get(); return (int_value >= min_ && int_value <= max_); } // Check */3 format if (boost::starts_with(string, "*/")) { std::string subvalue = string.substr(2); auto subvalue_int = tryTo<int64_t>(subvalue); return subvalue_int.isValue(); } std::vector<std::string> components; boost::split(components, string, boost::is_any_of(",")); for (auto component : components) { // Predefined value check like: sun, mon boost::algorithm::to_lower(component); if (values_.find(component) != values_.end()) { continue; } // just number if (tryTo<int64_t>(component)) { continue; } std::vector<std::string> sub_components; boost::split(sub_components, component, boost::is_any_of("-")); if (sub_components.size() == 2) { if (tryTo<int64_t>(sub_components[0]) && tryTo<int64_t>(sub_components[1])) { continue; } } // sub_components.size() > 2 || sub_components.size() == 1 return false; } return true; } bool IntMinMaxCheck::operator()(const std::string& string) const { auto cast_result = tryTo<int64_t>(string); if (!cast_result) { return false; } auto const value = cast_result.get(); return value >= min_ && value <= max_; } bool SpecificValuesCheck::operator()(const std::string& string) const { return set_.find(string) != set_.end(); } bool verifyIpAddress(std::string const& value) { auto err = boost::system::error_code{}; boost::asio::ip::make_address(value, err); return !err; } QueryData IntegrationTableTest::execute_query(std::string query) { SQLInternal sql(query, false); return sql.rows(); } void IntegrationTableTest::validate_row(const Row& row, const ValidatatioMap& validation_map) { ASSERT_EQ(row.size(), validation_map.size()) << "Unexpected number of columns"; for (auto iter : validation_map) { std::string key = iter.first; auto row_data_iter = row.find(key); ASSERT_NE(row_data_iter, row.end()) << "Could not find column " << boost::io::quoted(key) << " in the generated columns"; std::string value = row_data_iter->second; ValidatatioDataType validator = iter.second; if (validator.type() == typeid(int)) { int flags = boost::get<int>(validator); ASSERT_TRUE(validate_value_using_flags(value, flags)) << "Standard validator of the column " << boost::io::quoted(key) << " with value " << boost::io::quoted(value) << " failed"; } else { ASSERT_TRUE(boost::get<CustomCheckerType>(validator)(value)) << "Custom validator of the column " << boost::io::quoted(key) << " with value " << boost::io::quoted(value) << " failed"; } } } void IntegrationTableTest::validate_rows(const std::vector<Row>& rows, const ValidatatioMap& validation_map) { for (auto row : rows) { validate_row(row, validation_map); } } bool IntegrationTableTest::is_valid_hex(const std::string& value) { for (auto ch : value) { if (!std::isxdigit(ch)) { return false; } } return true; } bool IntegrationTableTest::validate_value_using_flags(const std::string& value, int flags) { if ((flags & NonEmpty) > 0) { if (value.length() == 0) { return false; } } if ((flags & NonNull)) { if (value == "null") { return false; } } if ((flags & NonZero)) { if (value == "0") { return false; } } if ((flags & IntType) > 0) { auto cast_result = tryTo<int64_t>(value); if (!cast_result) { return false; } auto intValue = cast_result.get(); if ((flags & NonNegative) > 0) { if (intValue < 0) { return false; } } } if ((flags & FileOnDisk) > 0) { auto path = fs::path(value); auto status = fs::status(path); if (!fs::exists(status) || !fs::is_regular_file(status)) { return false; } } if ((flags & DirectoryOnDisk) > 0) { auto path = fs::path(value); auto status = fs::status(path); if (!fs::exists(status) || !fs::is_directory(status)) { return false; } } if ((flags & MD5) > 0) { if (!is_valid_hex(value) || value.size() != 32) { return false; } } if ((flags & SHA1) > 0) { if (!is_valid_hex(value) || value.size() != 40) { return false; } } if ((flags & SHA256) > 0) { if (!is_valid_hex(value) || value.size() != 64) { return false; } } if ((flags & Bool) > 0) { if (value.length() != 1 || (value != "1" && value != "0")) { return false; } } if ((flags & ValidUUID) > 0) { try { boost::uuids::string_generator()(value); } catch (...) { return false; } } return true; } } // namespace osquery <commit_msg>Make more talkative in terms of unexpected columns (#5149)<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <gtest/gtest.h> #include <unordered_set> #include <boost/asio.hpp> #include <boost/filesystem.hpp> #include <boost/io/detail/quoted_manip.hpp> #include <boost/uuid/string_generator.hpp> #include <osquery/core/conversions.h> #include <osquery/tests/integration/tables/helper.h> namespace osquery { namespace fs = boost::filesystem; bool CronValuesCheck::operator()(const std::string& string) const { // Fast asterisk check, its most common if (string == "*") { return true; } // Specific value check auto cast_result = tryTo<int64_t>(string); if (cast_result) { // its int, so we can do easy validation int64_t int_value = cast_result.get(); return (int_value >= min_ && int_value <= max_); } // Check */3 format if (boost::starts_with(string, "*/")) { std::string subvalue = string.substr(2); auto subvalue_int = tryTo<int64_t>(subvalue); return subvalue_int.isValue(); } std::vector<std::string> components; boost::split(components, string, boost::is_any_of(",")); for (auto component : components) { // Predefined value check like: sun, mon boost::algorithm::to_lower(component); if (values_.find(component) != values_.end()) { continue; } // just number if (tryTo<int64_t>(component)) { continue; } std::vector<std::string> sub_components; boost::split(sub_components, component, boost::is_any_of("-")); if (sub_components.size() == 2) { if (tryTo<int64_t>(sub_components[0]) && tryTo<int64_t>(sub_components[1])) { continue; } } // sub_components.size() > 2 || sub_components.size() == 1 return false; } return true; } bool IntMinMaxCheck::operator()(const std::string& string) const { auto cast_result = tryTo<int64_t>(string); if (!cast_result) { return false; } auto const value = cast_result.get(); return value >= min_ && value <= max_; } bool SpecificValuesCheck::operator()(const std::string& string) const { return set_.find(string) != set_.end(); } bool verifyIpAddress(std::string const& value) { auto err = boost::system::error_code{}; boost::asio::ip::make_address(value, err); return !err; } QueryData IntegrationTableTest::execute_query(std::string query) { SQLInternal sql(query, false); return sql.rows(); } void IntegrationTableTest::validate_row(const Row& row, const ValidatatioMap& validation_map) { for (auto const& rec : row) { EXPECT_NE(validation_map.count(rec.first), std::size_t{0}) << "Unexpected column " << boost::io::quoted(rec.first) << " in a row"; } for (auto iter : validation_map) { std::string key = iter.first; auto row_data_iter = row.find(key); ASSERT_NE(row_data_iter, row.end()) << "Could not find column " << boost::io::quoted(key) << " in the generated columns"; std::string value = row_data_iter->second; ValidatatioDataType validator = iter.second; if (validator.type() == typeid(int)) { int flags = boost::get<int>(validator); ASSERT_TRUE(validate_value_using_flags(value, flags)) << "Standard validator of the column " << boost::io::quoted(key) << " with value " << boost::io::quoted(value) << " failed"; } else { ASSERT_TRUE(boost::get<CustomCheckerType>(validator)(value)) << "Custom validator of the column " << boost::io::quoted(key) << " with value " << boost::io::quoted(value) << " failed"; } } } void IntegrationTableTest::validate_rows(const std::vector<Row>& rows, const ValidatatioMap& validation_map) { for (auto row : rows) { validate_row(row, validation_map); } } bool IntegrationTableTest::is_valid_hex(const std::string& value) { for (auto ch : value) { if (!std::isxdigit(ch)) { return false; } } return true; } bool IntegrationTableTest::validate_value_using_flags(const std::string& value, int flags) { if ((flags & NonEmpty) > 0) { if (value.length() == 0) { return false; } } if ((flags & NonNull)) { if (value == "null") { return false; } } if ((flags & NonZero)) { if (value == "0") { return false; } } if ((flags & IntType) > 0) { auto cast_result = tryTo<int64_t>(value); if (!cast_result) { return false; } auto intValue = cast_result.get(); if ((flags & NonNegative) > 0) { if (intValue < 0) { return false; } } } if ((flags & FileOnDisk) > 0) { auto path = fs::path(value); auto status = fs::status(path); if (!fs::exists(status) || !fs::is_regular_file(status)) { return false; } } if ((flags & DirectoryOnDisk) > 0) { auto path = fs::path(value); auto status = fs::status(path); if (!fs::exists(status) || !fs::is_directory(status)) { return false; } } if ((flags & MD5) > 0) { if (!is_valid_hex(value) || value.size() != 32) { return false; } } if ((flags & SHA1) > 0) { if (!is_valid_hex(value) || value.size() != 40) { return false; } } if ((flags & SHA256) > 0) { if (!is_valid_hex(value) || value.size() != 64) { return false; } } if ((flags & Bool) > 0) { if (value.length() != 1 || (value != "1" && value != "0")) { return false; } } if ((flags & ValidUUID) > 0) { try { boost::uuids::string_generator()(value); } catch (...) { return false; } } return true; } } // namespace osquery <|endoftext|>
<commit_before>/* OpenSceneGraph example, osgmultitexture. * * 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 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 <osg/Notify> #include <osg/Texture2D> #include <osg/io_utils> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgFX/MultiTextureControl> #include <osgGA/TerrainManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <osgTerrain/Terrain> #include <osgViewer/ViewerEventHandlers> #include <osgViewer/Viewer> #include <iostream> template<class T> class FindTopMostNodeOfTypeVisitor : public osg::NodeVisitor { public: FindTopMostNodeOfTypeVisitor(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _foundNode(0) {} void apply(osg::Node& node) { T* result = dynamic_cast<T*>(&node); if (result) { _foundNode = result; } else { traverse(node); } } T* _foundNode; }; template<class T> T* findTopMostNodeOfType(osg::Node* node) { if (!node) return 0; FindTopMostNodeOfTypeVisitor<T> fnotv; node->accept(fnotv); return fnotv._foundNode; } /** Callback used to track the elevation of the camera and update the texture weights in an MultiTextureControl node.*/ class ElevationLayerBlendingCallback : public osg::NodeCallback { public: typedef std::vector<double> Elevations; ElevationLayerBlendingCallback(osgFX::MultiTextureControl* mtc, const Elevations& elevations, float animationTime=4.0f): _previousFrame(-1), _previousTime(0.0), _currentElevation(0.0), _mtc(mtc), _elevations(elevations), _animationTime(animationTime) {} /** Callback method called by the NodeVisitor when visiting a node.*/ virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { if (nv->getVisitorType()==osg::NodeVisitor::UPDATE_VISITOR) { float deltaTime = 0.01f; if (_previousFrame!=-1) { deltaTime = float(nv->getFrameStamp()->getReferenceTime() - _previousTime); } _previousTime = nv->getFrameStamp()->getReferenceTime(); _previousFrame = nv->getFrameStamp()->getFrameNumber(); if (_mtc.valid() && !_elevations.empty()) { unsigned int index = _mtc->getNumTextureWeights()-1; for(unsigned int i=0; i<_elevations.size(); ++i) { if (_currentElevation>_elevations[i]) { index = i; break; } } float delta = std::min(deltaTime/_animationTime, 1.0f); for(unsigned int i=0; i<_mtc->getNumTextureWeights(); ++i) { float currentValue = _mtc->getTextureWeight(i); float desiredValue = (i==index) ? 1.0f : 0.0f; if (desiredValue != currentValue) { if (currentValue<desiredValue) { desiredValue = std::min(currentValue + delta, desiredValue); } else { desiredValue = std::max(currentValue - delta, desiredValue); } _mtc->setTextureWeight(i, desiredValue); } } } } else if (nv->getVisitorType()==osg::NodeVisitor::CULL_VISITOR) { _currentElevation = nv->getViewPoint().z(); osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(node); if (csn) { osg::EllipsoidModel* em = csn->getEllipsoidModel(); if (em) { double X = nv->getViewPoint().x(); double Y = nv->getViewPoint().y(); double Z = nv->getViewPoint().z(); double latitude, longitude; em->convertXYZToLatLongHeight(X,Y,Z,latitude, longitude, _currentElevation); } } } traverse(node,nv); } int _previousFrame; double _previousTime; float _animationTime; double _currentElevation; osg::observer_ptr<osgFX::MultiTextureControl> _mtc; Elevations _elevations; }; // class to handle events with a pick class TerrainHandler : public osgGA::GUIEventHandler { public: TerrainHandler(osgTerrain::Terrain* terrain): _terrain(terrain) {} bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYDOWN): { if (ea.getKey()=='r') { _terrain->setSampleRatio(_terrain->getSampleRatio()*0.5); osg::notify(osg::NOTICE)<<"Sample ratio "<<_terrain->getSampleRatio()<<std::endl; return true; } else if (ea.getKey()=='R') { _terrain->setSampleRatio(_terrain->getSampleRatio()/0.5); osg::notify(osg::NOTICE)<<"Sample ratio "<<_terrain->getSampleRatio()<<std::endl; return true; } else if (ea.getKey()=='v') { _terrain->setVerticalScale(_terrain->getVerticalScale()*1.25); osg::notify(osg::NOTICE)<<"Vertical scale "<<_terrain->getVerticalScale()<<std::endl; return true; } else if (ea.getKey()=='V') { _terrain->setVerticalScale(_terrain->getVerticalScale()/1.25); osg::notify(osg::NOTICE)<<"Vertical scale "<<_terrain->getVerticalScale()<<std::endl; return true; } return false; } default: return false; } } protected: ~TerrainHandler() {} osg::ref_ptr<osgTerrain::Terrain> _terrain; }; int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // construct the viewer. osgViewer::Viewer viewer(arguments); float verticalScale = 1.0f; while(arguments.read("-v",verticalScale)) {} float sampleRatio = 1.0f; while(arguments.read("-r",sampleRatio)) {} // add all the event handlers to the viewer { // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // add the record camera path handler viewer.addEventHandler(new osgViewer::RecordCameraPathHandler); // add the LOD Scale handler viewer.addEventHandler(new osgViewer::LODScaleHandler); } // add all the camera manipulators { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); ++keyForAnimationPath; } } keyswitchManipulator->selectMatrixManipulator(num); viewer.setCameraManipulator( keyswitchManipulator.get() ); } // set up the scene graph { // load the nodes from the commandline arguments. osg::Node* rootnode = osgDB::readNodeFiles(arguments); if (!rootnode) { osg::notify(osg::NOTICE)<<"Warning: no valid data loaded, please specify a database on the command line."<<std::endl; return 1; } osgTerrain::Terrain* terrain = findTopMostNodeOfType<osgTerrain::Terrain>(rootnode); if (!terrain) { terrain = new osgTerrain::Terrain; terrain->addChild(rootnode); rootnode = terrain; } terrain->setSampleRatio(sampleRatio); terrain->setVerticalScale(verticalScale); // register our custom handler for adjust Terrain settings viewer.addEventHandler(new TerrainHandler(terrain)); osg::CoordinateSystemNode* csn = findTopMostNodeOfType<osg::CoordinateSystemNode>(rootnode); unsigned int numLayers = 1; osgFX::MultiTextureControl* mtc = findTopMostNodeOfType<osgFX::MultiTextureControl>(rootnode); if (mtc) { numLayers = mtc->getNumTextureWeights(); } if (numLayers<2) { osg::notify(osg::NOTICE)<<"Warning: scene must have MultiTextureControl node with at least 2 texture units defined."<<std::endl; return 1; } double maxElevationTransition = 1e6; ElevationLayerBlendingCallback::Elevations elevations; for(unsigned int i=0; i<numLayers; ++i) { elevations.push_back(maxElevationTransition); maxElevationTransition /= 2.0; } ElevationLayerBlendingCallback* elbc = new ElevationLayerBlendingCallback(mtc, elevations); // assign to the most appropriate node (the CoordinateSystemNode is best as it provides the elevation on the globe.) // note we must assign callback as both an update and cull callback, as update callback to do the update of // the the osgFX::MultiTextureControl node a thread safe way, and as a cull callback to gather the camera // position information. osg::Node* nodeToAssignCallbackTo = csn ? csn : (mtc ? mtc : rootnode); nodeToAssignCallbackTo->setUpdateCallback(elbc); nodeToAssignCallbackTo->setCullCallback(elbc); // add a viewport to the viewer and attach the scene graph. viewer.setSceneData( rootnode ); } // create the windows and run the threads. viewer.realize(); return viewer.run(); } <commit_msg>Added --login <url> <username> <password> http authentication.<commit_after>/* OpenSceneGraph example, osgmultitexture. * * 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 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 <osg/Notify> #include <osg/Texture2D> #include <osg/io_utils> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgFX/MultiTextureControl> #include <osgGA/TerrainManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <osgTerrain/Terrain> #include <osgViewer/ViewerEventHandlers> #include <osgViewer/Viewer> #include <iostream> template<class T> class FindTopMostNodeOfTypeVisitor : public osg::NodeVisitor { public: FindTopMostNodeOfTypeVisitor(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _foundNode(0) {} void apply(osg::Node& node) { T* result = dynamic_cast<T*>(&node); if (result) { _foundNode = result; } else { traverse(node); } } T* _foundNode; }; template<class T> T* findTopMostNodeOfType(osg::Node* node) { if (!node) return 0; FindTopMostNodeOfTypeVisitor<T> fnotv; node->accept(fnotv); return fnotv._foundNode; } /** Callback used to track the elevation of the camera and update the texture weights in an MultiTextureControl node.*/ class ElevationLayerBlendingCallback : public osg::NodeCallback { public: typedef std::vector<double> Elevations; ElevationLayerBlendingCallback(osgFX::MultiTextureControl* mtc, const Elevations& elevations, float animationTime=4.0f): _previousFrame(-1), _previousTime(0.0), _currentElevation(0.0), _mtc(mtc), _elevations(elevations), _animationTime(animationTime) {} /** Callback method called by the NodeVisitor when visiting a node.*/ virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { if (nv->getVisitorType()==osg::NodeVisitor::UPDATE_VISITOR) { float deltaTime = 0.01f; if (_previousFrame!=-1) { deltaTime = float(nv->getFrameStamp()->getReferenceTime() - _previousTime); } _previousTime = nv->getFrameStamp()->getReferenceTime(); _previousFrame = nv->getFrameStamp()->getFrameNumber(); if (_mtc.valid() && !_elevations.empty()) { unsigned int index = _mtc->getNumTextureWeights()-1; for(unsigned int i=0; i<_elevations.size(); ++i) { if (_currentElevation>_elevations[i]) { index = i; break; } } float delta = std::min(deltaTime/_animationTime, 1.0f); for(unsigned int i=0; i<_mtc->getNumTextureWeights(); ++i) { float currentValue = _mtc->getTextureWeight(i); float desiredValue = (i==index) ? 1.0f : 0.0f; if (desiredValue != currentValue) { if (currentValue<desiredValue) { desiredValue = std::min(currentValue + delta, desiredValue); } else { desiredValue = std::max(currentValue - delta, desiredValue); } _mtc->setTextureWeight(i, desiredValue); } } } } else if (nv->getVisitorType()==osg::NodeVisitor::CULL_VISITOR) { _currentElevation = nv->getViewPoint().z(); osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(node); if (csn) { osg::EllipsoidModel* em = csn->getEllipsoidModel(); if (em) { double X = nv->getViewPoint().x(); double Y = nv->getViewPoint().y(); double Z = nv->getViewPoint().z(); double latitude, longitude; em->convertXYZToLatLongHeight(X,Y,Z,latitude, longitude, _currentElevation); } } } traverse(node,nv); } int _previousFrame; double _previousTime; float _animationTime; double _currentElevation; osg::observer_ptr<osgFX::MultiTextureControl> _mtc; Elevations _elevations; }; // class to handle events with a pick class TerrainHandler : public osgGA::GUIEventHandler { public: TerrainHandler(osgTerrain::Terrain* terrain): _terrain(terrain) {} bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYDOWN): { if (ea.getKey()=='r') { _terrain->setSampleRatio(_terrain->getSampleRatio()*0.5); osg::notify(osg::NOTICE)<<"Sample ratio "<<_terrain->getSampleRatio()<<std::endl; return true; } else if (ea.getKey()=='R') { _terrain->setSampleRatio(_terrain->getSampleRatio()/0.5); osg::notify(osg::NOTICE)<<"Sample ratio "<<_terrain->getSampleRatio()<<std::endl; return true; } else if (ea.getKey()=='v') { _terrain->setVerticalScale(_terrain->getVerticalScale()*1.25); osg::notify(osg::NOTICE)<<"Vertical scale "<<_terrain->getVerticalScale()<<std::endl; return true; } else if (ea.getKey()=='V') { _terrain->setVerticalScale(_terrain->getVerticalScale()/1.25); osg::notify(osg::NOTICE)<<"Vertical scale "<<_terrain->getVerticalScale()<<std::endl; return true; } return false; } default: return false; } } protected: ~TerrainHandler() {} osg::ref_ptr<osgTerrain::Terrain> _terrain; }; int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->addCommandLineOption("-v","Set the terrain vertical scale."); arguments.getApplicationUsage()->addCommandLineOption("-r","Set the terrain sample ratio."); arguments.getApplicationUsage()->addCommandLineOption("--login <url> <username> <password>","Provide authentication information for http file access."); // construct the viewer. osgViewer::Viewer viewer(arguments); float verticalScale = 1.0f; while(arguments.read("-v",verticalScale)) {} float sampleRatio = 1.0f; while(arguments.read("-r",sampleRatio)) {} std::string url, username, password; while(arguments.read("--login",url, username, password)) { if (!osgDB::Registry::instance()->getAuthenticationMap()) { osgDB::Registry::instance()->setAuthenticationMap(new osgDB::AuthenticationMap); osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails( url, new osgDB::AuthenticationDetails(username, password) ); } } // add all the event handlers to the viewer { // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // add the record camera path handler viewer.addEventHandler(new osgViewer::RecordCameraPathHandler); // add the LOD Scale handler viewer.addEventHandler(new osgViewer::LODScaleHandler); } // add all the camera manipulators { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); ++keyForAnimationPath; } } keyswitchManipulator->selectMatrixManipulator(num); viewer.setCameraManipulator( keyswitchManipulator.get() ); } // set up the scene graph { // load the nodes from the commandline arguments. osg::Node* rootnode = osgDB::readNodeFiles(arguments); if (!rootnode) { osg::notify(osg::NOTICE)<<"Warning: no valid data loaded, please specify a database on the command line."<<std::endl; return 1; } osgTerrain::Terrain* terrain = findTopMostNodeOfType<osgTerrain::Terrain>(rootnode); if (!terrain) { terrain = new osgTerrain::Terrain; terrain->addChild(rootnode); rootnode = terrain; } terrain->setSampleRatio(sampleRatio); terrain->setVerticalScale(verticalScale); // register our custom handler for adjust Terrain settings viewer.addEventHandler(new TerrainHandler(terrain)); osg::CoordinateSystemNode* csn = findTopMostNodeOfType<osg::CoordinateSystemNode>(rootnode); unsigned int numLayers = 1; osgFX::MultiTextureControl* mtc = findTopMostNodeOfType<osgFX::MultiTextureControl>(rootnode); if (mtc) { numLayers = mtc->getNumTextureWeights(); } if (numLayers<2) { osg::notify(osg::NOTICE)<<"Warning: scene must have MultiTextureControl node with at least 2 texture units defined."<<std::endl; return 1; } double maxElevationTransition = 1e6; ElevationLayerBlendingCallback::Elevations elevations; for(unsigned int i=0; i<numLayers; ++i) { elevations.push_back(maxElevationTransition); maxElevationTransition /= 2.0; } ElevationLayerBlendingCallback* elbc = new ElevationLayerBlendingCallback(mtc, elevations); // assign to the most appropriate node (the CoordinateSystemNode is best as it provides the elevation on the globe.) // note we must assign callback as both an update and cull callback, as update callback to do the update of // the the osgFX::MultiTextureControl node a thread safe way, and as a cull callback to gather the camera // position information. osg::Node* nodeToAssignCallbackTo = csn ? csn : (mtc ? mtc : rootnode); nodeToAssignCallbackTo->setUpdateCallback(elbc); nodeToAssignCallbackTo->setCullCallback(elbc); // add a viewport to the viewer and attach the scene graph. viewer.setSceneData( rootnode ); } // create the windows and run the threads. viewer.realize(); return viewer.run(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDescriptiveStatistics.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkToolkits.h" #include "vtkDescriptiveStatistics.h" #include "vtkUnivariateStatisticsAlgorithmPrivate.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include "vtkStdString.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include <vtkstd/set> vtkCxxRevisionMacro(vtkDescriptiveStatistics, "1.23"); vtkStandardNewMacro(vtkDescriptiveStatistics); // ---------------------------------------------------------------------- vtkDescriptiveStatistics::vtkDescriptiveStatistics() { this->MultiplicativeFactor = 1.; } // ---------------------------------------------------------------------- vtkDescriptiveStatistics::~vtkDescriptiveStatistics() { } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::PrintSelf( ostream &os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::ExecuteLearn( vtkTable* dataset, vtkTable* output, bool finalize ) { vtkIdType nCol = dataset->GetNumberOfColumns(); if ( ! nCol ) { this->SampleSize = 0; return; } this->SampleSize = dataset->GetNumberOfRows(); if ( ! this->SampleSize ) { return; } this->Internals->EffectColumnBuffer(); this->SetColumnSelection( dataset ); if ( ! this->Internals->SelectedColumns.size() ) { return; } vtkStringArray* stringCol = vtkStringArray::New(); stringCol->SetName( "Variable" ); output->AddColumn( stringCol ); stringCol->Delete(); vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Minimum" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Maximum" ); output->AddColumn( doubleCol ); doubleCol->Delete(); if ( finalize ) { doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Mean" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Standard Deviation" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Variance" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Skewness" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sample Kurtosis" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "G2 Kurtosis" ); output->AddColumn( doubleCol ); doubleCol->Delete(); } else { doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x2" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x3" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x4" ); output->AddColumn( doubleCol ); doubleCol->Delete(); vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Cardinality" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); } for ( vtkstd::set<vtkStdString>::iterator it = this->Internals->SelectedColumns.begin(); it != this->Internals->SelectedColumns.end(); ++ it ) { vtkStdString col = *it; if ( ! dataset->GetColumnByName( col ) ) { vtkWarningMacro( "Dataset table does not have a column "<<col.c_str()<<". Ignoring it." ); continue; } double minVal = dataset->GetValueByName( 0, col ).ToDouble(); double maxVal = minVal; double val = 0.; double val2 = 0.; double sum1 = 0.; double sum2 = 0.; double sum3 = 0.; double sum4 = 0.; for ( vtkIdType r = 0; r < this->SampleSize; ++ r ) { val = dataset->GetValueByName( r, col ).ToDouble(); val2 = val * val; sum1 += val; sum2 += val2; sum3 += val2 * val; sum4 += val2 * val2; if ( val < minVal ) { minVal = val; } else if ( val > maxVal ) { maxVal = val; } } vtkVariantArray* row = vtkVariantArray::New(); if ( finalize ) { double sd; double G2; this->CalculateFromSums( this->SampleSize, sum1, sum2, sum3, sum4, sd, G2 ); row->SetNumberOfValues( 9 ); row->SetValue( 0, col ); row->SetValue( 1, minVal ); row->SetValue( 2, maxVal ); row->SetValue( 3, sum1 ); row->SetValue( 4, sd ); row->SetValue( 5, sum2 ); row->SetValue( 6, sum3 ); row->SetValue( 7, sum4 ); row->SetValue( 8, G2 ); } else { row->SetNumberOfValues( 8 ); row->SetValue( 0, col ); row->SetValue( 1, minVal ); row->SetValue( 2, maxVal ); row->SetValue( 3, sum1 ); row->SetValue( 4, sum2 ); row->SetValue( 5, sum3 ); row->SetValue( 6, sum4 ); row->SetValue( 7, this->SampleSize ); } output->InsertNextRow( row ); row->Delete(); } return; } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::ExecuteValidate( vtkTable*, vtkTable*, vtkTable* ) { // Not implemented for this statistical engine } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::ExecuteEvince( vtkTable* dataset, vtkTable* params, vtkTable* output) { vtkIdType nColD = dataset->GetNumberOfColumns(); if ( ! nColD ) { return; } vtkIdType nRowD = dataset->GetNumberOfRows(); if ( ! nRowD ) { return; } vtkIdType nColP = params->GetNumberOfColumns(); if ( nColP < 3 ) { vtkWarningMacro( "Parameter table has " << nColP << " < 3 columns. Doing nothing." ); return; } vtkIdType nRowP = params->GetNumberOfRows(); if ( ! nRowP ) { return; } this->Internals->EffectColumnBuffer(); this->SetColumnSelection( dataset ); if ( ! this->Internals->SelectedColumns.size() ) { return; } vtkStringArray* stringCol = vtkStringArray::New(); stringCol->SetName( "Variable" ); output->AddColumn( stringCol ); stringCol->Delete(); vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Row" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Relative Deviation" ); output->AddColumn( doubleCol ); doubleCol->Delete(); vtkVariantArray* row = vtkVariantArray::New(); row->SetNumberOfValues( 3 ); for ( vtkstd::set<vtkStdString>::iterator it = this->Internals->SelectedColumns.begin(); it != this->Internals->SelectedColumns.end(); ++ it ) { vtkStdString col = *it; if ( ! dataset->GetColumnByName( col ) ) { vtkWarningMacro( "Dataset table does not have a column "<<col.c_str()<<". Ignoring it." ); continue; } bool unfound = true; for ( int i = 0; i < nRowP; ++ i ) { if ( params->GetValue( i, 0 ).ToString() == col ) { unfound = false; double nominal = params->GetValueByName( i, "Mean" ).ToDouble(); double deviation = params->GetValueByName( i, "Standard Deviation" ).ToDouble(); double threshold = this->MultiplicativeFactor * deviation; double minimum = nominal - threshold; double maximum = nominal + threshold; double value; for ( vtkIdType r = 0; r < nRowD; ++ r ) { value = dataset->GetValueByName( r, col ).ToDouble(); if ( value < minimum || value > maximum ) { row->SetValue( 0, col ); row->SetValue( 1, r ); if ( deviation != 0. ) { row->SetValue( 2, ( value - nominal ) / deviation ); } else { row->SetValue( 2, 0. ); } output->InsertNextRow( row ); } } break; } } if ( unfound ) { vtkWarningMacro( "Parameter table does not have a row for dataset table column " <<col.c_str() <<". Ignoring it." ); continue; } } row->Delete(); return; } // ---------------------------------------------------------------------- int vtkDescriptiveStatistics::CalculateFromSums( int n, double& s1, double& s2, double& s3, double& s4, double& sd, double& G2 ) { if ( n < 1 ) { return -1; } double nd = static_cast<double>( n ); // (unbiased) estimation of the mean s1 /= nd; if ( n == 1 ) { s2 = 0.; sd = 0.; s3 = 0.; s4 = 0.; G2 = 0.; return 1; } // (unbiased) estimation of the variance double nm1 = nd - 1.; double s1p2 = s1 * s1; double var = ( s2 - s1p2 * nd ) / nm1; if ( var > 0. ) { // sample estimation of the kurtosis "excess" s4 = ( s4 / nd - 4. * s1 * s3 / nd + 6. * s1p2 * s2 / nd - 3. * s1p2 * s1p2 ) / ( var * var ) - 3.; // sample estimation of the skewness s3 = ( s3 / nd - 3. * s1 * s2 / nd + 2. * s1p2 * s1 ) / pow( var, 1.5 ); s2 = var; sd = sqrt( s2 ); } else { s2 = var; sd = 0.; s3 = 0.; s4 = 0.; G2 = 0.; return 1; } // G2 estimation of the kurtosis "excess" if ( n > 3 ) { G2 = ( ( nd + 1. ) * s4 + 6. ) * nm1 / ( ( nd - 2. ) * ( nd - 3. ) ); return 0; } else { G2 = s4; return 1; } } <commit_msg>ENH: include the MultiplicativeFactor ivar in PrintSelf().<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDescriptiveStatistics.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkToolkits.h" #include "vtkDescriptiveStatistics.h" #include "vtkUnivariateStatisticsAlgorithmPrivate.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include "vtkStdString.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include <vtkstd/set> vtkCxxRevisionMacro(vtkDescriptiveStatistics, "1.24"); vtkStandardNewMacro(vtkDescriptiveStatistics); // ---------------------------------------------------------------------- vtkDescriptiveStatistics::vtkDescriptiveStatistics() { this->MultiplicativeFactor = 1.; } // ---------------------------------------------------------------------- vtkDescriptiveStatistics::~vtkDescriptiveStatistics() { } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::PrintSelf( ostream &os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "MultiplicativeFactor: " << this->MultiplicativeFactor << endl; } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::ExecuteLearn( vtkTable* dataset, vtkTable* output, bool finalize ) { vtkIdType nCol = dataset->GetNumberOfColumns(); if ( ! nCol ) { this->SampleSize = 0; return; } this->SampleSize = dataset->GetNumberOfRows(); if ( ! this->SampleSize ) { return; } this->Internals->EffectColumnBuffer(); this->SetColumnSelection( dataset ); if ( ! this->Internals->SelectedColumns.size() ) { return; } vtkStringArray* stringCol = vtkStringArray::New(); stringCol->SetName( "Variable" ); output->AddColumn( stringCol ); stringCol->Delete(); vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Minimum" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Maximum" ); output->AddColumn( doubleCol ); doubleCol->Delete(); if ( finalize ) { doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Mean" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Standard Deviation" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Variance" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Skewness" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sample Kurtosis" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "G2 Kurtosis" ); output->AddColumn( doubleCol ); doubleCol->Delete(); } else { doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x2" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x3" ); output->AddColumn( doubleCol ); doubleCol->Delete(); doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Sum x4" ); output->AddColumn( doubleCol ); doubleCol->Delete(); vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Cardinality" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); } for ( vtkstd::set<vtkStdString>::iterator it = this->Internals->SelectedColumns.begin(); it != this->Internals->SelectedColumns.end(); ++ it ) { vtkStdString col = *it; if ( ! dataset->GetColumnByName( col ) ) { vtkWarningMacro( "Dataset table does not have a column "<<col.c_str()<<". Ignoring it." ); continue; } double minVal = dataset->GetValueByName( 0, col ).ToDouble(); double maxVal = minVal; double val = 0.; double val2 = 0.; double sum1 = 0.; double sum2 = 0.; double sum3 = 0.; double sum4 = 0.; for ( vtkIdType r = 0; r < this->SampleSize; ++ r ) { val = dataset->GetValueByName( r, col ).ToDouble(); val2 = val * val; sum1 += val; sum2 += val2; sum3 += val2 * val; sum4 += val2 * val2; if ( val < minVal ) { minVal = val; } else if ( val > maxVal ) { maxVal = val; } } vtkVariantArray* row = vtkVariantArray::New(); if ( finalize ) { double sd; double G2; this->CalculateFromSums( this->SampleSize, sum1, sum2, sum3, sum4, sd, G2 ); row->SetNumberOfValues( 9 ); row->SetValue( 0, col ); row->SetValue( 1, minVal ); row->SetValue( 2, maxVal ); row->SetValue( 3, sum1 ); row->SetValue( 4, sd ); row->SetValue( 5, sum2 ); row->SetValue( 6, sum3 ); row->SetValue( 7, sum4 ); row->SetValue( 8, G2 ); } else { row->SetNumberOfValues( 8 ); row->SetValue( 0, col ); row->SetValue( 1, minVal ); row->SetValue( 2, maxVal ); row->SetValue( 3, sum1 ); row->SetValue( 4, sum2 ); row->SetValue( 5, sum3 ); row->SetValue( 6, sum4 ); row->SetValue( 7, this->SampleSize ); } output->InsertNextRow( row ); row->Delete(); } return; } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::ExecuteValidate( vtkTable*, vtkTable*, vtkTable* ) { // Not implemented for this statistical engine } // ---------------------------------------------------------------------- void vtkDescriptiveStatistics::ExecuteEvince( vtkTable* dataset, vtkTable* params, vtkTable* output) { vtkIdType nColD = dataset->GetNumberOfColumns(); if ( ! nColD ) { return; } vtkIdType nRowD = dataset->GetNumberOfRows(); if ( ! nRowD ) { return; } vtkIdType nColP = params->GetNumberOfColumns(); if ( nColP < 3 ) { vtkWarningMacro( "Parameter table has " << nColP << " < 3 columns. Doing nothing." ); return; } vtkIdType nRowP = params->GetNumberOfRows(); if ( ! nRowP ) { return; } this->Internals->EffectColumnBuffer(); this->SetColumnSelection( dataset ); if ( ! this->Internals->SelectedColumns.size() ) { return; } vtkStringArray* stringCol = vtkStringArray::New(); stringCol->SetName( "Variable" ); output->AddColumn( stringCol ); stringCol->Delete(); vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New(); idTypeCol->SetName( "Row" ); output->AddColumn( idTypeCol ); idTypeCol->Delete(); vtkDoubleArray* doubleCol = vtkDoubleArray::New(); doubleCol->SetName( "Relative Deviation" ); output->AddColumn( doubleCol ); doubleCol->Delete(); vtkVariantArray* row = vtkVariantArray::New(); row->SetNumberOfValues( 3 ); for ( vtkstd::set<vtkStdString>::iterator it = this->Internals->SelectedColumns.begin(); it != this->Internals->SelectedColumns.end(); ++ it ) { vtkStdString col = *it; if ( ! dataset->GetColumnByName( col ) ) { vtkWarningMacro( "Dataset table does not have a column "<<col.c_str()<<". Ignoring it." ); continue; } bool unfound = true; for ( int i = 0; i < nRowP; ++ i ) { if ( params->GetValue( i, 0 ).ToString() == col ) { unfound = false; double nominal = params->GetValueByName( i, "Mean" ).ToDouble(); double deviation = params->GetValueByName( i, "Standard Deviation" ).ToDouble(); double threshold = this->MultiplicativeFactor * deviation; double minimum = nominal - threshold; double maximum = nominal + threshold; double value; for ( vtkIdType r = 0; r < nRowD; ++ r ) { value = dataset->GetValueByName( r, col ).ToDouble(); if ( value < minimum || value > maximum ) { row->SetValue( 0, col ); row->SetValue( 1, r ); if ( deviation != 0. ) { row->SetValue( 2, ( value - nominal ) / deviation ); } else { row->SetValue( 2, 0. ); } output->InsertNextRow( row ); } } break; } } if ( unfound ) { vtkWarningMacro( "Parameter table does not have a row for dataset table column " <<col.c_str() <<". Ignoring it." ); continue; } } row->Delete(); return; } // ---------------------------------------------------------------------- int vtkDescriptiveStatistics::CalculateFromSums( int n, double& s1, double& s2, double& s3, double& s4, double& sd, double& G2 ) { if ( n < 1 ) { return -1; } double nd = static_cast<double>( n ); // (unbiased) estimation of the mean s1 /= nd; if ( n == 1 ) { s2 = 0.; sd = 0.; s3 = 0.; s4 = 0.; G2 = 0.; return 1; } // (unbiased) estimation of the variance double nm1 = nd - 1.; double s1p2 = s1 * s1; double var = ( s2 - s1p2 * nd ) / nm1; if ( var > 0. ) { // sample estimation of the kurtosis "excess" s4 = ( s4 / nd - 4. * s1 * s3 / nd + 6. * s1p2 * s2 / nd - 3. * s1p2 * s1p2 ) / ( var * var ) - 3.; // sample estimation of the skewness s3 = ( s3 / nd - 3. * s1 * s2 / nd + 2. * s1p2 * s1 ) / pow( var, 1.5 ); s2 = var; sd = sqrt( s2 ); } else { s2 = var; sd = 0.; s3 = 0.; s4 = 0.; G2 = 0.; return 1; } // G2 estimation of the kurtosis "excess" if ( n > 3 ) { G2 = ( ( nd + 1. ) * s4 + 6. ) * nm1 / ( ( nd - 2. ) * ( nd - 3. ) ); return 0; } else { G2 = s4; return 1; } } <|endoftext|>
<commit_before>/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * 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 <string> #include <sstream> #include "LIEF/visitors/Hash.hpp" #include "LIEF/PE/signature/AuthenticatedAttributes.hpp" #include "pyPE.hpp" template<class T> using getter_t = T (AuthenticatedAttributes::*)(void) const; template<class T> using setter_t = void (AuthenticatedAttributes::*)(T); void init_PE_AuthenticatedAttributes_class(py::module& m) { py::class_<AuthenticatedAttributes>(m, "AuthenticatedAttributes") .def_property_readonly("content_type", &AuthenticatedAttributes::content_type, "Should return the ``messageDigest`` OID") .def_property_readonly("message_digest", &AuthenticatedAttributes::message_digest, "Return an hash of the signed attributes") .def_property_readonly("program_name", &AuthenticatedAttributes::program_name, "Return the program description (if any)") .def_property_readonly("more_info", &AuthenticatedAttributes::more_info, "Return an URL to website with more information about the signer") .def("__str__", [] (const AuthenticatedAttributes& authenticated_attributes) { std::ostringstream stream; stream << authenticated_attributes; std::string str = stream.str(); return str; }); } <commit_msg>Fix error with unicode<commit_after>/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * 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 <string> #include <sstream> #include "LIEF/visitors/Hash.hpp" #include "LIEF/PE/signature/AuthenticatedAttributes.hpp" #include "pyPE.hpp" template<class T> using getter_t = T (AuthenticatedAttributes::*)(void) const; template<class T> using setter_t = void (AuthenticatedAttributes::*)(T); void init_PE_AuthenticatedAttributes_class(py::module& m) { py::class_<AuthenticatedAttributes>(m, "AuthenticatedAttributes") .def_property_readonly("content_type", &AuthenticatedAttributes::content_type, "Should return the ``messageDigest`` OID") .def_property_readonly("message_digest", &AuthenticatedAttributes::message_digest, "Return an hash of the signed attributes") .def_property_readonly("program_name", [] (const AuthenticatedAttributes& authenticated_attributes) { return u16tou8(authenticated_attributes.program_name()); }, "Return the program description (if any)") .def_property_readonly("more_info", &AuthenticatedAttributes::more_info, "Return an URL to website with more information about the signer") .def("__str__", [] (const AuthenticatedAttributes& authenticated_attributes) { std::ostringstream stream; stream << authenticated_attributes; std::string str = stream.str(); return str; }); } <|endoftext|>
<commit_before>/* Copyright (C) 2001 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "picview.h" CS_IMPLEMENT_APPLICATION //--------------------------------------------------------------------------- PicView::PicView () { SetApplicationName ("PicView"); pic = 0; gui = 0; scale = false; } PicView::~PicView () { } void PicView::ProcessFrame () { iGraphics2D* g2d = g3d->GetDriver2D (); if (g2d->GetHeight() != y || g2d->GetWidth() != x) { x = g2d->GetWidth(); y = g2d->GetHeight(); aws->SetupCanvas(0, g3d->GetDriver2D (), g3d); if (gui) gui->MoveTo(g2d->GetWidth ()/2-100, 0); } if (!g3d->BeginDraw (CSDRAW_2DGRAPHICS)) return; g2d->Clear(0); if (pic) { if (scale) pic->DrawScaled(g3d, 0, 0, g2d->GetWidth (), g2d->GetHeight ()); else pic->Draw(g3d, 0, 0); } aws->Redraw (); aws->Print (g3d, 64); } void PicView::FinishFrame () { g3d->FinishDraw (); g3d->Print (0); } bool PicView::OnKeyboard(iEvent& ev) { csKeyEventType eventtype = csKeyEventHelper::GetEventType(&ev); if (eventtype == csKeyEventTypeDown) { utf32_char code = csKeyEventHelper::GetCookedCode(&ev); if (code == CSKEY_ESC || code == 'q') { ButtonQuit(this, 0); } else if (code == 'f') { ButtonFirst(this, 0); } else if (code == 'p') { ButtonPrev(this, 0); } else if (code == 'n') { ButtonNext(this, 0); } else if (code == 's') { ButtonScale(this, 0); } } return false; } bool PicView::HandleEvent (iEvent &ev) { csBaseEventHandler::HandleEvent(ev); if (aws) return aws->HandleEvent (ev); return false; } bool PicView::OnInitialize(int argc, char* argv[]) { if (!csInitializer::RequestPlugins(GetObjectRegistry(), CS_REQUEST_VFS, CS_REQUEST_OPENGL3D, CS_REQUEST_ENGINE, CS_REQUEST_FONTSERVER, CS_REQUEST_IMAGELOADER, CS_REQUEST_REPORTER, CS_REQUEST_REPORTERLISTENER, CS_REQUEST_PLUGIN("crystalspace.window.alternatemanager", iAws), CS_REQUEST_END)) return ReportError("Failed to initialize plugins!"); if (!RegisterQueue(GetObjectRegistry())) return ReportError("Failed to set up event handler!"); return true; } void PicView::OnExit() { } bool PicView::Application() { if (!OpenApplication(GetObjectRegistry())) return ReportError("Error opening system!"); g3d = CS_QUERY_REGISTRY(GetObjectRegistry(), iGraphics3D); if (!g3d) return ReportError("Failed to locate 3D renderer!"); engine = CS_QUERY_REGISTRY(GetObjectRegistry(), iEngine); if (!engine) return ReportError("Failed to locate 3D engine!"); kbd = CS_QUERY_REGISTRY(GetObjectRegistry(), iKeyboardDriver); if (!kbd) return ReportError("Failed to locate Keyboard Driver!"); vfs = CS_QUERY_REGISTRY(GetObjectRegistry(), iVFS); if (!vfs) return ReportError("Failed to locate Image Loader!"); imgloader = CS_QUERY_REGISTRY(GetObjectRegistry(), iImageIO); if (!imgloader) return ReportError("Failed to locate Image Loader!"); aws = CS_QUERY_REGISTRY(GetObjectRegistry(), iAws); if (!aws) return ReportError("Failed to locate Alternative WindowingSystem!"); vfs->ChDir ("/tmp"); files = vfs->FindFiles ("/this/*"); cur_idx = 0; CreateGui(); x = g3d->GetDriver2D ()->GetWidth (); y = g3d->GetDriver2D ()->GetHeight (); Run(); return true; } void PicView::CreateGui () { aws->SetupCanvas(0, g3d->GetDriver2D (), g3d); iAwsSink* sink = aws->GetSinkMgr ()->CreateSink ((void*)this); sink->RegisterTrigger ("First", &ButtonFirst); sink->RegisterTrigger ("Prev" , &ButtonPrev ); sink->RegisterTrigger ("Next" , &ButtonNext ); sink->RegisterTrigger ("Quit" , &ButtonQuit ); sink->RegisterTrigger ("Scale", &ButtonScale); aws->GetSinkMgr ()->RegisterSink ("PicView", sink); if (!aws->GetPrefMgr()->Load ("/aws/windows_skin.def")) ReportError("couldn't load skin definition file!"); if (!aws->GetPrefMgr()->Load ("/varia/picview.def")) ReportError("couldn't load definition file!"); aws->GetPrefMgr ()->SelectDefaultSkin ("Windows"); gui = aws->CreateWindowFrom ("PicView"); if (gui) { gui->MoveTo(g3d->GetDriver2D ()->GetWidth ()/2-100, 0); gui->Show (); } } void PicView::LoadNextImage (int idx, int step) { iTextureManager* txtmgr = g3d->GetTextureManager(); if (idx) cur_idx = idx; cur_idx += step; if (cur_idx < 0) cur_idx = files->Length ()-1; if ((size_t)cur_idx >= files->Length ()) cur_idx = 0; csRef<iDataBuffer> buf (vfs->ReadFile (files->Get (cur_idx))); if (!buf) return; csRef<iImage> ifile (imgloader->Load (buf->GetUint8 (), buf->GetSize (), txtmgr->GetTextureFormat ())); if (!ifile) return; delete pic; txt = txtmgr->RegisterTexture (ifile, CS_TEXTURE_2D | CS_TEXTURE_DITHER); pic = new csSimplePixmap (txt); } //--------------------------------------------------------------------------- void PicView::ButtonFirst(void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->LoadNextImage (1, -1); } void PicView::ButtonPrev (void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->LoadNextImage (0, -1); } void PicView::ButtonNext (void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->LoadNextImage (0, 1); } void PicView::ButtonQuit (void* app, iAwsSource *source) { PicView* picview = (PicView*)app; csRef<iEventQueue> q = CS_QUERY_REGISTRY(GetObjectRegistry(), iEventQueue); if (q.IsValid()) q->GetEventOutlet()->Broadcast(cscmdQuit); } void PicView::ButtonScale (void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->scale ^= true; } /*-------------------------------------------------------------------------* * Main function *-------------------------------------------------------------------------*/ int main (int argc, char* argv[]) { return PicView().Main(argc, argv); } <commit_msg>Eliminated compilation warning.<commit_after>/* Copyright (C) 2001 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "picview.h" CS_IMPLEMENT_APPLICATION //--------------------------------------------------------------------------- PicView::PicView () { SetApplicationName ("PicView"); pic = 0; gui = 0; scale = false; } PicView::~PicView () { } void PicView::ProcessFrame () { iGraphics2D* g2d = g3d->GetDriver2D (); if (g2d->GetHeight() != y || g2d->GetWidth() != x) { x = g2d->GetWidth(); y = g2d->GetHeight(); aws->SetupCanvas(0, g3d->GetDriver2D (), g3d); if (gui) gui->MoveTo(g2d->GetWidth ()/2-100, 0); } if (!g3d->BeginDraw (CSDRAW_2DGRAPHICS)) return; g2d->Clear(0); if (pic) { if (scale) pic->DrawScaled(g3d, 0, 0, g2d->GetWidth (), g2d->GetHeight ()); else pic->Draw(g3d, 0, 0); } aws->Redraw (); aws->Print (g3d, 64); } void PicView::FinishFrame () { g3d->FinishDraw (); g3d->Print (0); } bool PicView::OnKeyboard(iEvent& ev) { csKeyEventType eventtype = csKeyEventHelper::GetEventType(&ev); if (eventtype == csKeyEventTypeDown) { utf32_char code = csKeyEventHelper::GetCookedCode(&ev); if (code == CSKEY_ESC || code == 'q') { ButtonQuit(this, 0); } else if (code == 'f') { ButtonFirst(this, 0); } else if (code == 'p') { ButtonPrev(this, 0); } else if (code == 'n') { ButtonNext(this, 0); } else if (code == 's') { ButtonScale(this, 0); } } return false; } bool PicView::HandleEvent (iEvent &ev) { csBaseEventHandler::HandleEvent(ev); if (aws) return aws->HandleEvent (ev); return false; } bool PicView::OnInitialize(int argc, char* argv[]) { if (!csInitializer::RequestPlugins(GetObjectRegistry(), CS_REQUEST_VFS, CS_REQUEST_OPENGL3D, CS_REQUEST_ENGINE, CS_REQUEST_FONTSERVER, CS_REQUEST_IMAGELOADER, CS_REQUEST_REPORTER, CS_REQUEST_REPORTERLISTENER, CS_REQUEST_PLUGIN("crystalspace.window.alternatemanager", iAws), CS_REQUEST_END)) return ReportError("Failed to initialize plugins!"); if (!RegisterQueue(GetObjectRegistry())) return ReportError("Failed to set up event handler!"); return true; } void PicView::OnExit() { } bool PicView::Application() { if (!OpenApplication(GetObjectRegistry())) return ReportError("Error opening system!"); g3d = CS_QUERY_REGISTRY(GetObjectRegistry(), iGraphics3D); if (!g3d) return ReportError("Failed to locate 3D renderer!"); engine = CS_QUERY_REGISTRY(GetObjectRegistry(), iEngine); if (!engine) return ReportError("Failed to locate 3D engine!"); kbd = CS_QUERY_REGISTRY(GetObjectRegistry(), iKeyboardDriver); if (!kbd) return ReportError("Failed to locate Keyboard Driver!"); vfs = CS_QUERY_REGISTRY(GetObjectRegistry(), iVFS); if (!vfs) return ReportError("Failed to locate Image Loader!"); imgloader = CS_QUERY_REGISTRY(GetObjectRegistry(), iImageIO); if (!imgloader) return ReportError("Failed to locate Image Loader!"); aws = CS_QUERY_REGISTRY(GetObjectRegistry(), iAws); if (!aws) return ReportError("Failed to locate Alternative WindowingSystem!"); vfs->ChDir ("/tmp"); files = vfs->FindFiles ("/this/*"); cur_idx = 0; CreateGui(); x = g3d->GetDriver2D ()->GetWidth (); y = g3d->GetDriver2D ()->GetHeight (); Run(); return true; } void PicView::CreateGui () { aws->SetupCanvas(0, g3d->GetDriver2D (), g3d); iAwsSink* sink = aws->GetSinkMgr ()->CreateSink ((void*)this); sink->RegisterTrigger ("First", &ButtonFirst); sink->RegisterTrigger ("Prev" , &ButtonPrev ); sink->RegisterTrigger ("Next" , &ButtonNext ); sink->RegisterTrigger ("Quit" , &ButtonQuit ); sink->RegisterTrigger ("Scale", &ButtonScale); aws->GetSinkMgr ()->RegisterSink ("PicView", sink); if (!aws->GetPrefMgr()->Load ("/aws/windows_skin.def")) ReportError("couldn't load skin definition file!"); if (!aws->GetPrefMgr()->Load ("/varia/picview.def")) ReportError("couldn't load definition file!"); aws->GetPrefMgr ()->SelectDefaultSkin ("Windows"); gui = aws->CreateWindowFrom ("PicView"); if (gui) { gui->MoveTo(g3d->GetDriver2D ()->GetWidth ()/2-100, 0); gui->Show (); } } void PicView::LoadNextImage (int idx, int step) { iTextureManager* txtmgr = g3d->GetTextureManager(); if (idx) cur_idx = idx; cur_idx += step; if (cur_idx < 0) cur_idx = files->Length ()-1; if ((size_t)cur_idx >= files->Length ()) cur_idx = 0; csRef<iDataBuffer> buf (vfs->ReadFile (files->Get (cur_idx))); if (!buf) return; csRef<iImage> ifile (imgloader->Load (buf->GetUint8 (), buf->GetSize (), txtmgr->GetTextureFormat ())); if (!ifile) return; delete pic; txt = txtmgr->RegisterTexture (ifile, CS_TEXTURE_2D | CS_TEXTURE_DITHER); pic = new csSimplePixmap (txt); } //--------------------------------------------------------------------------- void PicView::ButtonFirst(void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->LoadNextImage (1, -1); } void PicView::ButtonPrev (void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->LoadNextImage (0, -1); } void PicView::ButtonNext (void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->LoadNextImage (0, 1); } void PicView::ButtonQuit (void* app, iAwsSource *source) { csRef<iEventQueue> q = CS_QUERY_REGISTRY(GetObjectRegistry(), iEventQueue); if (q.IsValid()) q->GetEventOutlet()->Broadcast(cscmdQuit); } void PicView::ButtonScale (void* app, iAwsSource *source) { PicView* picview = (PicView*)app; picview->scale ^= true; } /*-------------------------------------------------------------------------* * Main function *-------------------------------------------------------------------------*/ int main (int argc, char* argv[]) { return PicView().Main(argc, argv); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // ThreadLocal test program for The Loki Library // Copyright (c) 2009 by Richard Sposato // The copyright on this file is protected under the terms of the MIT license. // // 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 <cstdlib> #include <iostream> using namespace ::std; extern bool TestThreadLocalClassStaticValue( void ); extern bool TestThreadLocalFunctionStaticValue( void ); extern bool TestThreadLocalStaticValue( void ); // ---------------------------------------------------------------------------- int main( int argc, const char * const argv[] ) { (void)argc; (void)argv; bool okay = true; cout << "Starting ThreadLocal tests." << endl; cout << "If any tests fail, or any assertions fail," << endl << "then your compiler does not implement thread_local storage correctly." << endl; cout << endl << "Testing static thread_local storage inside classes." << endl; okay = TestThreadLocalClassStaticValue(); if ( okay ) cout << "Your compiler correctly implements thread_local storage for class static values." << endl; else cout << "Your compiler does not properly implement thread_local storage for class static values." << endl; cout << endl << "Testing static thread_local storage inside functions." << endl; okay = TestThreadLocalFunctionStaticValue(); if ( okay ) cout << "Your compiler correctly implements thread_local storage for function static values." << endl; else cout << "Your compiler does not properly implement thread_local storage for function static values." << endl; cout << endl << "Testing standalone static thread_local storage." << endl; okay = TestThreadLocalStaticValue(); if ( okay ) cout << "Your compiler correctly implements thread_local storage for standalone static values." << endl; else cout << "Your compiler does not properly implement thread_local storage for standalone static values." << endl; ::system( "pause" ); return 0; } // ---------------------------------------------------------------------------- <commit_msg>Minor cosmetic changes. Also replaced system call with use of std::cin.get.<commit_after>//////////////////////////////////////////////////////////////////////////////// // // ThreadLocal test program for The Loki Library // Copyright (c) 2009 by Richard Sposato // The copyright on this file is protected under the terms of the MIT license. // // 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 <cstdlib> #include <iostream> using namespace ::std; extern bool TestThreadLocalClassStaticValue( void ); extern bool TestThreadLocalFunctionStaticValue( void ); extern bool TestThreadLocalStaticValue( void ); // ---------------------------------------------------------------------------- int main( int argc, const char * const argv[] ) { (void)argc; (void)argv; bool okay = true; cout << "Starting ThreadLocal tests." << endl; cout << "If any tests fail, or any assertions fail," << endl << "then your compiler does not implement thread_local storage correctly." << endl; cout << endl << "Testing static thread_local storage inside classes." << endl; okay = TestThreadLocalClassStaticValue(); if ( okay ) cout << "Your compiler correctly implements thread_local storage for class static values." << endl; else cout << "Your compiler does not properly implement thread_local storage for class static values." << endl; cout << endl << "Testing static thread_local storage inside functions." << endl; okay = TestThreadLocalFunctionStaticValue(); if ( okay ) cout << "Your compiler correctly implements thread_local storage for function static values." << endl; else cout << "Your compiler does not properly implement thread_local storage for function static values." << endl; cout << endl << "Testing standalone static thread_local storage." << endl; okay = TestThreadLocalStaticValue(); if ( okay ) cout << "Your compiler correctly implements thread_local storage for standalone static values." << endl; else cout << "Your compiler does not properly implement thread_local storage for standalone static values." << endl; ::std::cout << "Please press enter key to continue." << ::std::endl; ::std::cin.get(); return 0; } // ---------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <[email protected]> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" #define KOPETE_VERSION "0.6.90cvs >= 20030426" static const char *description = I18N_NOOP("Kopete, the KDE Instant Messenger"); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP("Do not load plugins"), 0 }, { "noconnect" , I18N_NOOP("Disable auto-connection") , 0 }, // { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO { "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 }, { "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "[email protected]", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "[email protected]", "http://www.mac-vicar.com" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "[email protected]", "http://www.kdedevelopers.net" ); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "[email protected]" ); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "[email protected]", "http://raging.dropbear.id.au/daniel/"); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "[email protected]"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "[email protected]"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "[email protected]", "http://metz.gehn.net" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "[email protected]" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "[email protected]" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "[email protected]", "http://bemis.kicks-ass.net"); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "[email protected]", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "[email protected]", "http://www.keirstead.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "[email protected]" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "[email protected]" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); //aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Old developer"), "[email protected]" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Old Developer"), "[email protected]"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Old Developer"), "[email protected]", "http://www.hennevl.de"); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Old Developer"), "[email protected]" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "[email protected]" ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <commit_msg>- Some updates to website, version bump, etc<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <[email protected]> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" #define KOPETE_VERSION "0.6.90cvs >= 20030511" static const char *description = I18N_NOOP("Kopete, the KDE Instant Messenger"); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP("Do not load plugins"), 0 }, { "noconnect" , I18N_NOOP("Disable auto-connection") , 0 }, // { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO { "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 }, { "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001,2003, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "[email protected]", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "[email protected]", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "[email protected]"); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "[email protected]" ); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "[email protected]", "http://raging.dropbear.id.au/daniel/"); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "[email protected]"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "[email protected]"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "[email protected]", "http://metz.gehn.net" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "[email protected]" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "[email protected]" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "[email protected]", "http://bemis.kicks-ass.net"); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "[email protected]", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "[email protected]", "http://www.keirstead.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "[email protected]" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "[email protected]" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); //aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Old developer"), "[email protected]" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Old Developer"), "[email protected]"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Old Developer"), "[email protected]", "http://www.hennevl.de"); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Old Developer"), "[email protected]" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "[email protected]" ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before><commit_msg>Added SHEEN_ROUGHNESS and SHEEN_ALBEDOSCALING define<commit_after><|endoftext|>
<commit_before>#include <babylon/materials/pbr/pbr_material_defines.h> #include <sstream> namespace BABYLON { PBRMaterialDefines::PBRMaterialDefines() { boolDef = { {"PBR", true}, // {"REALTIME_FILTERING", false}, // {"MAINUV1", false}, // {"MAINUV2", false}, // {"UV1", false}, // {"UV2", false}, // {"ALBEDO", false}, // {"GAMMAALBEDO", false}, // {"VERTEXCOLOR", false}, // {"DETAIL", false}, // {"AMBIENT", false}, // {"AMBIENTINGRAYSCALE", false}, // {"OPACITY", false}, // {"VERTEXALPHA", false}, // {"OPACITYRGB", false}, // {"ALPHATEST", false}, // {"DEPTHPREPASS", false}, // {"ALPHABLEND", false}, // {"ALPHAFROMALBEDO", false}, // {"SPECULAROVERALPHA", false}, // {"RADIANCEOVERALPHA", false}, // {"ALPHAFRESNEL", false}, // {"LINEARALPHAFRESNEL", false}, // {"PREMULTIPLYALPHA", false}, // {"EMISSIVE", false}, // {"REFLECTIVITY", false}, // {"SPECULARTERM", false}, // {"MICROSURFACEFROMREFLECTIVITYMAP", false}, // {"MICROSURFACEAUTOMATIC", false}, // {"LODBASEDMICROSFURACE", false}, // {"MICROSURFACEMAP", false}, // {"METALLICWORKFLOW", false}, // {"ROUGHNESSSTOREINMETALMAPALPHA", false}, // {"ROUGHNESSSTOREINMETALMAPGREEN", false}, // {"METALLNESSSTOREINMETALMAPBLUE", false}, // {"AOSTOREINMETALMAPRED", false}, // {"METALLIC_REFLECTANCE", false}, // {"ENVIRONMENTBRDF", false}, // {"ENVIRONMENTBRDF_RGBD", false}, // {"NORMAL", false}, // {"TANGENT", false}, // {"BUMP", false}, // {"OBJECTSPACE_NORMALMAP", false}, // {"PARALLAX", false}, // {"PARALLAXOCCLUSION", false}, // {"NORMALXYSCALE", true}, // {"LIGHTMAP", false}, // {"USELIGHTMAPASSHADOWMAP", false}, // {"GAMMALIGHTMAP", false}, // {"RGBDLIGHTMAP", false}, // {"REFLECTION", false}, // {"REFLECTIONMAP_3D", false}, // {"REFLECTIONMAP_SPHERICAL", false}, // {"REFLECTIONMAP_PLANAR", false}, // {"REFLECTIONMAP_CUBIC", false}, // {"USE_LOCAL_REFLECTIONMAP_CUBIC", false}, // {"REFLECTIONMAP_PROJECTION", false}, // {"REFLECTIONMAP_SKYBOX", false}, // {"REFLECTIONMAP_EXPLICIT", false}, // {"REFLECTIONMAP_EQUIRECTANGULAR", false}, // {"REFLECTIONMAP_EQUIRECTANGULAR_FIXED", false}, // {"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED", false}, // {"INVERTCUBICMAP", false}, // {"USESPHERICALFROMREFLECTIONMAP", false}, // {"USEIRRADIANCEMAP", false}, // {"SPHERICAL_HARMONICS", false}, // {"USESPHERICALINVERTEX", false}, // {"REFLECTIONMAP_OPPOSITEZ", false}, // {"LODINREFLECTIONALPHA", false}, // {"GAMMAREFLECTION", false}, // {"RGBDREFLECTION", false}, // {"LINEARSPECULARREFLECTION", false}, // {"RADIANCEOCCLUSION", false}, // {"HORIZONOCCLUSION", false}, // {"INSTANCES", false}, // {"THIN_INSTANCES", false}, // {"PREPASS", false}, // {"BONETEXTURE", false}, // {"NONUNIFORMSCALING", false}, // {"MORPHTARGETS", false}, // {"MORPHTARGETS_NORMAL", false}, // {"MORPHTARGETS_TANGENT", false}, // {"MORPHTARGETS_UV", false}, // {"IMAGEPROCESSING", false}, // {"VIGNETTE", false}, // {"VIGNETTEBLENDMODEMULTIPLY", false}, // {"VIGNETTEBLENDMODEOPAQUE", false}, // {"TONEMAPPING", false}, // {"TONEMAPPING_ACES", false}, // {"CONTRAST", false}, // {"COLORCURVES", false}, // {"COLORGRADING", false}, // {"COLORGRADING3D", false}, // {"SAMPLER3DGREENDEPTH", false}, // {"SAMPLER3DBGRMAP", false}, // {"IMAGEPROCESSINGPOSTPROCESS", false}, // {"EXPOSURE", false}, // {"MULTIVIEW", false}, // {"USEPHYSICALLIGHTFALLOFF", false}, // {"USEGLTFLIGHTFALLOFF", false}, // {"TWOSIDEDLIGHTING", false}, // {"SHADOWFLOAT", false}, // {"CLIPPLANE", false}, // {"CLIPPLANE2", false}, // {"CLIPPLANE3", false}, // {"CLIPPLANE4", false}, // {"CLIPPLANE5", false}, // {"CLIPPLANE6", false}, // {"POINTSIZE", false}, // {"FOG", false}, // {"LOGARITHMICDEPTH", false}, // {"FORCENORMALFORWARD", false}, // {"SPECULARAA", false}, // {"CLEARCOAT", false}, // {"CLEARCOAT_DEFAULTIOR", false}, // {"CLEARCOAT_TEXTURE", false}, // {"CLEARCOAT_BUMP", false}, // {"CLEARCOAT_TINT", false}, // {"CLEARCOAT_TINT_TEXTURE", false}, // {"ANISOTROPIC", false}, // {"ANISOTROPIC_TEXTURE", false}, // {"BRDF_V_HEIGHT_CORRELATED", false}, // {"MS_BRDF_ENERGY_CONSERVATION", false}, // {"SPECULAR_GLOSSINESS_ENERGY_CONSERVATION", false}, // {"SHEEN", false}, // {"SHEEN_TEXTURE", false}, // {"SHEEN_LINKWITHALBEDO", false}, // {"SHEEN_ROUGHNESS", false}, // {"SHEEN_ALBEDOSCALING", false}, // {"SUBSURFACE", false}, // {"SS_REFRACTION", false}, // {"SS_TRANSLUCENCY", false}, // {"SS_SCATTERING", false}, // {"SS_THICKNESSANDMASK_TEXTURE", false}, // {"SS_REFRACTIONMAP_3D", false}, // {"SS_REFRACTIONMAP_OPPOSITEZ", false}, // {"SS_LODINREFRACTIONALPHA", false}, // {"SS_GAMMAREFRACTION", false}, // {"SS_RGBDREFRACTION", false}, // {"SS_LINEARSPECULARREFRACTION", false}, // {"SS_LINKREFRACTIONTOTRANSPARENCY", false}, // {"SS_ALBEDOFORREFRACTIONTINT", false}, // {"SS_MASK_FROM_THICKNESS_TEXTURE", false}, // {"UNLIT", false}, // }; intDef = { {"NUM_SAMPLES", 0}, // {"AMBIENTDIRECTUV", 0}, // {"ALBEDODIRECTUV", 0}, // {"DETAILDIRECTUV", 0}, // {"DETAIL_NORMALBLENDMETHOD", 0}, // {"OPACITYDIRECTUV", 0}, // {"EMISSIVEDIRECTUV", 0}, // {"REFLECTIVITYDIRECTUV", 0}, // {"MICROSURFACEMAPDIRECTUV", 0}, // {"METALLIC_REFLECTANCEDIRECTUV", 0}, // {"BUMPDIRECTUV", 0}, // {"LIGHTMAPDIRECTUV", 0}, // {"NUM_BONE_INFLUENCERS", 0}, // {"BonesPerMesh", 0}, // {"SCENE_MRT_COUNT", 0}, // {"NUM_MORPH_INFLUENCERS", 0}, // {"CLEARCOAT_TEXTUREDIRECTUV", 0}, // {"CLEARCOAT_BUMPDIRECTUV", 0}, // {"CLEARCOAT_TINT_TEXTUREDIRECTUV", 0}, // {"ANISOTROPIC_TEXTUREDIRECTUV", 0}, // {"SHEEN_TEXTUREDIRECTUV", 0}, // {"SS_THICKNESSANDMASK_TEXTUREDIRECTUV", 0}, // {"DEBUGMODE", 0}, // }; stringDef = { {"ALPHATESTVALUE", "0.5"}, // }; } PBRMaterialDefines::~PBRMaterialDefines() = default; void PBRMaterialDefines::reset() { MaterialDefines::reset(); boolDef["PBR"] = true; boolDef["NORMALXYSCALE"] = true; stringDef["ALPHATESTVALUE"] = "0.5"; } std::string PBRMaterialDefines::toString() const { std::ostringstream oss; oss << MaterialDefines::toString(); oss << IImageProcessingConfigurationDefines::convertToString(); return oss.str(); } } // end of namespace BABYLON <commit_msg>Added PBRMaterialDefines values<commit_after>#include <babylon/materials/pbr/pbr_material_defines.h> #include <sstream> namespace BABYLON { PBRMaterialDefines::PBRMaterialDefines() { boolDef = { {"PBR", true}, // {"REALTIME_FILTERING", false}, // {"MAINUV1", false}, // {"MAINUV2", false}, // {"UV1", false}, // {"UV2", false}, // {"ALBEDO", false}, // {"GAMMAALBEDO", false}, // {"VERTEXCOLOR", false}, // {"DETAIL", false}, // {"AMBIENT", false}, // {"AMBIENTINGRAYSCALE", false}, // {"OPACITY", false}, // {"VERTEXALPHA", false}, // {"OPACITYRGB", false}, // {"ALPHATEST", false}, // {"DEPTHPREPASS", false}, // {"ALPHABLEND", false}, // {"ALPHAFROMALBEDO", false}, // {"SPECULAROVERALPHA", false}, // {"RADIANCEOVERALPHA", false}, // {"ALPHAFRESNEL", false}, // {"LINEARALPHAFRESNEL", false}, // {"PREMULTIPLYALPHA", false}, // {"EMISSIVE", false}, // {"REFLECTIVITY", false}, // {"SPECULARTERM", false}, // {"MICROSURFACEFROMREFLECTIVITYMAP", false}, // {"MICROSURFACEAUTOMATIC", false}, // {"LODBASEDMICROSFURACE", false}, // {"MICROSURFACEMAP", false}, // {"METALLICWORKFLOW", false}, // {"ROUGHNESSSTOREINMETALMAPALPHA", false}, // {"ROUGHNESSSTOREINMETALMAPGREEN", false}, // {"METALLNESSSTOREINMETALMAPBLUE", false}, // {"AOSTOREINMETALMAPRED", false}, // {"METALLIC_REFLECTANCE", false}, // {"ENVIRONMENTBRDF", false}, // {"ENVIRONMENTBRDF_RGBD", false}, // {"NORMAL", false}, // {"TANGENT", false}, // {"BUMP", false}, // {"OBJECTSPACE_NORMALMAP", false}, // {"PARALLAX", false}, // {"PARALLAXOCCLUSION", false}, // {"NORMALXYSCALE", true}, // {"LIGHTMAP", false}, // {"USELIGHTMAPASSHADOWMAP", false}, // {"GAMMALIGHTMAP", false}, // {"RGBDLIGHTMAP", false}, // {"REFLECTION", false}, // {"REFLECTIONMAP_3D", false}, // {"REFLECTIONMAP_SPHERICAL", false}, // {"REFLECTIONMAP_PLANAR", false}, // {"REFLECTIONMAP_CUBIC", false}, // {"USE_LOCAL_REFLECTIONMAP_CUBIC", false}, // {"REFLECTIONMAP_PROJECTION", false}, // {"REFLECTIONMAP_SKYBOX", false}, // {"REFLECTIONMAP_EXPLICIT", false}, // {"REFLECTIONMAP_EQUIRECTANGULAR", false}, // {"REFLECTIONMAP_EQUIRECTANGULAR_FIXED", false}, // {"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED", false}, // {"INVERTCUBICMAP", false}, // {"USESPHERICALFROMREFLECTIONMAP", false}, // {"USEIRRADIANCEMAP", false}, // {"SPHERICAL_HARMONICS", false}, // {"USESPHERICALINVERTEX", false}, // {"REFLECTIONMAP_OPPOSITEZ", false}, // {"LODINREFLECTIONALPHA", false}, // {"GAMMAREFLECTION", false}, // {"RGBDREFLECTION", false}, // {"LINEARSPECULARREFLECTION", false}, // {"RADIANCEOCCLUSION", false}, // {"HORIZONOCCLUSION", false}, // {"INSTANCES", false}, // {"THIN_INSTANCES", false}, // {"PREPASS", false}, // {"PREPASS_IRRADIANCE", false}, // {"PREPASS_ALBEDO", false}, // {"PREPASS_DEPTHNORMAL", false}, // {"PREPASS_POSITION", false}, // {"PREPASS_VELOCITY", false}, // {"PREPASS_REFLECTIVITY", false}, // {"BONETEXTURE", false}, // {"BONES_VELOCITY_ENABLED", false}, // {"NONUNIFORMSCALING", false}, // {"MORPHTARGETS", false}, // {"MORPHTARGETS_NORMAL", false}, // {"MORPHTARGETS_TANGENT", false}, // {"MORPHTARGETS_UV", false}, // {"IMAGEPROCESSING", false}, // {"VIGNETTE", false}, // {"VIGNETTEBLENDMODEMULTIPLY", false}, // {"VIGNETTEBLENDMODEOPAQUE", false}, // {"TONEMAPPING", false}, // {"TONEMAPPING_ACES", false}, // {"CONTRAST", false}, // {"COLORCURVES", false}, // {"COLORGRADING", false}, // {"COLORGRADING3D", false}, // {"SAMPLER3DGREENDEPTH", false}, // {"SAMPLER3DBGRMAP", false}, // {"IMAGEPROCESSINGPOSTPROCESS", false}, // {"EXPOSURE", false}, // {"MULTIVIEW", false}, // {"USEPHYSICALLIGHTFALLOFF", false}, // {"USEGLTFLIGHTFALLOFF", false}, // {"TWOSIDEDLIGHTING", false}, // {"SHADOWFLOAT", false}, // {"CLIPPLANE", false}, // {"CLIPPLANE2", false}, // {"CLIPPLANE3", false}, // {"CLIPPLANE4", false}, // {"CLIPPLANE5", false}, // {"CLIPPLANE6", false}, // {"POINTSIZE", false}, // {"FOG", false}, // {"LOGARITHMICDEPTH", false}, // {"FORCENORMALFORWARD", false}, // {"SPECULARAA", false}, // {"CLEARCOAT", false}, // {"CLEARCOAT_DEFAULTIOR", false}, // {"CLEARCOAT_TEXTURE", false}, // {"CLEARCOAT_TEXTURE_ROUGHNESS", false}, // {"CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE", false}, // {"CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL", false}, // {"CLEARCOAT_BUMP", false}, // {"CLEARCOAT_REMAP_F0", true}, // {"CLEARCOAT_TINT", false}, // {"CLEARCOAT_TINT_TEXTURE", false}, // {"ANISOTROPIC", false}, // {"ANISOTROPIC_TEXTURE", false}, // {"BRDF_V_HEIGHT_CORRELATED", false}, // {"MS_BRDF_ENERGY_CONSERVATION", false}, // {"SPECULAR_GLOSSINESS_ENERGY_CONSERVATION", false}, // {"SHEEN", false}, // {"SHEEN_TEXTURE", false}, // {"SHEEN_TEXTURE_ROUGHNESS", false}, // {"SHEEN_LINKWITHALBEDO", false}, // {"SHEEN_ROUGHNESS", false}, // {"SHEEN_ALBEDOSCALING", false}, // {"SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE", false}, // {"SHEEN_TEXTURE_ROUGHNESS_IDENTICAL", false}, // {"SUBSURFACE", false}, // {"SS_REFRACTION", false}, // {"SS_TRANSLUCENCY", false}, // {"SS_SCATTERING", false}, // {"SS_THICKNESSANDMASK_TEXTURE", false}, // {"SS_REFRACTIONMAP_3D", false}, // {"SS_REFRACTIONMAP_OPPOSITEZ", false}, // {"SS_LODINREFRACTIONALPHA", false}, // {"SS_GAMMAREFRACTION", false}, // {"SS_RGBDREFRACTION", false}, // {"SS_LINEARSPECULARREFRACTION", false}, // {"SS_LINKREFRACTIONTOTRANSPARENCY", false}, // {"SS_ALBEDOFORREFRACTIONTINT", false}, // {"SS_MASK_FROM_THICKNESS_TEXTURE", false}, // {"UNLIT", false}, // }; intDef = { {"NUM_SAMPLES", 0}, // {"AMBIENTDIRECTUV", 0}, // {"ALBEDODIRECTUV", 0}, // {"DETAILDIRECTUV", 0}, // {"DETAIL_NORMALBLENDMETHOD", 0}, // {"OPACITYDIRECTUV", 0}, // {"EMISSIVEDIRECTUV", 0}, // {"REFLECTIVITYDIRECTUV", 0}, // {"MICROSURFACEMAPDIRECTUV", 0}, // {"METALLIC_REFLECTANCEDIRECTUV", 0}, // {"BUMPDIRECTUV", 0}, // {"LIGHTMAPDIRECTUV", 0}, // {"NUM_BONE_INFLUENCERS", 0}, // {"BonesPerMesh", 0}, // {"PREPASS_IRRADIANCE_INDEX", -1}, // {"PREPASS_ALBEDO_INDEX", -1}, // {"PREPASS_DEPTHNORMAL_INDEX", -1}, // {"PREPASS_POSITION_INDEX", -1}, // {"PREPASS_VELOCITY_INDEX", -1}, // {"PREPASS_REFLECTIVITY_INDEX", -1}, // {"SCENE_MRT_COUNT", 0}, // {"NUM_MORPH_INFLUENCERS", 0}, // {"CLEARCOAT_TEXTUREDIRECTUV", 0}, // {"CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV", 0}, // {"CLEARCOAT_BUMPDIRECTUV", 0}, // {"CLEARCOAT_TINT_TEXTUREDIRECTUV", 0}, // {"ANISOTROPIC_TEXTUREDIRECTUV", 0}, // {"SHEEN_TEXTUREDIRECTUV", 0}, // {"SHEEN_TEXTURE_ROUGHNESSDIRECTUV", 0}, // {"SS_THICKNESSANDMASK_TEXTUREDIRECTUV", 0}, // {"DEBUGMODE", 0}, // }; stringDef = { {"ALPHATESTVALUE", "0.5"}, // }; } PBRMaterialDefines::~PBRMaterialDefines() = default; void PBRMaterialDefines::reset() { MaterialDefines::reset(); boolDef["PBR"] = true; boolDef["NORMALXYSCALE"] = true; stringDef["ALPHATESTVALUE"] = "0.5"; } std::string PBRMaterialDefines::toString() const { std::ostringstream oss; oss << MaterialDefines::toString(); oss << IImageProcessingConfigurationDefines::convertToString(); return oss.str(); } } // end of namespace BABYLON <|endoftext|>
<commit_before>// Filename: pystub.cxx // Created by: drose (09Aug00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "pystub.h" extern "C" { EXPCL_DTOOLCONFIG int PyArg_Parse(...); EXPCL_DTOOLCONFIG int PyArg_ParseTuple(...); EXPCL_DTOOLCONFIG int PyArg_ParseTupleAndKeywords(...); EXPCL_DTOOLCONFIG int PyCFunction_New(...); EXPCL_DTOOLCONFIG int PyCFunction_NewEx(...); EXPCL_DTOOLCONFIG int PyCallable_Check(...); EXPCL_DTOOLCONFIG int PyDict_DelItemString(...); EXPCL_DTOOLCONFIG int PyDict_GetItem(...); EXPCL_DTOOLCONFIG int PyDict_GetItemString(...); EXPCL_DTOOLCONFIG int PyDict_New(...); EXPCL_DTOOLCONFIG int PyDict_SetItem(...); EXPCL_DTOOLCONFIG int PyDict_SetItemString(...); EXPCL_DTOOLCONFIG int PyDict_Size(...); EXPCL_DTOOLCONFIG int PyDict_Type(...); EXPCL_DTOOLCONFIG int PyErr_Clear(...); EXPCL_DTOOLCONFIG int PyErr_ExceptionMatches(...); EXPCL_DTOOLCONFIG int PyErr_Fetch(...); EXPCL_DTOOLCONFIG int PyErr_Format(...); EXPCL_DTOOLCONFIG int PyErr_Occurred(...); EXPCL_DTOOLCONFIG int PyErr_Print(...); EXPCL_DTOOLCONFIG int PyErr_Restore(...); EXPCL_DTOOLCONFIG int PyErr_SetString(...); EXPCL_DTOOLCONFIG int PyErr_Warn(...); EXPCL_DTOOLCONFIG int PyErr_WarnEx(...); EXPCL_DTOOLCONFIG int PyEval_CallFunction(...); EXPCL_DTOOLCONFIG int PyEval_CallObjectWithKeywords(...); EXPCL_DTOOLCONFIG int PyEval_InitThreads(...); EXPCL_DTOOLCONFIG int PyEval_RestoreThread(...); EXPCL_DTOOLCONFIG int PyEval_SaveThread(...); EXPCL_DTOOLCONFIG int PyFloat_AsDouble(...); EXPCL_DTOOLCONFIG int PyFloat_FromDouble(...); EXPCL_DTOOLCONFIG int PyFloat_Type(...); EXPCL_DTOOLCONFIG int PyGen_Check(...); EXPCL_DTOOLCONFIG int PyGen_Type(...); EXPCL_DTOOLCONFIG int PyGILState_Ensure(...); EXPCL_DTOOLCONFIG int PyGILState_Release(...); EXPCL_DTOOLCONFIG int PyImport_GetModuleDict(...); EXPCL_DTOOLCONFIG int PyInt_AsLong(...); EXPCL_DTOOLCONFIG int PyInt_AsSsize_t(...); EXPCL_DTOOLCONFIG int PyInt_FromLong(...); EXPCL_DTOOLCONFIG int PyInt_Type(...); EXPCL_DTOOLCONFIG int PyList_Append(...); EXPCL_DTOOLCONFIG int PyList_AsTuple(...); EXPCL_DTOOLCONFIG int PyList_GetItem(...); EXPCL_DTOOLCONFIG int PyList_New(...); EXPCL_DTOOLCONFIG int PyList_SetItem(...); EXPCL_DTOOLCONFIG int PyLong_AsLong(...); EXPCL_DTOOLCONFIG int PyLong_AsLongLong(...); EXPCL_DTOOLCONFIG int PyLong_AsUnsignedLong(...); EXPCL_DTOOLCONFIG int PyLong_AsUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyLong_FromLong(...); EXPCL_DTOOLCONFIG int PyLong_FromLongLong(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLong(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyLong_Type(...); EXPCL_DTOOLCONFIG int PyMapping_GetItemString(...); EXPCL_DTOOLCONFIG int PyModule_AddIntConstant(...); EXPCL_DTOOLCONFIG int PyModule_AddObject(...); EXPCL_DTOOLCONFIG int PyModule_AddStringConstant(...); EXPCL_DTOOLCONFIG int PyNumber_Long(...); EXPCL_DTOOLCONFIG int PyObject_Call(...); EXPCL_DTOOLCONFIG int PyObject_CallFunction(...); EXPCL_DTOOLCONFIG int PyObject_CallMethod(...); EXPCL_DTOOLCONFIG int PyObject_CallMethodObjArgs(...); EXPCL_DTOOLCONFIG int PyObject_CallObject(...); EXPCL_DTOOLCONFIG int PyObject_Cmp(...); EXPCL_DTOOLCONFIG int PyObject_Compare(...); EXPCL_DTOOLCONFIG int PyObject_Free(...); EXPCL_DTOOLCONFIG int PyObject_GenericGetAttr(...); EXPCL_DTOOLCONFIG int PyObject_GenericSetAttr(...); EXPCL_DTOOLCONFIG int PyObject_GetAttrString(...); EXPCL_DTOOLCONFIG int PyObject_HasAttrString(...); EXPCL_DTOOLCONFIG int PyObject_IsInstance(...); EXPCL_DTOOLCONFIG int PyObject_IsTrue(...); EXPCL_DTOOLCONFIG int PyObject_Repr(...); EXPCL_DTOOLCONFIG int PyObject_SetAttrString(...); EXPCL_DTOOLCONFIG int PyObject_Str(...); EXPCL_DTOOLCONFIG int PyObject_Type(...); EXPCL_DTOOLCONFIG int PySequence_Check(...); EXPCL_DTOOLCONFIG int PySequence_GetItem(...); EXPCL_DTOOLCONFIG int PySequence_Size(...); EXPCL_DTOOLCONFIG int PySequence_Tuple(...); EXPCL_DTOOLCONFIG int PyString_AsString(...); EXPCL_DTOOLCONFIG int PyString_AsStringAndSize(...); EXPCL_DTOOLCONFIG int PyString_FromString(...); EXPCL_DTOOLCONFIG int PyString_FromStringAndSize(...); EXPCL_DTOOLCONFIG int PyString_Size(...); EXPCL_DTOOLCONFIG int PyString_Type(...); EXPCL_DTOOLCONFIG int PySys_GetObject(...); EXPCL_DTOOLCONFIG int PyThreadState_Clear(...); EXPCL_DTOOLCONFIG int PyThreadState_Delete(...); EXPCL_DTOOLCONFIG int PyThreadState_Get(...); EXPCL_DTOOLCONFIG int PyThreadState_New(...); EXPCL_DTOOLCONFIG int PyThreadState_Swap(...); EXPCL_DTOOLCONFIG int PyTuple_GetItem(...); EXPCL_DTOOLCONFIG int PyTuple_New(...); EXPCL_DTOOLCONFIG int PyTuple_Pack(...); EXPCL_DTOOLCONFIG int PyTuple_Size(...); EXPCL_DTOOLCONFIG int PyTuple_Type(...); EXPCL_DTOOLCONFIG int PyType_GenericAlloc(...); EXPCL_DTOOLCONFIG int PyType_IsSubtype(...); EXPCL_DTOOLCONFIG int PyType_Ready(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS2_FromWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS2_AsWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS2_GetSize(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS4_FromWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS4_AsWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS4_GetSize(...); EXPCL_DTOOLCONFIG int PyUnicode_Type(...); EXPCL_DTOOLCONFIG int Py_BuildValue(...); EXPCL_DTOOLCONFIG int Py_InitModule4(...); EXPCL_DTOOLCONFIG int Py_InitModule4_64(...); EXPCL_DTOOLCONFIG int Py_InitModule4TraceRefs(...); EXPCL_DTOOLCONFIG int _PyObject_DebugFree(...); EXPCL_DTOOLCONFIG int _PyObject_Del(...); EXPCL_DTOOLCONFIG int _Py_Dealloc(...); EXPCL_DTOOLCONFIG int _Py_NegativeRefcount(...); EXPCL_DTOOLCONFIG int _Py_RefTotal(...); EXPCL_DTOOLCONFIG int Py_IsInitialized(); EXPCL_DTOOLCONFIG extern void *PyExc_AssertionError; EXPCL_DTOOLCONFIG extern void *PyExc_AttributeError; EXPCL_DTOOLCONFIG extern void *PyExc_FutureWarning; EXPCL_DTOOLCONFIG extern void *PyExc_IndexError; EXPCL_DTOOLCONFIG extern void *PyExc_RuntimeError; EXPCL_DTOOLCONFIG extern void *PyExc_StandardError; EXPCL_DTOOLCONFIG extern void *PyExc_StopIteration; EXPCL_DTOOLCONFIG extern void *PyExc_TypeError; EXPCL_DTOOLCONFIG extern void *PyExc_ValueError; EXPCL_DTOOLCONFIG extern void *_Py_NoneStruct; EXPCL_DTOOLCONFIG extern void *_Py_NotImplementedStruct; }; int PyArg_Parse(...) { return 0; }; int PyArg_ParseTuple(...) { return 0; } int PyArg_ParseTupleAndKeywords(...) { return 0; } int PyCFunction_New(...) { return 0; }; int PyCFunction_NewEx(...) { return 0; }; int PyCallable_Check(...) { return 0; } int PyDict_DelItemString(...) { return 0; } int PyDict_GetItem(...) { return 0; } int PyDict_GetItemString(...) { return 0; } int PyDict_New(...) { return 0; }; int PyDict_SetItem(...) { return 0; }; int PyDict_SetItemString(...) { return 0; }; int PyDict_Size(...){ return 0; } int PyDict_Type(...) { return 0; }; int PyErr_Clear(...) { return 0; }; int PyErr_ExceptionMatches(...) { return 0; }; int PyErr_Fetch(...) { return 0; } int PyErr_Format(...) { return 0; }; int PyErr_Occurred(...) { return 0; } int PyErr_Print(...) { return 0; } int PyErr_Restore(...) { return 0; } int PyErr_SetString(...) { return 0; } int PyErr_Warn(...) { return 0; } int PyErr_WarnEx(...) { return 0; } int PyEval_CallFunction(...) { return 0; } int PyEval_CallObjectWithKeywords(...) { return 0; } int PyEval_InitThreads(...) { return 0; } int PyEval_RestoreThread(...) { return 0; } int PyEval_SaveThread(...) { return 0; } int PyFloat_AsDouble(...) { return 0; } int PyFloat_FromDouble(...) { return 0; } int PyFloat_Type(...) { return 0; } int PyGen_Check(...) { return 0; } int PyGen_Type(...) { return 0; } int PyGILState_Ensure(...) { return 0; } int PyGILState_Release(...) { return 0; } int PyImport_GetModuleDict(...) { return 0; } int PyInt_AsLong(...) { return 0; } int PyInt_AsSsize_t(...) { return 0; } int PyInt_FromLong(...) { return 0; } int PyInt_Type(...) { return 0; } int PyList_Append(...) { return 0; } int PyList_AsTuple(...) { return 0; } int PyList_GetItem(...) { return 0; } int PyList_New(...) { return 0; } int PyList_SetItem(...) { return 0; } int PyLong_AsLong(...) { return 0; } int PyLong_AsLongLong(...) { return 0; } int PyLong_AsUnsignedLong(...) { return 0; } int PyLong_AsUnsignedLongLong(...) { return 0; } int PyLong_FromLong(...) { return 0; } int PyLong_FromLongLong(...) { return 0; } int PyLong_FromUnsignedLong(...) { return 0; } int PyLong_FromUnsignedLongLong(...) { return 0; } int PyLong_Type(...) { return 0; } int PyMapping_GetItemString(...) { return 0; } int PyModule_AddIntConstant(...) { return 0; }; int PyModule_AddObject(...) { return 0; }; int PyModule_AddStringConstant(...) { return 0; }; int PyNumber_Long(...) { return 0; } int PyObject_Call(...) { return 0; } int PyObject_CallFunction(...) { return 0; } int PyObject_CallMethod(...) { return 0; } int PyObject_CallMethodObjArgs(...) { return 0; } int PyObject_CallObject(...) { return 0; } int PyObject_Cmp(...) { return 0; } int PyObject_Compare(...) { return 0; } int PyObject_Free(...) { return 0; } int PyObject_GenericGetAttr(...) { return 0; }; int PyObject_GenericSetAttr(...) { return 0; }; int PyObject_GetAttrString(...) { return 0; } int PyObject_HasAttrString(...) { return 0; } int PyObject_IsInstance(...) { return 0; } int PyObject_IsTrue(...) { return 0; } int PyObject_Repr(...) { return 0; } int PyObject_SetAttrString(...) { return 0; } int PyObject_Str(...) { return 0; } int PyObject_Type(...) { return 0; } int PySequence_Check(...) { return 0; } int PySequence_GetItem(...) { return 0; } int PySequence_Size(...) { return 0; } int PySequence_Tuple(...) { return 0; } int PyString_AsString(...) { return 0; } int PyString_AsStringAndSize(...) { return 0; } int PyString_FromString(...) { return 0; } int PyString_FromStringAndSize(...) { return 0; } int PyString_Size(...) { return 0; } int PyString_Type(...) { return 0; } int PySys_GetObject(...) { return 0; } int PyThreadState_Clear(...) { return 0; } int PyThreadState_Delete(...) { return 0; } int PyThreadState_Get(...) { return 0; } int PyThreadState_New(...) { return 0; } int PyThreadState_Swap(...) { return 0; } int PyTuple_GetItem(...) { return 0; } int PyTuple_New(...) { return 0; } int PyTuple_Pack(...) { return 0; } int PyTuple_Size(...) { return 0; }; int PyTuple_Type(...) { return 0; }; int PyType_GenericAlloc(...) { return 0; }; int PyType_IsSubtype(...) { return 0; } int PyType_Ready(...) { return 0; }; int PyUnicodeUCS2_FromWideChar(...) { return 0; } int PyUnicodeUCS2_AsWideChar(...) { return 0; } int PyUnicodeUCS2_GetSize(...) { return 0; } int PyUnicodeUCS4_FromWideChar(...) { return 0; } int PyUnicodeUCS4_AsWideChar(...) { return 0; } int PyUnicodeUCS4_GetSize(...) { return 0; } int PyUnicode_Type(...) { return 0; } int Py_BuildValue(...) { return 0; } int Py_InitModule4(...) { return 0; } int Py_InitModule4_64(...) { return 0; } int Py_InitModule4TraceRefs(...) { return 0; }; int _PyObject_DebugFree(...) { return 0; }; int _PyObject_Del(...) { return 0; }; int _Py_Dealloc(...) { return 0; }; int _Py_NegativeRefcount(...) { return 0; }; int _Py_RefTotal(...) { return 0; }; // We actually might call this one. int Py_IsInitialized() { return 0; } void *PyExc_AssertionError = (void *)NULL; void *PyExc_AttributeError = (void *)NULL; void *PyExc_FutureWarning = (void *)NULL; void *PyExc_IndexError = (void *)NULL; void *PyExc_RuntimeError = (void *)NULL; void *PyExc_StandardError = (void *)NULL; void *PyExc_StopIteration = (void *)NULL; void *PyExc_TypeError = (void *)NULL; void *PyExc_ValueError = (void *)NULL; void *_Py_NoneStruct = (void *)NULL; void *_Py_NotImplementedStruct = (void *)NULL; void pystub() { } <commit_msg>Add missing symbols to pystub hopefully to stop the buildbots' error diarrhoea<commit_after>// Filename: pystub.cxx // Created by: drose (09Aug00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "pystub.h" extern "C" { EXPCL_DTOOLCONFIG int PyArg_Parse(...); EXPCL_DTOOLCONFIG int PyArg_ParseTuple(...); EXPCL_DTOOLCONFIG int PyArg_ParseTupleAndKeywords(...); EXPCL_DTOOLCONFIG int PyCFunction_New(...); EXPCL_DTOOLCONFIG int PyCFunction_NewEx(...); EXPCL_DTOOLCONFIG int PyCallable_Check(...); EXPCL_DTOOLCONFIG int PyDict_DelItemString(...); EXPCL_DTOOLCONFIG int PyDict_GetItem(...); EXPCL_DTOOLCONFIG int PyDict_GetItemString(...); EXPCL_DTOOLCONFIG int PyDict_New(...); EXPCL_DTOOLCONFIG int PyDict_SetItem(...); EXPCL_DTOOLCONFIG int PyDict_SetItemString(...); EXPCL_DTOOLCONFIG int PyDict_Size(...); EXPCL_DTOOLCONFIG int PyDict_Type(...); EXPCL_DTOOLCONFIG int PyErr_Clear(...); EXPCL_DTOOLCONFIG int PyErr_ExceptionMatches(...); EXPCL_DTOOLCONFIG int PyErr_Fetch(...); EXPCL_DTOOLCONFIG int PyErr_Format(...); EXPCL_DTOOLCONFIG int PyErr_Occurred(...); EXPCL_DTOOLCONFIG int PyErr_Print(...); EXPCL_DTOOLCONFIG int PyErr_Restore(...); EXPCL_DTOOLCONFIG int PyErr_SetString(...); EXPCL_DTOOLCONFIG int PyErr_Warn(...); EXPCL_DTOOLCONFIG int PyErr_WarnEx(...); EXPCL_DTOOLCONFIG int PyEval_CallFunction(...); EXPCL_DTOOLCONFIG int PyEval_CallObjectWithKeywords(...); EXPCL_DTOOLCONFIG int PyEval_InitThreads(...); EXPCL_DTOOLCONFIG int PyEval_RestoreThread(...); EXPCL_DTOOLCONFIG int PyEval_SaveThread(...); EXPCL_DTOOLCONFIG int PyFloat_AsDouble(...); EXPCL_DTOOLCONFIG int PyFloat_FromDouble(...); EXPCL_DTOOLCONFIG int PyFloat_Type(...); EXPCL_DTOOLCONFIG int PyGen_Check(...); EXPCL_DTOOLCONFIG int PyGen_Type(...); EXPCL_DTOOLCONFIG int PyGILState_Ensure(...); EXPCL_DTOOLCONFIG int PyGILState_Release(...); EXPCL_DTOOLCONFIG int PyImport_GetModuleDict(...); EXPCL_DTOOLCONFIG int PyInt_AsLong(...); EXPCL_DTOOLCONFIG int PyInt_AsSsize_t(...); EXPCL_DTOOLCONFIG int PyInt_FromLong(...); EXPCL_DTOOLCONFIG int PyInt_Type(...); EXPCL_DTOOLCONFIG int PyList_Append(...); EXPCL_DTOOLCONFIG int PyList_AsTuple(...); EXPCL_DTOOLCONFIG int PyList_GetItem(...); EXPCL_DTOOLCONFIG int PyList_New(...); EXPCL_DTOOLCONFIG int PyList_SetItem(...); EXPCL_DTOOLCONFIG int PyLong_AsLong(...); EXPCL_DTOOLCONFIG int PyLong_AsLongLong(...); EXPCL_DTOOLCONFIG int PyLong_AsUnsignedLong(...); EXPCL_DTOOLCONFIG int PyLong_AsUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyLong_FromLong(...); EXPCL_DTOOLCONFIG int PyLong_FromLongLong(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLong(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyLong_Type(...); EXPCL_DTOOLCONFIG int PyMapping_GetItemString(...); EXPCL_DTOOLCONFIG int PyModule_AddIntConstant(...); EXPCL_DTOOLCONFIG int PyModule_AddObject(...); EXPCL_DTOOLCONFIG int PyModule_AddStringConstant(...); EXPCL_DTOOLCONFIG int PyNumber_Float(...); EXPCL_DTOOLCONFIG int PyNumber_Long(...); EXPCL_DTOOLCONFIG int PyObject_Call(...); EXPCL_DTOOLCONFIG int PyObject_CallFunction(...); EXPCL_DTOOLCONFIG int PyObject_CallMethod(...); EXPCL_DTOOLCONFIG int PyObject_CallMethodObjArgs(...); EXPCL_DTOOLCONFIG int PyObject_CallObject(...); EXPCL_DTOOLCONFIG int PyObject_Cmp(...); EXPCL_DTOOLCONFIG int PyObject_Compare(...); EXPCL_DTOOLCONFIG int PyObject_Free(...); EXPCL_DTOOLCONFIG int PyObject_GenericGetAttr(...); EXPCL_DTOOLCONFIG int PyObject_GenericSetAttr(...); EXPCL_DTOOLCONFIG int PyObject_GetAttrString(...); EXPCL_DTOOLCONFIG int PyObject_HasAttrString(...); EXPCL_DTOOLCONFIG int PyObject_IsInstance(...); EXPCL_DTOOLCONFIG int PyObject_IsTrue(...); EXPCL_DTOOLCONFIG int PyObject_Repr(...); EXPCL_DTOOLCONFIG int PyObject_SetAttrString(...); EXPCL_DTOOLCONFIG int PyObject_Str(...); EXPCL_DTOOLCONFIG int PyObject_Type(...); EXPCL_DTOOLCONFIG int PySequence_Check(...); EXPCL_DTOOLCONFIG int PySequence_Fast(...); EXPCL_DTOOLCONFIG int PySequence_GetItem(...); EXPCL_DTOOLCONFIG int PySequence_Size(...); EXPCL_DTOOLCONFIG int PySequence_Tuple(...); EXPCL_DTOOLCONFIG int PyString_AsString(...); EXPCL_DTOOLCONFIG int PyString_AsStringAndSize(...); EXPCL_DTOOLCONFIG int PyString_FromString(...); EXPCL_DTOOLCONFIG int PyString_FromStringAndSize(...); EXPCL_DTOOLCONFIG int PyString_Size(...); EXPCL_DTOOLCONFIG int PyString_Type(...); EXPCL_DTOOLCONFIG int PySys_GetObject(...); EXPCL_DTOOLCONFIG int PyThreadState_Clear(...); EXPCL_DTOOLCONFIG int PyThreadState_Delete(...); EXPCL_DTOOLCONFIG int PyThreadState_Get(...); EXPCL_DTOOLCONFIG int PyThreadState_New(...); EXPCL_DTOOLCONFIG int PyThreadState_Swap(...); EXPCL_DTOOLCONFIG int PyTuple_GetItem(...); EXPCL_DTOOLCONFIG int PyTuple_New(...); EXPCL_DTOOLCONFIG int PyTuple_Pack(...); EXPCL_DTOOLCONFIG int PyTuple_Size(...); EXPCL_DTOOLCONFIG int PyTuple_Type(...); EXPCL_DTOOLCONFIG int PyType_GenericAlloc(...); EXPCL_DTOOLCONFIG int PyType_IsSubtype(...); EXPCL_DTOOLCONFIG int PyType_Ready(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS2_FromWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS2_AsWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS2_GetSize(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS4_FromWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS4_AsWideChar(...); EXPCL_DTOOLCONFIG int PyUnicodeUCS4_GetSize(...); EXPCL_DTOOLCONFIG int PyUnicode_Type(...); EXPCL_DTOOLCONFIG int Py_BuildValue(...); EXPCL_DTOOLCONFIG int Py_InitModule4(...); EXPCL_DTOOLCONFIG int Py_InitModule4_64(...); EXPCL_DTOOLCONFIG int Py_InitModule4TraceRefs(...); EXPCL_DTOOLCONFIG int _PyObject_DebugFree(...); EXPCL_DTOOLCONFIG int _PyObject_Del(...); EXPCL_DTOOLCONFIG int _Py_Dealloc(...); EXPCL_DTOOLCONFIG int _Py_NegativeRefcount(...); EXPCL_DTOOLCONFIG int _Py_RefTotal(...); EXPCL_DTOOLCONFIG int Py_IsInitialized(); EXPCL_DTOOLCONFIG extern void *PyExc_AssertionError; EXPCL_DTOOLCONFIG extern void *PyExc_AttributeError; EXPCL_DTOOLCONFIG extern void *PyExc_FutureWarning; EXPCL_DTOOLCONFIG extern void *PyExc_IndexError; EXPCL_DTOOLCONFIG extern void *PyExc_RuntimeError; EXPCL_DTOOLCONFIG extern void *PyExc_StandardError; EXPCL_DTOOLCONFIG extern void *PyExc_StopIteration; EXPCL_DTOOLCONFIG extern void *PyExc_TypeError; EXPCL_DTOOLCONFIG extern void *PyExc_ValueError; EXPCL_DTOOLCONFIG extern void *_Py_NoneStruct; EXPCL_DTOOLCONFIG extern void *_Py_NotImplementedStruct; }; int PyArg_Parse(...) { return 0; }; int PyArg_ParseTuple(...) { return 0; } int PyArg_ParseTupleAndKeywords(...) { return 0; } int PyCFunction_New(...) { return 0; }; int PyCFunction_NewEx(...) { return 0; }; int PyCallable_Check(...) { return 0; } int PyDict_DelItemString(...) { return 0; } int PyDict_GetItem(...) { return 0; } int PyDict_GetItemString(...) { return 0; } int PyDict_New(...) { return 0; }; int PyDict_SetItem(...) { return 0; }; int PyDict_SetItemString(...) { return 0; }; int PyDict_Size(...){ return 0; } int PyDict_Type(...) { return 0; }; int PyErr_Clear(...) { return 0; }; int PyErr_ExceptionMatches(...) { return 0; }; int PyErr_Fetch(...) { return 0; } int PyErr_Format(...) { return 0; }; int PyErr_Occurred(...) { return 0; } int PyErr_Print(...) { return 0; } int PyErr_Restore(...) { return 0; } int PyErr_SetString(...) { return 0; } int PyErr_Warn(...) { return 0; } int PyErr_WarnEx(...) { return 0; } int PyEval_CallFunction(...) { return 0; } int PyEval_CallObjectWithKeywords(...) { return 0; } int PyEval_InitThreads(...) { return 0; } int PyEval_RestoreThread(...) { return 0; } int PyEval_SaveThread(...) { return 0; } int PyFloat_AsDouble(...) { return 0; } int PyFloat_FromDouble(...) { return 0; } int PyFloat_Type(...) { return 0; } int PyGen_Check(...) { return 0; } int PyGen_Type(...) { return 0; } int PyGILState_Ensure(...) { return 0; } int PyGILState_Release(...) { return 0; } int PyImport_GetModuleDict(...) { return 0; } int PyInt_AsLong(...) { return 0; } int PyInt_AsSsize_t(...) { return 0; } int PyInt_FromLong(...) { return 0; } int PyInt_Type(...) { return 0; } int PyList_Append(...) { return 0; } int PyList_AsTuple(...) { return 0; } int PyList_GetItem(...) { return 0; } int PyList_New(...) { return 0; } int PyList_SetItem(...) { return 0; } int PyLong_AsLong(...) { return 0; } int PyLong_AsLongLong(...) { return 0; } int PyLong_AsUnsignedLong(...) { return 0; } int PyLong_AsUnsignedLongLong(...) { return 0; } int PyLong_FromLong(...) { return 0; } int PyLong_FromLongLong(...) { return 0; } int PyLong_FromUnsignedLong(...) { return 0; } int PyLong_FromUnsignedLongLong(...) { return 0; } int PyLong_Type(...) { return 0; } int PyMapping_GetItemString(...) { return 0; } int PyModule_AddIntConstant(...) { return 0; }; int PyModule_AddObject(...) { return 0; }; int PyModule_AddStringConstant(...) { return 0; }; int PyNumber_Float(...) { return 0; } int PyNumber_Long(...) { return 0; } int PyObject_Call(...) { return 0; } int PyObject_CallFunction(...) { return 0; } int PyObject_CallMethod(...) { return 0; } int PyObject_CallMethodObjArgs(...) { return 0; } int PyObject_CallObject(...) { return 0; } int PyObject_Cmp(...) { return 0; } int PyObject_Compare(...) { return 0; } int PyObject_Free(...) { return 0; } int PyObject_GenericGetAttr(...) { return 0; }; int PyObject_GenericSetAttr(...) { return 0; }; int PyObject_GetAttrString(...) { return 0; } int PyObject_HasAttrString(...) { return 0; } int PyObject_IsInstance(...) { return 0; } int PyObject_IsTrue(...) { return 0; } int PyObject_Repr(...) { return 0; } int PyObject_SetAttrString(...) { return 0; } int PyObject_Str(...) { return 0; } int PyObject_Type(...) { return 0; } int PySequence_Check(...) { return 0; } int PySequence_Fast(...) { return 0; } int PySequence_GetItem(...) { return 0; } int PySequence_Size(...) { return 0; } int PySequence_Tuple(...) { return 0; } int PyString_AsString(...) { return 0; } int PyString_AsStringAndSize(...) { return 0; } int PyString_FromString(...) { return 0; } int PyString_FromStringAndSize(...) { return 0; } int PyString_Size(...) { return 0; } int PyString_Type(...) { return 0; } int PySys_GetObject(...) { return 0; } int PyThreadState_Clear(...) { return 0; } int PyThreadState_Delete(...) { return 0; } int PyThreadState_Get(...) { return 0; } int PyThreadState_New(...) { return 0; } int PyThreadState_Swap(...) { return 0; } int PyTuple_GetItem(...) { return 0; } int PyTuple_New(...) { return 0; } int PyTuple_Pack(...) { return 0; } int PyTuple_Size(...) { return 0; }; int PyTuple_Type(...) { return 0; }; int PyType_GenericAlloc(...) { return 0; }; int PyType_IsSubtype(...) { return 0; } int PyType_Ready(...) { return 0; }; int PyUnicodeUCS2_FromWideChar(...) { return 0; } int PyUnicodeUCS2_AsWideChar(...) { return 0; } int PyUnicodeUCS2_GetSize(...) { return 0; } int PyUnicodeUCS4_FromWideChar(...) { return 0; } int PyUnicodeUCS4_AsWideChar(...) { return 0; } int PyUnicodeUCS4_GetSize(...) { return 0; } int PyUnicode_Type(...) { return 0; } int Py_BuildValue(...) { return 0; } int Py_InitModule4(...) { return 0; } int Py_InitModule4_64(...) { return 0; } int Py_InitModule4TraceRefs(...) { return 0; }; int _PyObject_DebugFree(...) { return 0; }; int _PyObject_Del(...) { return 0; }; int _Py_Dealloc(...) { return 0; }; int _Py_NegativeRefcount(...) { return 0; }; int _Py_RefTotal(...) { return 0; }; // We actually might call this one. int Py_IsInitialized() { return 0; } void *PyExc_AssertionError = (void *)NULL; void *PyExc_AttributeError = (void *)NULL; void *PyExc_FutureWarning = (void *)NULL; void *PyExc_IndexError = (void *)NULL; void *PyExc_RuntimeError = (void *)NULL; void *PyExc_StandardError = (void *)NULL; void *PyExc_StopIteration = (void *)NULL; void *PyExc_TypeError = (void *)NULL; void *PyExc_ValueError = (void *)NULL; void *_Py_NoneStruct = (void *)NULL; void *_Py_NotImplementedStruct = (void *)NULL; void pystub() { } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACE_INTERFACE_HH #define DUNE_GDT_SPACE_INTERFACE_HH #include <memory> #include <dune/common/dynvector.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/stuff/la/container/pattern.hh> #include "constraints.hh" // needs to be here, since one of the above includes the config.h #include <dune/common/bartonnackmanifcheck.hh> namespace Dune { namespace GDT { template< class Traits > class SpaceInterface { public: typedef typename Traits::derived_type derived_type; typedef typename Traits::GridPartType GridPartType; static const int polOrder = Traits::polOrder; typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::EntityType EntityType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; const std::shared_ptr< const GridPartType >& gridPart() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().gridPart()); return asImp().gridPart(); } const BackendType& backend() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().backend()); return asImp().backend(); } bool continuous() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().continuous()); return asImp().continuous(); } const MapperType& mapper() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().mapper()); return asImp().mapper(); } BaseFunctionSetType baseFunctionSet(const EntityType& entity) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().baseFunctionSet(entity)); return asImp().baseFunctionSet(entity); } template< class ConstraintsType > void localConstraints(const EntityType& entity, ConstraintsType& ret) const { CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(asImp().localConstraints(entity, ret)); asImp().localConstraints(entity, ret); } PatternType* computePattern() const { return computePattern(*this); } template< class OtherSpaceType > PatternType* computePattern(const OtherSpaceType& other) const { return computePattern(*(gridPart()), other); } template< class LocalGridPartType, class OtherSpaceType > PatternType* computePattern(const LocalGridPartType& localGridPart, const OtherSpaceType& otherSpace) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().computePattern(localGridPart, otherSpace)); return asImp().computePattern(localGridPart, otherSpace); } private: class BasisVisualization : public Dune::VTKFunction< typename GridPartType::GridViewType > { static_assert(dimRangeCols == 1, "Not implemented yet!"); public: typedef typename BaseFunctionSetType::DomainType DomainType; typedef typename BaseFunctionSetType::RangeType RangeType; BasisVisualization(const derived_type& sp, const size_t ind, const std::string nm = "basis") : space_(sp) , index_(ind) , values_(space_.mapper().maxNumDofs(), RangeType(0)) , name_(nm) { if (index_ >= space_.mapper().maxNumDofs()) DUNE_THROW(Dune::RangeError, "index has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << index_ << ")!"); } virtual std::string name() const { return name_; } /** \defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' */ /* @{ */ virtual int ncomps() const { return dimRange; } virtual double evaluate(int component, const EntityType& entity, const DomainType& xx) const { const auto baseFunctionSet = space_.baseFunctionSet(entity); if (component < 0) DUNE_THROW(Dune::RangeError, "component must not be negative (is " << component << ")!"); if (component < int(baseFunctionSet.size())) { baseFunctionSet.evaluate(xx, values_); assert(component < int(values_.size()) && "This should not happen!"); return values_[index_][component]; } else if (component < int(space_.mapper().maxNumDofs())) return 0.0; else DUNE_THROW(Dune::RangeError, "component has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << component << ")!"); } /* @} */ private: const derived_type& space_; const size_t index_; mutable std::vector< RangeType > values_; const std::string name_; }; // class BasisVisualization public: void visualize(const std::string filename_prefix = "") const { std::string filename = filename_prefix; if (filename.empty()) { filename = "dune.gdt.space"; } typedef typename Dune::VTKWriter< typename GridPartType::GridViewType > VTKWriterType; VTKWriterType vtk_writer(gridPart()->gridView(), Dune::VTK::nonconforming); for (size_t ii = 0; ii < mapper().maxNumDofs(); ++ii) { std::string number = ""; if (ii == 1) number = "1st"; else if (ii == 2) number = "2nd"; else if (ii == 3) number = "3rd"; else number = Stuff::Common::toString(ii) + "th"; const auto iith_baseFunction = std::make_shared< BasisVisualization >(asImp(), ii, number + " basis"); vtk_writer.addVertexData(iith_baseFunction); } vtk_writer.write(filename); } // ... visualize(...) derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } protected: /** * \brief computes a sparsity pattern, where this space is the test space (rows/outer) and the other space is the * ansatz space (cols/inner) */ template< class LocalGridPartType, class O > PatternType* computeCodim0Pattern(const LocalGridPartType& localGridPart, const SpaceInterface< O >& otherSpace) const { PatternType* ret = new PatternType(mapper().size()); PatternType& pattern = *ret; // walk the grid part for (typename LocalGridPartType::template Codim< 0 >::IteratorType entityIt = localGridPart.template begin< 0 >(); entityIt != localGridPart.template end< 0 >(); ++entityIt) { const typename LocalGridPartType::template Codim< 0 >::EntityType& entity = *entityIt; // get basefunctionsets const auto testBase = baseFunctionSet(entity); const auto ansatzBase = otherSpace.baseFunctionSet(entity); Dune::DynamicVector< size_t > globalRows(testBase.size(), 0); mapper().globalIndices(entity, globalRows); Dune::DynamicVector< size_t > globalCols(ansatzBase.size(), 0); otherSpace.mapper().globalIndices(entity, globalCols); for (size_t ii = 0; ii < testBase.size(); ++ii) { auto& columns = pattern.inner(globalRows[ii]); for (size_t jj = 0; jj < ansatzBase.size(); ++jj) { columns.insert(globalCols[jj]); } } } // walk the grid part return ret; } // ... computeVolumePattern(...) /** * \brief computes a DG sparsity pattern, where this space is the test space (rows/outer) and the other space is the * ansatz space (cols/inner) */ template< class LocalGridPartType, class O > PatternType* computeCodim0AndCodim1Pattern(const LocalGridPartType& local_grid_part, const SpaceInterface< O >& other_space) const { // prepare PatternType* ret = new PatternType(mapper().size()); PatternType& pattern = *ret; Dune::DynamicVector< size_t > global_rows(mapper().maxNumDofs(), 0); Dune::DynamicVector< size_t > global_cols(other_space.mapper().maxNumDofs(), 0); // walk the grid part const auto entity_it_end = local_grid_part.template end< 0 >(); for (auto entity_it = local_grid_part.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get basefunctionsets const auto test_base_entity = baseFunctionSet(entity); const auto ansatz_base_entity = other_space.baseFunctionSet(entity); mapper().globalIndices(entity, global_rows); other_space.mapper().globalIndices(entity, global_cols); // compute entity/entity for (size_t ii = 0; ii < test_base_entity.size(); ++ii) { auto& columns = pattern.inner(global_rows[ii]); for (size_t jj = 0; jj < ansatz_base_entity.size(); ++jj) { columns.insert(global_cols[jj]); } } // walk the intersections const auto intersection_it_end = local_grid_part.iend(entity); for (auto intersection_it = local_grid_part.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; // get the neighbour if (intersection.neighbor() && !intersection.boundary()) { const auto neighbour_ptr = intersection.outside(); const auto& neighbour = *neighbour_ptr; // get the basis const auto ansatz_base_neighbour = other_space.baseFunctionSet(neighbour); other_space.mapper().globalIndices(neighbour, global_cols); // compute entity/neighbour for (size_t ii = 0; ii < test_base_entity.size(); ++ii) { auto& columns = pattern.inner(global_rows[ii]); for (size_t jj = 0; jj < ansatz_base_neighbour.size(); ++jj) { columns.insert(global_cols[jj]); } } } // get the neighbour } // walk the intersections } // walk the grid part return ret; } // ... computeVolumeAndCouplingPattern(...) template< class LocalGridPartType, class O > PatternType* computeCodim1Pattern(const LocalGridPartType& local_grid_part, const SpaceInterface< O >& other_space) const { // prepare PatternType* ret = new PatternType(mapper().size()); PatternType& pattern = *ret; Dune::DynamicVector< size_t > global_rows(mapper().maxNumDofs(), 0); Dune::DynamicVector< size_t > global_cols(other_space.mapper().maxNumDofs(), 0); // walk the grid part const auto entity_it_end = local_grid_part.template end< 0 >(); for (auto entity_it = local_grid_part.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get basefunctionsets const auto test_base_entity = baseFunctionSet(entity); mapper().globalIndices(entity, global_rows); // walk the intersections const auto intersection_it_end = local_grid_part.iend(entity); for (auto intersection_it = local_grid_part.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; // get the neighbour if (intersection.neighbor() && !intersection.boundary()) { const auto neighbour_ptr = intersection.outside(); const auto& neighbour = *neighbour_ptr; // get the basis const auto ansatz_base_neighbour = other_space.baseFunctionSet(neighbour); other_space.mapper().globalIndices(neighbour, global_cols); // compute entity/neighbour for (size_t ii = 0; ii < test_base_entity.size(); ++ii) { auto& columns = pattern.inner(global_rows[ii]); for (size_t jj = 0; jj < ansatz_base_neighbour.size(); ++jj) { columns.insert(global_cols[jj]); } } } // get the neighbour } // walk the intersections } // walk the grid part return ret; } // ... computeCodim1Pattern(...) }; // class SpaceInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACE_INTERFACE_HH <commit_msg>[space.interfaces] fixed wrong return type<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACE_INTERFACE_HH #define DUNE_GDT_SPACE_INTERFACE_HH #include <memory> #include <dune/common/dynvector.hh> #include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/stuff/la/container/pattern.hh> #include "constraints.hh" // needs to be here, since one of the above includes the config.h #include <dune/common/bartonnackmanifcheck.hh> namespace Dune { namespace GDT { template< class Traits > class SpaceInterface { public: typedef typename Traits::derived_type derived_type; typedef typename Traits::GridPartType GridPartType; static const int polOrder = Traits::polOrder; typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::EntityType EntityType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; std::shared_ptr< const GridPartType > gridPart() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().gridPart()); return asImp().gridPart(); } const BackendType& backend() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().backend()); return asImp().backend(); } bool continuous() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().continuous()); return asImp().continuous(); } const MapperType& mapper() const { CHECK_INTERFACE_IMPLEMENTATION(asImp().mapper()); return asImp().mapper(); } BaseFunctionSetType baseFunctionSet(const EntityType& entity) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().baseFunctionSet(entity)); return asImp().baseFunctionSet(entity); } template< class ConstraintsType > void localConstraints(const EntityType& entity, ConstraintsType& ret) const { CHECK_AND_CALL_INTERFACE_IMPLEMENTATION(asImp().localConstraints(entity, ret)); asImp().localConstraints(entity, ret); } PatternType* computePattern() const { return computePattern(*this); } template< class OtherSpaceType > PatternType* computePattern(const OtherSpaceType& other) const { return computePattern(*(gridPart()), other); } template< class LocalGridPartType, class OtherSpaceType > PatternType* computePattern(const LocalGridPartType& localGridPart, const OtherSpaceType& otherSpace) const { CHECK_INTERFACE_IMPLEMENTATION(asImp().computePattern(localGridPart, otherSpace)); return asImp().computePattern(localGridPart, otherSpace); } private: class BasisVisualization : public Dune::VTKFunction< typename GridPartType::GridViewType > { static_assert(dimRangeCols == 1, "Not implemented yet!"); public: typedef typename BaseFunctionSetType::DomainType DomainType; typedef typename BaseFunctionSetType::RangeType RangeType; BasisVisualization(const derived_type& sp, const size_t ind, const std::string nm = "basis") : space_(sp) , index_(ind) , values_(space_.mapper().maxNumDofs(), RangeType(0)) , name_(nm) { if (index_ >= space_.mapper().maxNumDofs()) DUNE_THROW(Dune::RangeError, "index has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << index_ << ")!"); } virtual std::string name() const { return name_; } /** \defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' */ /* @{ */ virtual int ncomps() const { return dimRange; } virtual double evaluate(int component, const EntityType& entity, const DomainType& xx) const { const auto baseFunctionSet = space_.baseFunctionSet(entity); if (component < 0) DUNE_THROW(Dune::RangeError, "component must not be negative (is " << component << ")!"); if (component < int(baseFunctionSet.size())) { baseFunctionSet.evaluate(xx, values_); assert(component < int(values_.size()) && "This should not happen!"); return values_[index_][component]; } else if (component < int(space_.mapper().maxNumDofs())) return 0.0; else DUNE_THROW(Dune::RangeError, "component has to be smaller than " << space_.mapper().maxNumDofs() << "(is " << component << ")!"); } /* @} */ private: const derived_type& space_; const size_t index_; mutable std::vector< RangeType > values_; const std::string name_; }; // class BasisVisualization public: void visualize(const std::string filename_prefix = "") const { std::string filename = filename_prefix; if (filename.empty()) { filename = "dune.gdt.space"; } typedef typename Dune::VTKWriter< typename GridPartType::GridViewType > VTKWriterType; VTKWriterType vtk_writer(gridPart()->gridView(), Dune::VTK::nonconforming); for (size_t ii = 0; ii < mapper().maxNumDofs(); ++ii) { std::string number = ""; if (ii == 1) number = "1st"; else if (ii == 2) number = "2nd"; else if (ii == 3) number = "3rd"; else number = Stuff::Common::toString(ii) + "th"; const auto iith_baseFunction = std::make_shared< BasisVisualization >(asImp(), ii, number + " basis"); vtk_writer.addVertexData(iith_baseFunction); } vtk_writer.write(filename); } // ... visualize(...) derived_type& asImp() { return static_cast< derived_type& >(*this); } const derived_type& asImp() const { return static_cast< const derived_type& >(*this); } protected: /** * \brief computes a sparsity pattern, where this space is the test space (rows/outer) and the other space is the * ansatz space (cols/inner) */ template< class LocalGridPartType, class O > PatternType* computeCodim0Pattern(const LocalGridPartType& localGridPart, const SpaceInterface< O >& otherSpace) const { PatternType* ret = new PatternType(mapper().size()); PatternType& pattern = *ret; // walk the grid part for (typename LocalGridPartType::template Codim< 0 >::IteratorType entityIt = localGridPart.template begin< 0 >(); entityIt != localGridPart.template end< 0 >(); ++entityIt) { const typename LocalGridPartType::template Codim< 0 >::EntityType& entity = *entityIt; // get basefunctionsets const auto testBase = baseFunctionSet(entity); const auto ansatzBase = otherSpace.baseFunctionSet(entity); Dune::DynamicVector< size_t > globalRows(testBase.size(), 0); mapper().globalIndices(entity, globalRows); Dune::DynamicVector< size_t > globalCols(ansatzBase.size(), 0); otherSpace.mapper().globalIndices(entity, globalCols); for (size_t ii = 0; ii < testBase.size(); ++ii) { auto& columns = pattern.inner(globalRows[ii]); for (size_t jj = 0; jj < ansatzBase.size(); ++jj) { columns.insert(globalCols[jj]); } } } // walk the grid part return ret; } // ... computeVolumePattern(...) /** * \brief computes a DG sparsity pattern, where this space is the test space (rows/outer) and the other space is the * ansatz space (cols/inner) */ template< class LocalGridPartType, class O > PatternType* computeCodim0AndCodim1Pattern(const LocalGridPartType& local_grid_part, const SpaceInterface< O >& other_space) const { // prepare PatternType* ret = new PatternType(mapper().size()); PatternType& pattern = *ret; Dune::DynamicVector< size_t > global_rows(mapper().maxNumDofs(), 0); Dune::DynamicVector< size_t > global_cols(other_space.mapper().maxNumDofs(), 0); // walk the grid part const auto entity_it_end = local_grid_part.template end< 0 >(); for (auto entity_it = local_grid_part.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get basefunctionsets const auto test_base_entity = baseFunctionSet(entity); const auto ansatz_base_entity = other_space.baseFunctionSet(entity); mapper().globalIndices(entity, global_rows); other_space.mapper().globalIndices(entity, global_cols); // compute entity/entity for (size_t ii = 0; ii < test_base_entity.size(); ++ii) { auto& columns = pattern.inner(global_rows[ii]); for (size_t jj = 0; jj < ansatz_base_entity.size(); ++jj) { columns.insert(global_cols[jj]); } } // walk the intersections const auto intersection_it_end = local_grid_part.iend(entity); for (auto intersection_it = local_grid_part.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; // get the neighbour if (intersection.neighbor() && !intersection.boundary()) { const auto neighbour_ptr = intersection.outside(); const auto& neighbour = *neighbour_ptr; // get the basis const auto ansatz_base_neighbour = other_space.baseFunctionSet(neighbour); other_space.mapper().globalIndices(neighbour, global_cols); // compute entity/neighbour for (size_t ii = 0; ii < test_base_entity.size(); ++ii) { auto& columns = pattern.inner(global_rows[ii]); for (size_t jj = 0; jj < ansatz_base_neighbour.size(); ++jj) { columns.insert(global_cols[jj]); } } } // get the neighbour } // walk the intersections } // walk the grid part return ret; } // ... computeVolumeAndCouplingPattern(...) template< class LocalGridPartType, class O > PatternType* computeCodim1Pattern(const LocalGridPartType& local_grid_part, const SpaceInterface< O >& other_space) const { // prepare PatternType* ret = new PatternType(mapper().size()); PatternType& pattern = *ret; Dune::DynamicVector< size_t > global_rows(mapper().maxNumDofs(), 0); Dune::DynamicVector< size_t > global_cols(other_space.mapper().maxNumDofs(), 0); // walk the grid part const auto entity_it_end = local_grid_part.template end< 0 >(); for (auto entity_it = local_grid_part.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get basefunctionsets const auto test_base_entity = baseFunctionSet(entity); mapper().globalIndices(entity, global_rows); // walk the intersections const auto intersection_it_end = local_grid_part.iend(entity); for (auto intersection_it = local_grid_part.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; // get the neighbour if (intersection.neighbor() && !intersection.boundary()) { const auto neighbour_ptr = intersection.outside(); const auto& neighbour = *neighbour_ptr; // get the basis const auto ansatz_base_neighbour = other_space.baseFunctionSet(neighbour); other_space.mapper().globalIndices(neighbour, global_cols); // compute entity/neighbour for (size_t ii = 0; ii < test_base_entity.size(); ++ii) { auto& columns = pattern.inner(global_rows[ii]); for (size_t jj = 0; jj < ansatz_base_neighbour.size(); ++jj) { columns.insert(global_cols[jj]); } } } // get the neighbour } // walk the intersections } // walk the grid part return ret; } // ... computeCodim1Pattern(...) }; // class SpaceInterface } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACE_INTERFACE_HH <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "condensedbitvectors.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/rcuvector.h> #include <cassert> using vespalib::IllegalArgumentException; using vespalib::make_string; using vespalib::GenerationHolder; namespace search { namespace { template <typename T> class CondensedBitVectorT : public CondensedBitVector { public: CondensedBitVectorT(size_t sz, GenerationHolder &genHolder) : _v(sz, 30, 1000, genHolder) { for (size_t i = 0; i < sz; ++i) { _v.push_back(0); } } private: static uint8_t countBits(T v) { return ((sizeof(T)) <= 4) ? __builtin_popcount(v) : __builtin_popcountl(v); } T computeMask(const KeySet & keys) const __attribute__ ((noinline)) { T mask(0); for (size_t i : keys) { assert(i < getKeyCapacity()); mask |= (B << i); } return mask; } static const uint64_t B = 1ul; void initializeCountVector(const KeySet & keys, CountVector & cv) const override { struct S { void operator () (uint8_t & cv, uint8_t v) { cv = v; } }; computeCountVector(computeMask(keys), cv, S()); } void addCountVector(const KeySet & keys, CountVector & cv) const override { struct S { void operator () (uint8_t & cv, uint8_t v) { cv += v; } }; computeCountVector(computeMask(keys), cv, S()); } void clearIndex(uint32_t index) override { _v[index] = 0; } template <typename F> void computeCountVector(T mask, CountVector & cv, F func) const __attribute__((noinline)); template <typename F> void computeTail(T mask, CountVector & cv, F func, size_t i) const __attribute__((noinline)); void set(Key key, uint32_t index, bool v) override { assert(key < getKeyCapacity()); if (v) { _v[index] |= B << key; } else { _v[index] &= ~(B << key); } } bool get(Key key, uint32_t index) const override { assert(key < getKeyCapacity()); return (_v[index] & (B << key)) != 0; } size_t getKeyCapacity() const override { return sizeof(T)*8; } size_t getCapacity() const override { return _v.capacity(); } size_t getSize() const override { return _v.size(); } void adjustDocIdLimit(uint32_t docId) override; vespalib::RcuVectorBase<T> _v; }; template <typename T> template <typename F> void CondensedBitVectorT<T>::computeCountVector(T mask, CountVector & cv, F func) const { size_t i(0); const size_t UNROLL = 2; uint8_t *d = &cv[0]; const T *v = &_v[0]; for (const size_t m(cv.size() - (UNROLL - 1)); i < m; i+=UNROLL) { for (size_t j(0); j < UNROLL; j++) { func(d[i+j], countBits(v[i+j] & mask)); } } computeTail(mask, cv, func, i); } template <typename T> template <typename F> void CondensedBitVectorT<T>::computeTail(T mask, CountVector & cv, F func, size_t i) const { for (; i < cv.size(); i++) { func(cv[i], countBits(_v[i] & mask)); } } template <typename T> void CondensedBitVectorT<T>::adjustDocIdLimit(uint32_t docId) { _v.reserve(docId+1); while (_v.size() <= docId) { _v.push_back(0); } } void throwIllegalKey(size_t numKeys, size_t key) __attribute__((noinline)); void throwIllegalKey(size_t numKeys, size_t key) { throw IllegalArgumentException(make_string("All %ld possible keys are used. Key %ld is not added", numKeys, key), VESPA_STRLOC); } } CondensedBitVector::~CondensedBitVector() = default; void CondensedBitVector::addKey(Key key) const { if ( ! hasKey(key)) { throwIllegalKey(getKeyCapacity(), key); } } CondensedBitVector::UP CondensedBitVector::create(size_t size, GenerationHolder &genHolder) { return std::make_unique<CondensedBitVectorT<uint32_t>>(size, genHolder); } } <commit_msg>Use acquire_elem_ref() in condensed bit vector.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "condensedbitvectors.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/rcuvector.h> #include <cassert> using vespalib::IllegalArgumentException; using vespalib::make_string; using vespalib::GenerationHolder; namespace search { namespace { template <typename T> class CondensedBitVectorT : public CondensedBitVector { public: CondensedBitVectorT(size_t sz, GenerationHolder &genHolder) : _v(sz, 30, 1000, genHolder) { for (size_t i = 0; i < sz; ++i) { _v.push_back(0); } } private: static uint8_t countBits(T v) { return ((sizeof(T)) <= 4) ? __builtin_popcount(v) : __builtin_popcountl(v); } T computeMask(const KeySet & keys) const __attribute__ ((noinline)) { T mask(0); for (size_t i : keys) { assert(i < getKeyCapacity()); mask |= (B << i); } return mask; } static const uint64_t B = 1ul; void initializeCountVector(const KeySet & keys, CountVector & cv) const override { struct S { void operator () (uint8_t & cv, uint8_t v) { cv = v; } }; computeCountVector(computeMask(keys), cv, S()); } void addCountVector(const KeySet & keys, CountVector & cv) const override { struct S { void operator () (uint8_t & cv, uint8_t v) { cv += v; } }; computeCountVector(computeMask(keys), cv, S()); } void clearIndex(uint32_t index) override { _v[index] = 0; } template <typename F> void computeCountVector(T mask, CountVector & cv, F func) const __attribute__((noinline)); template <typename F> void computeTail(T mask, CountVector & cv, F func, size_t i) const __attribute__((noinline)); void set(Key key, uint32_t index, bool v) override { assert(key < getKeyCapacity()); if (v) { _v[index] |= B << key; } else { _v[index] &= ~(B << key); } } bool get(Key key, uint32_t index) const override { assert(key < getKeyCapacity()); return (_v.acquire_elem_ref(index) & (B << key)) != 0; } size_t getKeyCapacity() const override { return sizeof(T)*8; } size_t getCapacity() const override { return _v.capacity(); } size_t getSize() const override { return _v.size(); } void adjustDocIdLimit(uint32_t docId) override; vespalib::RcuVectorBase<T> _v; }; template <typename T> template <typename F> void CondensedBitVectorT<T>::computeCountVector(T mask, CountVector & cv, F func) const { size_t i(0); const size_t UNROLL = 2; uint8_t *d = &cv[0]; const T *v = &_v.acquire_elem_ref(0); for (const size_t m(cv.size() - (UNROLL - 1)); i < m; i+=UNROLL) { for (size_t j(0); j < UNROLL; j++) { func(d[i+j], countBits(v[i+j] & mask)); } } computeTail(mask, cv, func, i); } template <typename T> template <typename F> void CondensedBitVectorT<T>::computeTail(T mask, CountVector & cv, F func, size_t i) const { auto* v = &_v.acquire_elem_ref(0); for (; i < cv.size(); i++) { func(cv[i], countBits(v[i] & mask)); } } template <typename T> void CondensedBitVectorT<T>::adjustDocIdLimit(uint32_t docId) { _v.reserve(docId+1); while (_v.size() <= docId) { _v.push_back(0); } } void throwIllegalKey(size_t numKeys, size_t key) __attribute__((noinline)); void throwIllegalKey(size_t numKeys, size_t key) { throw IllegalArgumentException(make_string("All %ld possible keys are used. Key %ld is not added", numKeys, key), VESPA_STRLOC); } } CondensedBitVector::~CondensedBitVector() = default; void CondensedBitVector::addKey(Key key) const { if ( ! hasKey(key)) { throwIllegalKey(getKeyCapacity(), key); } } CondensedBitVector::UP CondensedBitVector::create(size_t size, GenerationHolder &genHolder) { return std::make_unique<CondensedBitVectorT<uint32_t>>(size, genHolder); } } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_RANDOM_HH #define DUNE_STUFF_RANDOM_HH #include <random> #include <boost/assign/list_of.hpp> namespace Dune { namespace Stuff { namespace Common { template < typename T, bool = std::is_integral<T>::value > struct UniformDistributionSelector { }; template < typename T > struct UniformDistributionSelector<T,true> { typedef std::uniform_int_distribution <T> type; }; template < typename T > struct UniformDistributionSelector<T,false> { typedef std::uniform_real_distribution<T> type; }; template < class T, class DistributionImp , class EngineImp > struct RNG { typedef DistributionImp DistributionType; typedef EngineImp EngineType; EngineType generator; DistributionType distribution; RNG(EngineType g, DistributionType d) : generator(g) , distribution(d) {} inline T operator()() { return distribution(generator); } }; namespace { const std::string alphanums( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "1234567890"); const std::string other_printables( "!@#$%^&*()" "`~-_=+[{]{\\|;:'\",<.>/? "); } class RandomStrings : public RNG<std::string, std::uniform_int_distribution<int>, std::mt19937 > { typedef RNG<std::string, std::uniform_int_distribution<int>, std::mt19937 > BaseType; const size_t length; public: RandomStrings(size_t l) : BaseType(std::mt19937(std::random_device()()), std::uniform_int_distribution<int>(0,alphanums.size() - 1)) , length(l) {} inline std::string operator ()() { std::string ret(length,'\0'); std::generate(std::begin(ret), std::end(ret), [=] () { return alphanums[distribution(generator)]; }); return ret; } }; template < class T > class DefaultRNG : public RNG<T, typename UniformDistributionSelector<T>::type, std::default_random_engine > { typedef RNG<T, typename UniformDistributionSelector<T>::type, std::default_random_engine > BaseType; public: DefaultRNG(T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max() ) : BaseType(std::default_random_engine(std::random_device()()), typename UniformDistributionSelector<T>::type(min, max)) {} }; template < > class DefaultRNG<std::string> : public RandomStrings { public: DefaultRNG(size_t ilength = 12) : RandomStrings(ilength) {} }; } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_RANDOM_HH <commit_msg>[common.random] fix warning<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_RANDOM_HH #define DUNE_STUFF_RANDOM_HH #include <random> #include <limits> #include <boost/assign/list_of.hpp> namespace Dune { namespace Stuff { namespace Common { template < typename T, bool = std::is_integral<T>::value > struct UniformDistributionSelector { }; template < typename T > struct UniformDistributionSelector<T,true> { typedef std::uniform_int_distribution <T> type; }; template < typename T > struct UniformDistributionSelector<T,false> { typedef std::uniform_real_distribution<T> type; }; template < class T, class DistributionImp , class EngineImp > struct RNG { typedef DistributionImp DistributionType; typedef EngineImp EngineType; EngineType generator; DistributionType distribution; RNG(EngineType g, DistributionType d) : generator(g) , distribution(d) {} inline T operator()() { return distribution(generator); } }; namespace { const std::string alphanums( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "1234567890"); const std::string other_printables( "!@#$%^&*()" "`~-_=+[{]{\\|;:'\",<.>/? "); } class RandomStrings : public RNG<std::string, std::uniform_int_distribution<int>, std::mt19937 > { typedef RNG<std::string, std::uniform_int_distribution<int>, std::mt19937 > BaseType; const size_t length; public: RandomStrings(size_t l) : BaseType(std::mt19937(std::random_device()()), std::uniform_int_distribution<int>(0,assert_is_int_compatible_and_convert(alphanums.size() - 1))) , length(l) {} inline std::string operator ()() { std::string ret(length,'\0'); std::generate(std::begin(ret), std::end(ret), [=] () { return alphanums[distribution(generator)]; }); return ret; } private: static inline int assert_is_int_compatible_and_convert(size_t size) { assert(size < std::numeric_limits< int >::max()); return int(size); } }; template < class T > class DefaultRNG : public RNG<T, typename UniformDistributionSelector<T>::type, std::default_random_engine > { typedef RNG<T, typename UniformDistributionSelector<T>::type, std::default_random_engine > BaseType; public: DefaultRNG(T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max() ) : BaseType(std::default_random_engine(std::random_device()()), typename UniformDistributionSelector<T>::type(min, max)) {} }; template < > class DefaultRNG<std::string> : public RandomStrings { public: DefaultRNG(size_t ilength = 12) : RandomStrings(ilength) {} }; } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_RANDOM_HH <|endoftext|>
<commit_before>// Write a print function that print a text on the screen. If the type of the string is int include a space between the values. Do NOT change existing code. // Hint: Start by implementing the generic version. #include <iostream> #include <seqan/sequence.h> int computeScore(seqan::String<char> subText, seqan::String<char> pattern) { int localScore = 0; for (unsigned i = 0; i < seqan::length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText> void print(TText const & text) { std::cout << text << std::endl; } int main() { seqan::String<char> text = "This is an awesome tutorial to get to now the basic principles of SeqAn!"; seqan::String<char> pattern = "tutorial"; print(text); seqan::String<int> score; seqan::resize(score, seqan::length(text), 0); for (unsigned i = 0; i < seqan::length(text) - seqan::length(pattern) + 1; ++i) score[i] = computeScore(seqan::infix(text, i, i + seqan::length(pattern)), pattern); print(score); return 0; } <commit_msg>[DOC] Added the first assignment of the new index tutorial.<commit_after>// Write a print function that print a text on the screen. If the type of the string is int include a space between the values. Do NOT change existing code. // Hint: Start by implementing the generic version. #include <iostream> #include <seqan/file.h> #include <seqan/sequence.h> int computeScore(seqan::String<char> subText, seqan::String<char> pattern) { int localScore = 0; for (unsigned i = 0; i < seqan::length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText> void print(TText const & text) { std::cout << text << std::endl; } int main() { seqan::String<char> text = "This is an awesome tutorial to get to now the basic principles of SeqAn!"; seqan::String<char> pattern = "tutorial"; print(text); seqan::String<int> score; seqan::resize(score, seqan::length(text), 0); for (unsigned i = 0; i < seqan::length(text) - seqan::length(pattern) + 1; ++i) score[i] = computeScore(seqan::infix(text, i, i + seqan::length(pattern)), pattern); print(score); return 0; } <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_RANGES_RANGES_HH #define DUNE_STUFF_RANGES_RANGES_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #else #include "config.h" #endif // ifdef HAVE_CMAKE_CONFIG #if HAVE_DUNE_GRID #include <dune/stuff/common/disable_warnings.hh> #include <dune/grid/common/gridview.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <boost/serialization/static_warning.hpp> #include <boost/iterator/iterator_facade.hpp> #endif #if HAVE_DUNE_FEM #include <dune/fem/version.hh> #include <dune/stuff/common/disable_warnings.hh> #include <dune/fem/function/common/discretefunction.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/fem/gridpart/common/gridpart.hh> #include <dune/fem/space/lagrange/lagrangepoints.hh> #endif #include <dune/stuff/common/math.hh> #include <dune/stuff/fem/namespace.hh> namespace Dune { #if HAVE_DUNE_FEM namespace Fem { template < class DiscreteFunctionTraits > auto begin( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dbegin()) { return func.dbegin(); } template < class DiscreteFunctionTraits > auto end( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dend()) { return func.dend(); } template < class DiscreteFunctionTraits > auto begin( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dbegin()) { return func.dbegin(); } template < class DiscreteFunctionTraits > auto end( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dend()) { return func.dend(); } } // namespace Fem #endif } //namespace Dune namespace Dune { namespace Stuff { namespace Common { #if HAVE_DUNE_GRID //! adapter enabling view usage in range-based for template < class GridViewType, int codim = 0> class ViewRange { const GridViewType& view_; public: ViewRange(const GridViewType& view) :view_(view) { BOOST_STATIC_WARNING(codim == 0 && "unnecessary ViewRange usage with codim 0"); } typename GridViewType::template Codim< codim >::Iterator begin() const { return view_.template begin< codim >(); } typename GridViewType::template Codim< codim >::Iterator end() const { return view_.template end< codim >(); } }; template < class GridViewTraits, int codim = 0> ViewRange<Dune::GridView<GridViewTraits>, codim> viewRange(const Dune::GridView<GridViewTraits>& view) { return ViewRange<Dune::GridView<GridViewTraits>, codim>(view); } /** adapter enabling intersectionniterator usage in range-based for * works for GridParts and GridViews */ template < class GridAbstractionType, class EntityType > class IntersectionRange { const GridAbstractionType& view_; const EntityType& entity_; public: IntersectionRange(const GridAbstractionType& view, const EntityType& entity) : view_(view) , entity_(entity) {} auto begin() const -> decltype(view_.ibegin(entity_)) { return view_.ibegin(entity_); } auto end() const -> decltype(view_.iend(entity_)) { return view_.iend(entity_); } }; template < class GridViewTraits> IntersectionRange<Dune::GridView<GridViewTraits>, typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity> intersectionRange(const Dune::GridView<GridViewTraits>& gridview, const typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity& entity) { return IntersectionRange<Dune::GridView<GridViewTraits>, typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity>(gridview, entity); } //! custom const iterator for \ref FixedMap template <class GeometryType> class ConstCornerIterator : public boost::iterator_facade< ConstCornerIterator<GeometryType> , const typename GeometryType::GlobalCoordinate , boost::forward_traversal_tag > { typedef ConstCornerIterator<GeometryType> ThisType; typedef typename GeometryType::GlobalCoordinate CornerType; public: ConstCornerIterator() :index_(-1) , geometry_(nullptr) {} explicit ConstCornerIterator(const GeometryType*const geometry, int i = 0) : index_(i) , geometry_(geometry) {} private: friend class boost::iterator_core_access; void increment() { index_++; } bool equal(ThisType const& other) const { return this->geometry_ && (index_ == other.index_) && (this->geometry_ == other.geometry_); } const CornerType& dereference() const { return geometry_->corner(index_); } int index_; const GeometryType * const geometry_; }; template <class GeometryType> class CornerRange { typedef ConstCornerIterator<GeometryType> IteratorType; public: CornerRange(const GeometryType& geometry) : geometry_(geometry) {} IteratorType begin() const { return IteratorType(geometry_, 0); } IteratorType end() const { return IteratorType(geometry_, geometry_->corners()); } private: const GeometryType& geometry_; }; template <int mydim, int cdim, class GridImp, template< int, int, class > class GeometryImp> CornerRange<Dune::Geometry< mydim, cdim, GridImp, GeometryImp>> cornerRange(const Dune::Geometry< mydim, cdim, GridImp, GeometryImp>& geometry) { return CornerRange<Dune::Geometry< mydim, cdim, GridImp, GeometryImp>>(geometry); } template <int mydim, int cdim, class GridImp, template< int, int, class > class EntityImp> auto cornerRange(const Dune::Entity< mydim, cdim, GridImp, EntityImp>& entity) -> ConstCornerIterator<decltype(entity.geometry())> { return CornerRange<decltype(entity.geometry())>(entity.geometry()); } #endif //#if HAVE_DUNE_GRID #if HAVE_DUNE_FEM //! Range adapter for lagrange points from lagrange spaces template < class GridPartType, int order, int faceCodim > class LagrangePointSetRange { typedef Dune::Fem::LagrangePointSet<GridPartType, order> LagrangePointSetType; typedef typename LagrangePointSetType::template Codim< faceCodim >::SubEntityIteratorType SubEntityIteratorType; const LagrangePointSetType& lp_set_; const unsigned int subEntity_; public: /** the template isn't lazyness here, the underlying set is templated on it too */ template < class DiscreteFunctionspaceType, class EntityType > LagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const unsigned int subEntity) : lp_set_(space.lagrangePointSet(entity)) , subEntity_(subEntity) {} LagrangePointSetRange(const LagrangePointSetType& lp_set, const unsigned int subEntity) : lp_set_(lp_set) , subEntity_(subEntity) {} SubEntityIteratorType begin() const { return lp_set_.template beginSubEntity< faceCodim >(subEntity_); } SubEntityIteratorType end() const { return lp_set_.template endSubEntity< faceCodim >(subEntity_); } }; template < int codim, class DiscreteFunctionspaceType, class EntityType > LagrangePointSetRange<typename DiscreteFunctionspaceType::GridPartType, DiscreteFunctionspaceType::polynomialOrder, codim> lagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const int subEntity) { return LagrangePointSetRange<typename DiscreteFunctionspaceType::GridPartType, DiscreteFunctionspaceType::polynomialOrder, codim>(space, entity, subEntity); } template < class LgPointSetType, int codim = 1 > LagrangePointSetRange<typename LgPointSetType::GridPartType, LgPointSetType::polynomialOrder, codim> lagrangePointSetRange(const LgPointSetType& lpset, const int subEntity) { return LagrangePointSetRange<typename LgPointSetType::GridPartType, LgPointSetType::polynomialOrder, codim>(lpset, subEntity); } template < class GridPartTraits > IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>, typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType> intersectionRange(const Dune::Fem::GridPartInterface<GridPartTraits>& gridpart, const typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType& entity) { return IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>, typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType>(gridpart, entity); } #endif //HAVE_DUNE_FEM //! get a vector with values in [start : increment : end) template < class T, class sequence = std::vector<T> > sequence valueRange(const T start, const T end, const T increment = Epsilon<T>::value) { // sadly, no overloaded version of std::abs is available for // unsigned long long, so we compute the absolute value of increment // ourselfs const T incrementAbs = std::is_unsigned<T>::value ? increment : std::abs(increment); sequence ret(typename sequence::size_type(((end>start) ? end-start : start-end)/incrementAbs), start); typename sequence::size_type i = 0; std::generate(std::begin(ret), std::end(ret), [&](){ return T(start + (increment * i++)); }); return ret; } //! get a vector with values in [0 : Epsilon<T> : end) template < class T, class sequence = std::vector<T> > sequence valueRange(const T end) { return valueRange(T(0),end); } } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_RANGES_RANGES_HH /** Copyright (c) 2012, Felix Albrecht, Rene Milk * 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. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ <commit_msg>[common.ranges] added fem guard<commit_after>#ifndef DUNE_STUFF_RANGES_RANGES_HH #define DUNE_STUFF_RANGES_RANGES_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #else #include "config.h" #endif // ifdef HAVE_CMAKE_CONFIG #if HAVE_DUNE_GRID #include <dune/stuff/common/disable_warnings.hh> #include <dune/grid/common/gridview.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <boost/serialization/static_warning.hpp> #include <boost/iterator/iterator_facade.hpp> #endif #if HAVE_DUNE_FEM #include <dune/fem/version.hh> #include <dune/stuff/fem/namespace.hh> #include <dune/stuff/common/disable_warnings.hh> #include <dune/fem/function/common/discretefunction.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/fem/gridpart/common/gridpart.hh> #if DUNE_FEM_IS_LOCALFUNCTIONS_COMPATIBLE #include <dune/fem/space/lagrangespace/lagrangepoints.hh> #else #include <dune/fem/space/lagrange/lagrangepoints.hh> #endif #endif #include <dune/stuff/common/math.hh> #include <dune/stuff/fem/namespace.hh> namespace Dune { #if HAVE_DUNE_FEM namespace Fem { template < class DiscreteFunctionTraits > auto begin( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dbegin()) { return func.dbegin(); } template < class DiscreteFunctionTraits > auto end( const Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dend()) { return func.dend(); } template < class DiscreteFunctionTraits > auto begin( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dbegin()) { return func.dbegin(); } template < class DiscreteFunctionTraits > auto end( Dune::Fem::DiscreteFunctionInterface< DiscreteFunctionTraits >& func ) -> decltype(func.dend()) { return func.dend(); } } // namespace Fem #endif } //namespace Dune namespace Dune { namespace Stuff { namespace Common { #if HAVE_DUNE_GRID //! adapter enabling view usage in range-based for template < class GridViewType, int codim = 0> class ViewRange { const GridViewType& view_; public: ViewRange(const GridViewType& view) :view_(view) { BOOST_STATIC_WARNING(codim == 0 && "unnecessary ViewRange usage with codim 0"); } typename GridViewType::template Codim< codim >::Iterator begin() const { return view_.template begin< codim >(); } typename GridViewType::template Codim< codim >::Iterator end() const { return view_.template end< codim >(); } }; template < class GridViewTraits, int codim = 0> ViewRange<Dune::GridView<GridViewTraits>, codim> viewRange(const Dune::GridView<GridViewTraits>& view) { return ViewRange<Dune::GridView<GridViewTraits>, codim>(view); } /** adapter enabling intersectionniterator usage in range-based for * works for GridParts and GridViews */ template < class GridAbstractionType, class EntityType > class IntersectionRange { const GridAbstractionType& view_; const EntityType& entity_; public: IntersectionRange(const GridAbstractionType& view, const EntityType& entity) : view_(view) , entity_(entity) {} auto begin() const -> decltype(view_.ibegin(entity_)) { return view_.ibegin(entity_); } auto end() const -> decltype(view_.iend(entity_)) { return view_.iend(entity_); } }; template < class GridViewTraits> IntersectionRange<Dune::GridView<GridViewTraits>, typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity> intersectionRange(const Dune::GridView<GridViewTraits>& gridview, const typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity& entity) { return IntersectionRange<Dune::GridView<GridViewTraits>, typename Dune::GridView<GridViewTraits>::template Codim< 0 >::Entity>(gridview, entity); } //! custom const iterator for \ref FixedMap template <class GeometryType> class ConstCornerIterator : public boost::iterator_facade< ConstCornerIterator<GeometryType> , const typename GeometryType::GlobalCoordinate , boost::forward_traversal_tag > { typedef ConstCornerIterator<GeometryType> ThisType; typedef typename GeometryType::GlobalCoordinate CornerType; public: ConstCornerIterator() :index_(-1) , geometry_(nullptr) {} explicit ConstCornerIterator(const GeometryType*const geometry, int i = 0) : index_(i) , geometry_(geometry) {} private: friend class boost::iterator_core_access; void increment() { index_++; } bool equal(ThisType const& other) const { return this->geometry_ && (index_ == other.index_) && (this->geometry_ == other.geometry_); } const CornerType& dereference() const { return geometry_->corner(index_); } int index_; const GeometryType * const geometry_; }; template <class GeometryType> class CornerRange { typedef ConstCornerIterator<GeometryType> IteratorType; public: CornerRange(const GeometryType& geometry) : geometry_(geometry) {} IteratorType begin() const { return IteratorType(geometry_, 0); } IteratorType end() const { return IteratorType(geometry_, geometry_->corners()); } private: const GeometryType& geometry_; }; template <int mydim, int cdim, class GridImp, template< int, int, class > class GeometryImp> CornerRange<Dune::Geometry< mydim, cdim, GridImp, GeometryImp>> cornerRange(const Dune::Geometry< mydim, cdim, GridImp, GeometryImp>& geometry) { return CornerRange<Dune::Geometry< mydim, cdim, GridImp, GeometryImp>>(geometry); } template <int mydim, int cdim, class GridImp, template< int, int, class > class EntityImp> auto cornerRange(const Dune::Entity< mydim, cdim, GridImp, EntityImp>& entity) -> ConstCornerIterator<decltype(entity.geometry())> { return CornerRange<decltype(entity.geometry())>(entity.geometry()); } #endif //#if HAVE_DUNE_GRID #if HAVE_DUNE_FEM //! Range adapter for lagrange points from lagrange spaces template < class GridPartType, int order, int faceCodim > class LagrangePointSetRange { typedef Dune::Fem::LagrangePointSet<GridPartType, order> LagrangePointSetType; typedef typename LagrangePointSetType::template Codim< faceCodim >::SubEntityIteratorType SubEntityIteratorType; const LagrangePointSetType& lp_set_; const unsigned int subEntity_; public: /** the template isn't lazyness here, the underlying set is templated on it too */ template < class DiscreteFunctionspaceType, class EntityType > LagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const unsigned int subEntity) : lp_set_(space.lagrangePointSet(entity)) , subEntity_(subEntity) {} LagrangePointSetRange(const LagrangePointSetType& lp_set, const unsigned int subEntity) : lp_set_(lp_set) , subEntity_(subEntity) {} SubEntityIteratorType begin() const { return lp_set_.template beginSubEntity< faceCodim >(subEntity_); } SubEntityIteratorType end() const { return lp_set_.template endSubEntity< faceCodim >(subEntity_); } }; template < int codim, class DiscreteFunctionspaceType, class EntityType > LagrangePointSetRange<typename DiscreteFunctionspaceType::GridPartType, DiscreteFunctionspaceType::polynomialOrder, codim> lagrangePointSetRange(const DiscreteFunctionspaceType& space, const EntityType& entity, const int subEntity) { return LagrangePointSetRange<typename DiscreteFunctionspaceType::GridPartType, DiscreteFunctionspaceType::polynomialOrder, codim>(space, entity, subEntity); } template < class LgPointSetType, int codim = 1 > LagrangePointSetRange<typename LgPointSetType::GridPartType, LgPointSetType::polynomialOrder, codim> lagrangePointSetRange(const LgPointSetType& lpset, const int subEntity) { return LagrangePointSetRange<typename LgPointSetType::GridPartType, LgPointSetType::polynomialOrder, codim>(lpset, subEntity); } template < class GridPartTraits > IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>, typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType> intersectionRange(const Dune::Fem::GridPartInterface<GridPartTraits>& gridpart, const typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType& entity) { return IntersectionRange<Dune::Fem::GridPartInterface<GridPartTraits>, typename Dune::Fem::GridPartInterface<GridPartTraits>::template Codim< 0 >::EntityType>(gridpart, entity); } #endif //HAVE_DUNE_FEM //! get a vector with values in [start : increment : end) template < class T, class sequence = std::vector<T> > sequence valueRange(const T start, const T end, const T increment = Epsilon<T>::value) { // sadly, no overloaded version of std::abs is available for // unsigned long long, so we compute the absolute value of increment // ourselfs const T incrementAbs = std::is_unsigned<T>::value ? increment : std::abs(increment); sequence ret(typename sequence::size_type(((end>start) ? end-start : start-end)/incrementAbs), start); typename sequence::size_type i = 0; std::generate(std::begin(ret), std::end(ret), [&](){ return T(start + (increment * i++)); }); return ret; } //! get a vector with values in [0 : Epsilon<T> : end) template < class T, class sequence = std::vector<T> > sequence valueRange(const T end) { return valueRange(T(0),end); } } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_RANGES_RANGES_HH /** Copyright (c) 2012, Felix Albrecht, Rene Milk * 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. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <algorithm> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <BeamFormer.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char * argv[]) { bool local = false; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxRows = 0; unsigned int maxColumns = 0; unsigned int threadUnit = 0; unsigned int threadIncrement = 0; unsigned int maxItems = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); local = args.getSwitch("-local"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); maxColumns = args.getSwitchArgument< unsigned int >("-max_columns"); threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams")); observation.setNrStations(args.getSwitchArgument< unsigned int >("-stations")); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), 0, 0); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... [-local] -opencl_platform ... -opencl_device ... -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_columns ... -max_rows ... -thread_increment ... -beams ... -stations ... -samples ... -channels ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); // Allocate host memory std::vector< dataType > samples = std::vector< dataType >(observation.getNrChannels() * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4); std::vector< float > weights = std::vector< float >(observation.getNrChannels() * observation.getNrStations() * observation.getNrPaddedBeams() * 2); std::srand(time(0)); std::fill(weights.begin(), weights.end(), std::rand() % 100); std::fill(samples.begin(), samples.end(), std::rand() % 1000); // Allocate device memory cl::Buffer samples_d, output_d, weights_d; try { samples_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, samples.size() * sizeof(dataType), 0, 0); output_d = cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4 * sizeof(dataType), 0, 0); weights_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, weights.size() * sizeof(float), 0, 0); } catch ( cl::Error & err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(weights_d, CL_FALSE, 0, weights.size() * sizeof(float), reinterpret_cast< void * >(weights.data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(samples_d, CL_FALSE, 0, samples.size() * sizeof(dataType), reinterpret_cast< void * >(samples.data())); } catch ( cl::Error & err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } // Find the parameters std::vector< unsigned int > samplesPerBlock; for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) { if ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) { samplesPerBlock.push_back(samples); } } std::vector< unsigned int > beamsPerBlock; for ( unsigned int beams = 1; beams <= maxRows; beams++ ) { if ( (observation.getNrBeams() % beams) == 0 ) { beamsPerBlock.push_back(beams); } } std::cout << std::fixed << std::endl; std::cout << "# nrBeams nrStations nrChannels nrSamples samplesPerBlock beamsPerBlock samplesPerThread beamsPerThread GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) { for ( std::vector< unsigned int >::iterator beams = beamsPerBlock.begin(); beams != beamsPerBlock.end(); ++beams ) { if ( ((*samples) * (*beams)) > maxThreads ) { break; } else if ( ((*samples) * (*beams)) % threadUnit != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { if ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) { continue; } for ( unsigned int beamsPerThread = 1; beamsPerThread <= maxItems; beamsPerThread++ ) { if ( (observation.getNrBeams() % ((*beams) * beamsPerThread)) != 0 ) { continue; } else if ( (samplesPerThread + (samplesPerThread * beamsPerThread * 4) + 8) > maxItems ) { break; } // Generate kernel double gflops = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrBeams()) * observation.getNrChannels() * observation.getNrSamplesPerSecond() * observation.getNrStations() * 16) + (static_cast< long long unsigned int >(observation.getNrBeams()) * observation.getNrChannels() * observation.getNrSamplesPerSecond() * 4)); double gbs = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrChannels()) * observation.getNrSamplesPerSecond() * observation.getNrStations() * (observation.getNrBeams() / (beamsPerThread * *beams)) * 4 * sizeof(dataType)) + (static_cast< long long unsigned int >(observation.getNrBeams()) * observation.getNrChannels() * observation.getNrSamplesPerSecond() * 4 * sizeof(dataType)) + (observation.getNrChannels() * observation.getNrStations() * (observation.getNrBeams() / (samplesPerThread * *samples)) * 2 * sizeof(float))); isa::utils::Timer timer; cl::Event event; cl::Kernel * kernel; std::string * code = RadioAstronomy::getBeamFormerOpenCL(local, *samples, *beams, samplesPerThread, beamsPerThread, typeName, observation); try { kernel = isa::OpenCL::compile("beamFormer", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; continue; } cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / samplesPerThread, observation.getNrBeams() / beamsPerThread, observation.getNrChannels()); cl::NDRange local(*samples, *beams, 1); kernel->setArg(0, samples_d); kernel->setArg(1, output_d); kernel->setArg(2, weights_d); // Warm-up run try { clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } // Tuning runs try { for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } std::cout << observation.getNrBeams() << " " << observation.getNrStations() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " " << *samples << " " << *beams << " " << samplesPerThread << " " << beamsPerThread << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } } } std::cout << std::endl; return 0; } <commit_msg>Fixing the output.<commit_after>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <algorithm> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <BeamFormer.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char * argv[]) { bool local = false; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxRows = 0; unsigned int maxColumns = 0; unsigned int threadUnit = 0; unsigned int threadIncrement = 0; unsigned int maxItems = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); local = args.getSwitch("-local"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); maxColumns = args.getSwitchArgument< unsigned int >("-max_columns"); threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams")); observation.setNrStations(args.getSwitchArgument< unsigned int >("-stations")); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), 0, 0); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... [-local] -opencl_platform ... -opencl_device ... -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_columns ... -max_rows ... -thread_increment ... -beams ... -stations ... -samples ... -channels ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); // Allocate host memory std::vector< dataType > samples = std::vector< dataType >(observation.getNrChannels() * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4); std::vector< float > weights = std::vector< float >(observation.getNrChannels() * observation.getNrStations() * observation.getNrPaddedBeams() * 2); std::srand(time(0)); std::fill(weights.begin(), weights.end(), std::rand() % 100); std::fill(samples.begin(), samples.end(), std::rand() % 1000); // Allocate device memory cl::Buffer samples_d, output_d, weights_d; try { samples_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, samples.size() * sizeof(dataType), 0, 0); output_d = cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, observation.getNrBeams() * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4 * sizeof(dataType), 0, 0); weights_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, weights.size() * sizeof(float), 0, 0); } catch ( cl::Error & err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(weights_d, CL_FALSE, 0, weights.size() * sizeof(float), reinterpret_cast< void * >(weights.data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(samples_d, CL_FALSE, 0, samples.size() * sizeof(dataType), reinterpret_cast< void * >(samples.data())); } catch ( cl::Error & err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString(err.err()) << "." << std::endl; return 1; } // Find the parameters std::vector< unsigned int > samplesPerBlock; for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) { if ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) { samplesPerBlock.push_back(samples); } } std::vector< unsigned int > beamsPerBlock; for ( unsigned int beams = 1; beams <= maxRows; beams++ ) { if ( (observation.getNrBeams() % beams) == 0 ) { beamsPerBlock.push_back(beams); } } std::cout << std::fixed << std::endl; std::cout << "# nrBeams nrStations nrChannels nrSamples local samplesPerBlock beamsPerBlock samplesPerThread beamsPerThread GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) { for ( std::vector< unsigned int >::iterator beams = beamsPerBlock.begin(); beams != beamsPerBlock.end(); ++beams ) { if ( ((*samples) * (*beams)) > maxThreads ) { break; } else if ( ((*samples) * (*beams)) % threadUnit != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { if ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) { continue; } for ( unsigned int beamsPerThread = 1; beamsPerThread <= maxItems; beamsPerThread++ ) { if ( (observation.getNrBeams() % ((*beams) * beamsPerThread)) != 0 ) { continue; } else if ( (samplesPerThread + (samplesPerThread * beamsPerThread * 4) + 8) > maxItems ) { break; } // Generate kernel double gflops = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrBeams()) * observation.getNrChannels() * observation.getNrSamplesPerSecond() * observation.getNrStations() * 16) + (static_cast< long long unsigned int >(observation.getNrBeams()) * observation.getNrChannels() * observation.getNrSamplesPerSecond() * 4)); double gbs = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrChannels()) * observation.getNrSamplesPerSecond() * observation.getNrStations() * (observation.getNrBeams() / (beamsPerThread * *beams)) * 4 * sizeof(dataType)) + (static_cast< long long unsigned int >(observation.getNrBeams()) * observation.getNrChannels() * observation.getNrSamplesPerSecond() * 4 * sizeof(dataType)) + (observation.getNrChannels() * observation.getNrStations() * (observation.getNrBeams() / (samplesPerThread * *samples)) * 2 * sizeof(float))); isa::utils::Timer timer; cl::Event event; cl::Kernel * kernel; std::string * code = RadioAstronomy::getBeamFormerOpenCL(local, *samples, *beams, samplesPerThread, beamsPerThread, typeName, observation); try { kernel = isa::OpenCL::compile("beamFormer", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; continue; } cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / samplesPerThread, observation.getNrBeams() / beamsPerThread, observation.getNrChannels()); cl::NDRange local(*samples, *beams, 1); kernel->setArg(0, samples_d); kernel->setArg(1, output_d); kernel->setArg(2, weights_d); // Warm-up run try { clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } // Tuning runs try { for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl; continue; } std::cout << observation.getNrBeams() << " " << observation.getNrStations() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " "; std::cout << local << " " << *samples << " " << *beams << " " << samplesPerThread << " " << beamsPerThread << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } } } std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_TRAVERSAL_HPP #define DTK_DETAILS_TREE_TRAVERSAL_HPP #include <DTK_DBC.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_DetailsNode.hpp> #include <DTK_DetailsPriorityQueue.hpp> #include <DTK_DetailsStack.hpp> #include <DTK_Predicates.hpp> namespace DataTransferKit { template <typename DeviceType> class BoundingVolumeHierarchy; namespace Details { template <typename DeviceType> struct TreeTraversal { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION static int query( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &pred, Insert const &insert ) { using Tag = typename Predicate::Tag; return queryDispatch( bvh, pred, insert, Tag{} ); } /** * Return true if the node is a leaf. */ KOKKOS_INLINE_FUNCTION static bool isLeaf( Node const *node ) { return ( node->children.first == nullptr ); } /** * Return the index of the leaf node. */ KOKKOS_INLINE_FUNCTION static int getIndex( BoundingVolumeHierarchy<DeviceType> const &bvh, Node const *leaf ) { return reinterpret_cast<size_t>( leaf->children.second ); } /** * Return the root node of the BVH. */ KOKKOS_INLINE_FUNCTION static Node const *getRoot( BoundingVolumeHierarchy<DeviceType> const &bvh ) { if ( bvh.empty() ) return nullptr; return ( bvh.size() > 1 ? bvh._internal_nodes : bvh._leaf_nodes ) .data(); } }; // There are two (related) families of search: one using a spatial predicate and // one using nearest neighbours query (see boost::geometry::queries // documentation). template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_FUNCTION int spatialQuery( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &predicate, Insert const &insert ) { if ( bvh.empty() ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); if ( predicate( leaf ) ) { int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); insert( leaf_index ); return 1; } else return 0; } Stack<Node const *> stack; Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); stack.push( root ); int count = 0; while ( !stack.empty() ) { Node const *node = stack.top(); stack.pop(); if ( TreeTraversal<DeviceType>::isLeaf( node ) ) { insert( TreeTraversal<DeviceType>::getIndex( bvh, node ) ); count++; } else { for ( Node const *child : {node->children.first, node->children.second} ) { if ( predicate( child ) ) { stack.push( child ); } } } } return count; } // query k nearest neighbours template <typename DeviceType, typename Distance, typename Insert> KOKKOS_FUNCTION int nearestQuery( BoundingVolumeHierarchy<DeviceType> const &bvh, Distance const &distance, int k, Insert const &insert ) { if ( bvh.empty() || k < 1 ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); double const leaf_distance = distance( leaf ); insert( leaf_index, leaf_distance ); return 1; } using PairNodePtrDistance = Kokkos::pair<Node const *, double>; struct CompareDistance { KOKKOS_INLINE_FUNCTION bool operator()( PairNodePtrDistance const &lhs, PairNodePtrDistance const &rhs ) const { // reverse order (larger distance means lower priority) return lhs.second > rhs.second; } }; PriorityQueue<PairNodePtrDistance, CompareDistance> queue; // priority does not matter for the root since the node will be // processed directly and removed from the priority queue we don't even // bother computing the distance to it. Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); queue.push( root, 0. ); int count = 0; while ( !queue.empty() && count < k ) { // get the node that is on top of the priority list (i.e. is the // closest to the query point) Node const *node = queue.top().first; double const node_distance = queue.top().second; // NOTE: it would be nice to be able to do something like // tie( node, node_distance = queue.top(); // NOTE: not calling queue.pop() here so that it can be combined with // the next push in case the node is internal (thus sparing a bubble-up // operation) if ( TreeTraversal<DeviceType>::isLeaf( node ) ) { queue.pop(); insert( TreeTraversal<DeviceType>::getIndex( bvh, node ), node_distance ); count++; } else { // insert children of the node in the priority list auto const left_child = node->children.first; auto const right_child = node->children.second; queue.pop_push( left_child, distance( left_child ) ); queue.push( right_child, distance( right_child ) ); } } return count; } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &pred, Insert const &insert, SpatialPredicateTag ) { return spatialQuery( bvh, pred, insert ); } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &pred, Insert const &insert, NearestPredicateTag ) { auto const geometry = pred._geometry; auto const k = pred._k; return nearestQuery( bvh, [geometry]( Node const *node ) { return distance( geometry, node->bounding_box ); }, k, insert ); } } // namespace Details } // namespace DataTransferKit #endif <commit_msg>Removed bvh argument in TreeTraversal::getIndex()<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_TRAVERSAL_HPP #define DTK_DETAILS_TREE_TRAVERSAL_HPP #include <DTK_DBC.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_DetailsNode.hpp> #include <DTK_DetailsPriorityQueue.hpp> #include <DTK_DetailsStack.hpp> #include <DTK_Predicates.hpp> namespace DataTransferKit { template <typename DeviceType> class BoundingVolumeHierarchy; namespace Details { template <typename DeviceType> struct TreeTraversal { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION static int query( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &pred, Insert const &insert ) { using Tag = typename Predicate::Tag; return queryDispatch( bvh, pred, insert, Tag{} ); } /** * Return true if the node is a leaf. */ KOKKOS_INLINE_FUNCTION static bool isLeaf( Node const *node ) { return ( node->children.first == nullptr ); } /** * Return the index of the leaf node. */ KOKKOS_INLINE_FUNCTION static size_t getIndex( Node const *leaf ) { return reinterpret_cast<size_t>( leaf->children.second ); } /** * Return the root node of the BVH. */ KOKKOS_INLINE_FUNCTION static Node const *getRoot( BoundingVolumeHierarchy<DeviceType> const &bvh ) { if ( bvh.empty() ) return nullptr; return ( bvh.size() > 1 ? bvh._internal_nodes : bvh._leaf_nodes ) .data(); } }; // There are two (related) families of search: one using a spatial predicate and // one using nearest neighbours query (see boost::geometry::queries // documentation). template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_FUNCTION int spatialQuery( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &predicate, Insert const &insert ) { if ( bvh.empty() ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); if ( predicate( leaf ) ) { int const leaf_index = TreeTraversal<DeviceType>::getIndex( leaf ); insert( leaf_index ); return 1; } else return 0; } Stack<Node const *> stack; Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); stack.push( root ); int count = 0; while ( !stack.empty() ) { Node const *node = stack.top(); stack.pop(); if ( TreeTraversal<DeviceType>::isLeaf( node ) ) { insert( TreeTraversal<DeviceType>::getIndex( node ) ); count++; } else { for ( Node const *child : {node->children.first, node->children.second} ) { if ( predicate( child ) ) { stack.push( child ); } } } } return count; } // query k nearest neighbours template <typename DeviceType, typename Distance, typename Insert> KOKKOS_FUNCTION int nearestQuery( BoundingVolumeHierarchy<DeviceType> const &bvh, Distance const &distance, int k, Insert const &insert ) { if ( bvh.empty() || k < 1 ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); int const leaf_index = TreeTraversal<DeviceType>::getIndex( leaf ); double const leaf_distance = distance( leaf ); insert( leaf_index, leaf_distance ); return 1; } using PairNodePtrDistance = Kokkos::pair<Node const *, double>; struct CompareDistance { KOKKOS_INLINE_FUNCTION bool operator()( PairNodePtrDistance const &lhs, PairNodePtrDistance const &rhs ) const { // reverse order (larger distance means lower priority) return lhs.second > rhs.second; } }; PriorityQueue<PairNodePtrDistance, CompareDistance> queue; // priority does not matter for the root since the node will be // processed directly and removed from the priority queue we don't even // bother computing the distance to it. Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); queue.push( root, 0. ); int count = 0; while ( !queue.empty() && count < k ) { // get the node that is on top of the priority list (i.e. is the // closest to the query point) Node const *node = queue.top().first; double const node_distance = queue.top().second; // NOTE: it would be nice to be able to do something like // tie( node, node_distance = queue.top(); // NOTE: not calling queue.pop() here so that it can be combined with // the next push in case the node is internal (thus sparing a bubble-up // operation) if ( TreeTraversal<DeviceType>::isLeaf( node ) ) { queue.pop(); insert( TreeTraversal<DeviceType>::getIndex( node ), node_distance ); count++; } else { // insert children of the node in the priority list auto const left_child = node->children.first; auto const right_child = node->children.second; queue.pop_push( left_child, distance( left_child ) ); queue.push( right_child, distance( right_child ) ); } } return count; } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &pred, Insert const &insert, SpatialPredicateTag ) { return spatialQuery( bvh, pred, insert ); } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BoundingVolumeHierarchy<DeviceType> const &bvh, Predicate const &pred, Insert const &insert, NearestPredicateTag ) { auto const geometry = pred._geometry; auto const k = pred._k; return nearestQuery( bvh, [geometry]( Node const *node ) { return distance( geometry, node->bounding_box ); }, k, insert ); } } // namespace Details } // namespace DataTransferKit #endif <|endoftext|>
<commit_before>#include "test_common.hh" #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> #include <dune/stuff/function.hh> using namespace Dune::Stuff; typedef testing::Types< FunctionExpression< double, 1, double, 1 >, FunctionCheckerboard< double, 1, double, 1 > > NonparametricFunctions; typedef testing::Types< FunctionAffineParametricCheckerboard< double, 1, double, 1 >, FunctionAffineParametricDefault< double, 1, double, 1 > > SeparableFunctions; template< class T > struct NonparametricTest : public ::testing::Test { typedef T FunctionType; typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRange = FunctionType::dimRange; typedef typename FunctionType::RangeType RangeType; typedef FunctionInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange > InterfaceType; void check() const { const std::unique_ptr< InterfaceType > function( Functions< DomainFieldType, dimDomain, RangeFieldType, dimRange >::create(FunctionType::id(), FunctionType::createSampleDescription())); DomainType x(1); RangeType ret; if (function->parametric()) DUNE_THROW(Dune::InvalidStateException, "ERROR: nonparametric function returned parametric() == true"); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); function->evaluate(x, ret); } }; template< class T > struct SeparableTest : public ::testing::Test { typedef T FunctionType; typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRange = FunctionType::dimRange; typedef typename FunctionType::RangeType RangeType; typedef FunctionInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange > InterfaceType; typedef FunctionAffineParametricDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange > DefaultType; typedef Common::Parameter::FieldType ParamFieldType; static const int maxParamDim = Common::Parameter::maxDim; typedef Common::Parameter::Type ParamType; void check() const { const std::unique_ptr< InterfaceType > function( FunctionType::create(FunctionType::createSampleDescription())); if (!function->parametric()) DUNE_THROW(Dune::InvalidStateException, "ERROR: separable function returned parametric() == false!"); if (!function->affineparametric()) DUNE_THROW(Dune::InvalidStateException, "ERROR: separable function returned affineparametric() == false!"); const std::string name = function->name(); const int order = function->order(); const size_t paramSize = function->paramSize(); ParamType mu(paramSize); const std::vector< ParamType > paramRange = function->paramRange(); if (paramRange.size() != 2) DUNE_THROW(Dune::InvalidStateException, "ERROR: paramRange() has wrong size!"); if (paramRange[0].size() != paramSize) DUNE_THROW(Dune::InvalidStateException, "ERROR: paramRange()[0] has wrong size!"); if (paramRange[1].size() != paramSize) DUNE_THROW(Dune::InvalidStateException, "ERROR: paramRange()[1] has wrong size!"); for (size_t pp = 0; pp < paramSize; ++pp) mu[pp] = paramRange[0][pp] + 0.5*(paramRange[1][pp] - paramRange[0][pp]); DomainType x(1); RangeType ret; function->evaluate(x, mu, ret); const std::vector< std::string >& paramExplanation = function->paramExplanation(); if (paramExplanation.size() != paramSize) DUNE_THROW(Dune::InvalidStateException, "ERROR: paramExplanation() has wrong size!"); DefaultType DUNE_UNUSED(separableDefault)(paramSize, paramRange, function->components(), function->coefficients(), paramExplanation, order, name); } }; TYPED_TEST_CASE(NonparametricTest, NonparametricFunctions); TYPED_TEST(NonparametricTest, Nonparametric) { this->check(); } TYPED_TEST_CASE(SeparableTest, SeparableFunctions); TYPED_TEST(SeparableTest, Separable) { this->check(); } int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <commit_msg>[test.function] update, refs #220<commit_after>#include "test_common.hh" #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> #include <dune/stuff/function/interface.hh> #include <dune/stuff/function/expression.hh> #include <dune/stuff/function/checkerboard.hh> #include <dune/stuff/function/spe10.hh> using namespace Dune::Stuff; typedef testing::Types< FunctionExpression< double, 1, double, 1 > , FunctionCheckerboard< double, 1, double, 1 > , FunctionCheckerboard< double, 2, double, 1 > , FunctionCheckerboard< double, 3, double, 1 > // , FunctionSpe10Model1< double, 2, double, 1 > // <- this makes only sense, if the data file is present > Functions; template< class FunctionType > struct FunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; void check() const { DomainType x(1); RangeType ret(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); function->evaluate(x, ret); } }; TYPED_TEST_CASE(FunctionTest, Functions); TYPED_TEST(FunctionTest, Function) { this->check(); } int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>//===- Miscompilation.cpp - Debug program miscompilations -----------------===// // // This file implements program miscompilation debugging support. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "SystemUtils.h" #include "ListReducer.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/Linker.h" #include "Support/CommandLine.h" // Anonymous namespace to define command line options for miscompilation // debugging. // namespace { // Output - The user can specify a file containing the expected output of the // program. If this filename is set, it is used as the reference diff source, // otherwise the raw input run through an interpreter is used as the reference // source. // cl::opt<std::string> Output("output", cl::desc("Specify a reference program output " "(for miscompilation detection)")); } class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> { BugDriver &BD; public: ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {} virtual TestResult doTest(const std::vector<const PassInfo*> &Prefix, const std::vector<const PassInfo*> &Kept); }; ReduceMiscompilingPasses::TestResult ReduceMiscompilingPasses::doTest(const std::vector<const PassInfo*> &Prefix, const std::vector<const PassInfo*> &Kept) { // First, run the program with just the Kept passes. If it is still broken // with JUST the kept passes, discard the prefix passes. std::cout << "Checking to see if '" << getPassesString(Kept) << "' compile correctly: "; std::string BytecodeResult; if (BD.runPasses(Kept, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } // Check to see if the finished program matches the reference output... if (BD.diffProgram(Output, BytecodeResult, true /*delete bytecode*/)) { std::cout << "nope.\n"; return KeepSuffix; // Miscompilation detected! } std::cout << "yup.\n"; // No miscompilation! if (Prefix.empty()) return NoFailure; // First, run the program with just the Kept passes. If it is still broken // with JUST the kept passes, discard the prefix passes. std::cout << "Checking to see if '" << getPassesString(Prefix) << "' compile correctly: "; // If it is not broken with the kept passes, it's possible that the prefix // passes must be run before the kept passes to break it. If the program // WORKS after the prefix passes, but then fails if running the prefix AND // kept passes, we can update our bytecode file to include the result of the // prefix passes, then discard the prefix passes. // if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } // If the prefix maintains the predicate by itself, only keep the prefix! if (BD.diffProgram(Output, BytecodeResult)) { std::cout << "nope.\n"; removeFile(BytecodeResult); return KeepPrefix; } std::cout << "yup.\n"; // No miscompilation! // Ok, so now we know that the prefix passes work, try running the suffix // passes on the result of the prefix passes. // Module *PrefixOutput = BD.ParseInputFile(BytecodeResult); if (PrefixOutput == 0) { std::cerr << BD.getToolName() << ": Error reading bytecode file '" << BytecodeResult << "'!\n"; exit(1); } removeFile(BytecodeResult); // No longer need the file on disk std::cout << "Checking to see if '" << getPassesString(Kept) << "' passes compile correctly after the '" << getPassesString(Prefix) << "' passes: "; Module *OriginalInput = BD.Program; BD.Program = PrefixOutput; if (BD.runPasses(Kept, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } // Run the result... if (BD.diffProgram(Output, BytecodeResult, true/*delete bytecode*/)) { std::cout << "nope.\n"; delete OriginalInput; // We pruned down the original input... return KeepPrefix; } // Otherwise, we must not be running the bad pass anymore. std::cout << "yup.\n"; // No miscompilation! BD.Program = OriginalInput; // Restore original program delete PrefixOutput; // Free experiment return NoFailure; } static void PrintFunctionList(const std::vector<Function*> &Funcs) { for (unsigned i = 0, e = Funcs.size(); i != e; ++i) { if (i) std::cout << ", "; std::cout << Funcs[i]->getName(); } } class ReduceMiscompilingFunctions : public ListReducer<Function*> { BugDriver &BD; public: ReduceMiscompilingFunctions(BugDriver &bd) : BD(bd) {} virtual TestResult doTest(const std::vector<Function*> &Prefix, const std::vector<Function*> &Kept) { if (TestFuncs(Kept, false)) return KeepSuffix; if (!Prefix.empty() && TestFuncs(Prefix, false)) return KeepPrefix; return NoFailure; } bool TestFuncs(const std::vector<Function*> &Prefix, bool EmitBytecode); }; // DeleteFunctionBody - "Remove" the function by deleting all of it's basic // blocks, making it external. // static void DeleteFunctionBody(Function *F) { // First, break circular use/def chain references... for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) I->dropAllReferences(); // Next, delete all of the basic blocks. F->getBasicBlockList().clear(); assert(F->isExternal() && "This didn't make the function external!"); } bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs, bool EmitBytecode) { // Test to see if the function is misoptimized if we ONLY run it on the // functions listed in Funcs. if (!EmitBytecode) { std::cout << "Checking to see if the program is misoptimized when these " << "functions are run\nthrough the passes: "; PrintFunctionList(Funcs); std::cout << "\n"; } else { std::cout <<"Outputting reduced bytecode files which expose the problem:\n"; } // First step: clone the module for the two halves of the program we want. Module *ToOptimize = CloneModule(BD.Program); // Second step: Make sure functions & globals are all external so that linkage // between the two modules will work. for (Module::iterator I = ToOptimize->begin(), E = ToOptimize->end();I!=E;++I) I->setLinkage(GlobalValue::ExternalLinkage); for (Module::giterator I = ToOptimize->gbegin(), E = ToOptimize->gend(); I != E; ++I) I->setLinkage(GlobalValue::ExternalLinkage); // Third step: make a clone of the externalized program for the non-optimized // part. Module *ToNotOptimize = CloneModule(ToOptimize); // Fourth step: Remove the test functions from the ToNotOptimize module, and // all of the global variables. for (unsigned i = 0, e = Funcs.size(); i != e; ++i) { Function *TNOF = ToNotOptimize->getFunction(Funcs[i]->getName(), Funcs[i]->getFunctionType()); assert(TNOF && "Function doesn't exist in module!"); DeleteFunctionBody(TNOF); // Function is now external in this module! } for (Module::giterator I = ToNotOptimize->gbegin(), E = ToNotOptimize->gend(); I != E; ++I) I->setInitializer(0); // Delete the initializer to make it external if (EmitBytecode) { std::cout << " Non-optimized portion: "; std::swap(BD.Program, ToNotOptimize); BD.EmitProgressBytecode("tonotoptimize", true); std::swap(BD.Program, ToNotOptimize); } // Fifth step: Remove all functions from the ToOptimize module EXCEPT for the // ones specified in Funcs. We know which ones these are because they are // non-external in ToOptimize, but external in ToNotOptimize. // for (Module::iterator I = ToOptimize->begin(), E = ToOptimize->end();I!=E;++I) if (!I->isExternal()) { Function *TNOF = ToNotOptimize->getFunction(I->getName(), I->getFunctionType()); assert(TNOF && "Function doesn't exist in ToNotOptimize module??"); if (!TNOF->isExternal()) DeleteFunctionBody(I); } if (EmitBytecode) { std::cout << " Portion that is input to optimizer: "; std::swap(BD.Program, ToOptimize); BD.EmitProgressBytecode("tooptimize"); std::swap(BD.Program, ToOptimize); } // Sixth step: Run the optimization passes on ToOptimize, producing a // transformed version of the functions being tested. Module *OldProgram = BD.Program; BD.Program = ToOptimize; if (!EmitBytecode) std::cout << " Optimizing functions being tested: "; std::string BytecodeResult; if (BD.runPasses(BD.PassesToRun, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } if (!EmitBytecode) std::cout << "done.\n"; delete BD.Program; // Delete the old "ToOptimize" module BD.Program = BD.ParseInputFile(BytecodeResult); if (EmitBytecode) { std::cout << " 'tooptimize' after being optimized: "; BD.EmitProgressBytecode("optimized", true); } if (BD.Program == 0) { std::cerr << BD.getToolName() << ": Error reading bytecode file '" << BytecodeResult << "'!\n"; exit(1); } removeFile(BytecodeResult); // No longer need the file on disk // Seventh step: Link the optimized part of the program back to the // unoptimized part of the program. // if (LinkModules(BD.Program, ToNotOptimize, &BytecodeResult)) { std::cerr << BD.getToolName() << ": Error linking modules together:" << BytecodeResult << "\n"; exit(1); } delete ToNotOptimize; // We are done with this module... if (EmitBytecode) { std::cout << " Program as tested: "; BD.EmitProgressBytecode("linked", true); delete BD.Program; BD.Program = OldProgram; return false; // We don't need to actually execute the program here. } std::cout << " Checking to see if the merged program executes correctly: "; // Eighth step: Execute the program. If it does not match the expected // output, then 'Funcs' are being misoptimized! bool Broken = BD.diffProgram(Output); delete BD.Program; // Delete the hacked up program BD.Program = OldProgram; // Restore the original std::cout << (Broken ? "nope.\n" : "yup.\n"); return Broken; } /// debugMiscompilation - This method is used when the passes selected are not /// crashing, but the generated output is semantically different from the /// input. /// bool BugDriver::debugMiscompilation() { std::cout << "*** Debugging miscompilation!\n"; // Set up the execution environment, selecting a method to run LLVM bytecode. if (initializeExecutionEnvironment()) return true; // Run the raw input to see where we are coming from. If a reference output // was specified, make sure that the raw output matches it. If not, it's a // problem in the front-end or whatever produced the input code. // bool CreatedOutput = false; if (Output.empty()) { std::cout << "Generating reference output from raw program..."; Output = executeProgram("bugpoint.reference.out"); CreatedOutput = true; std::cout << " done! Reference output is: bugpoint.reference.out.\n"; } else if (diffProgram(Output)) { std::cout << "\n*** Input program does not match reference diff!\n" << " Must be problem with input source!\n"; return false; // Problem found } // Figure out which transformations miscompile the input program. unsigned OldSize = PassesToRun.size(); ReduceMiscompilingPasses(*this).reduceList(PassesToRun); // Make sure something was miscompiled... if (PassesToRun.size() == OldSize) { std::cerr << "*** Optimized program matches reference output! No problem " << "detected...\nbugpoint can't help you with your problem!\n"; return false; } std::cout << "\n*** Found miscompiling pass" << (PassesToRun.size() == 1 ? "" : "es") << ": " << getPassesString(PassesToRun) << "\n"; EmitProgressBytecode("passinput"); // Okay, now that we have reduced the list of passes which are causing the // failure, see if we can pin down which functions are being // miscompiled... first build a list of all of the non-external functions in // the program. std::vector<Function*> MiscompiledFunctions; for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I) if (!I->isExternal()) MiscompiledFunctions.push_back(I); // Do the reduction... ReduceMiscompilingFunctions(*this).reduceList(MiscompiledFunctions); std::cout << "\n*** The following functions are being miscompiled: "; PrintFunctionList(MiscompiledFunctions); std::cout << "\n"; // Output a bunch of bytecode files for the user... ReduceMiscompilingFunctions(*this).TestFuncs(MiscompiledFunctions, true); if (CreatedOutput) removeFile(Output); return false; } <commit_msg>Adjust to match new ListReducer interface Move function to generic code<commit_after>//===- Miscompilation.cpp - Debug program miscompilations -----------------===// // // This file implements program miscompilation debugging support. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "SystemUtils.h" #include "ListReducer.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/Linker.h" #include "Support/CommandLine.h" // Anonymous namespace to define command line options for miscompilation // debugging. // namespace { // Output - The user can specify a file containing the expected output of the // program. If this filename is set, it is used as the reference diff source, // otherwise the raw input run through an interpreter is used as the reference // source. // cl::opt<std::string> Output("output", cl::desc("Specify a reference program output " "(for miscompilation detection)")); } class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> { BugDriver &BD; public: ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {} virtual TestResult doTest(std::vector<const PassInfo*> &Prefix, std::vector<const PassInfo*> &Kept); }; ReduceMiscompilingPasses::TestResult ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix, std::vector<const PassInfo*> &Kept) { // First, run the program with just the Kept passes. If it is still broken // with JUST the kept passes, discard the prefix passes. std::cout << "Checking to see if '" << getPassesString(Kept) << "' compile correctly: "; std::string BytecodeResult; if (BD.runPasses(Kept, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } // Check to see if the finished program matches the reference output... if (BD.diffProgram(Output, BytecodeResult, true /*delete bytecode*/)) { std::cout << "nope.\n"; return KeepSuffix; // Miscompilation detected! } std::cout << "yup.\n"; // No miscompilation! if (Prefix.empty()) return NoFailure; // First, run the program with just the Kept passes. If it is still broken // with JUST the kept passes, discard the prefix passes. std::cout << "Checking to see if '" << getPassesString(Prefix) << "' compile correctly: "; // If it is not broken with the kept passes, it's possible that the prefix // passes must be run before the kept passes to break it. If the program // WORKS after the prefix passes, but then fails if running the prefix AND // kept passes, we can update our bytecode file to include the result of the // prefix passes, then discard the prefix passes. // if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } // If the prefix maintains the predicate by itself, only keep the prefix! if (BD.diffProgram(Output, BytecodeResult)) { std::cout << "nope.\n"; removeFile(BytecodeResult); return KeepPrefix; } std::cout << "yup.\n"; // No miscompilation! // Ok, so now we know that the prefix passes work, try running the suffix // passes on the result of the prefix passes. // Module *PrefixOutput = BD.ParseInputFile(BytecodeResult); if (PrefixOutput == 0) { std::cerr << BD.getToolName() << ": Error reading bytecode file '" << BytecodeResult << "'!\n"; exit(1); } removeFile(BytecodeResult); // No longer need the file on disk std::cout << "Checking to see if '" << getPassesString(Kept) << "' passes compile correctly after the '" << getPassesString(Prefix) << "' passes: "; Module *OriginalInput = BD.Program; BD.Program = PrefixOutput; if (BD.runPasses(Kept, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } // Run the result... if (BD.diffProgram(Output, BytecodeResult, true/*delete bytecode*/)) { std::cout << "nope.\n"; delete OriginalInput; // We pruned down the original input... return KeepPrefix; } // Otherwise, we must not be running the bad pass anymore. std::cout << "yup.\n"; // No miscompilation! BD.Program = OriginalInput; // Restore original program delete PrefixOutput; // Free experiment return NoFailure; } static void PrintFunctionList(const std::vector<Function*> &Funcs) { for (unsigned i = 0, e = Funcs.size(); i != e; ++i) { if (i) std::cout << ", "; std::cout << Funcs[i]->getName(); } } class ReduceMiscompilingFunctions : public ListReducer<Function*> { BugDriver &BD; public: ReduceMiscompilingFunctions(BugDriver &bd) : BD(bd) {} virtual TestResult doTest(std::vector<Function*> &Prefix, std::vector<Function*> &Kept) { if (TestFuncs(Kept, false)) return KeepSuffix; if (!Prefix.empty() && TestFuncs(Prefix, false)) return KeepPrefix; return NoFailure; } bool TestFuncs(const std::vector<Function*> &Prefix, bool EmitBytecode); }; bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs, bool EmitBytecode) { // Test to see if the function is misoptimized if we ONLY run it on the // functions listed in Funcs. if (!EmitBytecode) { std::cout << "Checking to see if the program is misoptimized when these " << "functions are run\nthrough the passes: "; PrintFunctionList(Funcs); std::cout << "\n"; } else { std::cout <<"Outputting reduced bytecode files which expose the problem:\n"; } // First step: clone the module for the two halves of the program we want. Module *ToOptimize = CloneModule(BD.Program); // Second step: Make sure functions & globals are all external so that linkage // between the two modules will work. for (Module::iterator I = ToOptimize->begin(), E = ToOptimize->end();I!=E;++I) I->setLinkage(GlobalValue::ExternalLinkage); for (Module::giterator I = ToOptimize->gbegin(), E = ToOptimize->gend(); I != E; ++I) I->setLinkage(GlobalValue::ExternalLinkage); // Third step: make a clone of the externalized program for the non-optimized // part. Module *ToNotOptimize = CloneModule(ToOptimize); // Fourth step: Remove the test functions from the ToNotOptimize module, and // all of the global variables. for (unsigned i = 0, e = Funcs.size(); i != e; ++i) { Function *TNOF = ToNotOptimize->getFunction(Funcs[i]->getName(), Funcs[i]->getFunctionType()); assert(TNOF && "Function doesn't exist in module!"); DeleteFunctionBody(TNOF); // Function is now external in this module! } for (Module::giterator I = ToNotOptimize->gbegin(), E = ToNotOptimize->gend(); I != E; ++I) I->setInitializer(0); // Delete the initializer to make it external if (EmitBytecode) { std::cout << " Non-optimized portion: "; std::swap(BD.Program, ToNotOptimize); BD.EmitProgressBytecode("tonotoptimize", true); std::swap(BD.Program, ToNotOptimize); } // Fifth step: Remove all functions from the ToOptimize module EXCEPT for the // ones specified in Funcs. We know which ones these are because they are // non-external in ToOptimize, but external in ToNotOptimize. // for (Module::iterator I = ToOptimize->begin(), E = ToOptimize->end();I!=E;++I) if (!I->isExternal()) { Function *TNOF = ToNotOptimize->getFunction(I->getName(), I->getFunctionType()); assert(TNOF && "Function doesn't exist in ToNotOptimize module??"); if (!TNOF->isExternal()) DeleteFunctionBody(I); } if (EmitBytecode) { std::cout << " Portion that is input to optimizer: "; std::swap(BD.Program, ToOptimize); BD.EmitProgressBytecode("tooptimize"); std::swap(BD.Program, ToOptimize); } // Sixth step: Run the optimization passes on ToOptimize, producing a // transformed version of the functions being tested. Module *OldProgram = BD.Program; BD.Program = ToOptimize; if (!EmitBytecode) std::cout << " Optimizing functions being tested: "; std::string BytecodeResult; if (BD.runPasses(BD.PassesToRun, BytecodeResult, false/*delete*/, true/*quiet*/)) { std::cerr << BD.getToolName() << ": Error running this sequence of passes" << " on the input program!\n"; exit(1); } if (!EmitBytecode) std::cout << "done.\n"; delete BD.Program; // Delete the old "ToOptimize" module BD.Program = BD.ParseInputFile(BytecodeResult); if (EmitBytecode) { std::cout << " 'tooptimize' after being optimized: "; BD.EmitProgressBytecode("optimized", true); } if (BD.Program == 0) { std::cerr << BD.getToolName() << ": Error reading bytecode file '" << BytecodeResult << "'!\n"; exit(1); } removeFile(BytecodeResult); // No longer need the file on disk // Seventh step: Link the optimized part of the program back to the // unoptimized part of the program. // if (LinkModules(BD.Program, ToNotOptimize, &BytecodeResult)) { std::cerr << BD.getToolName() << ": Error linking modules together:" << BytecodeResult << "\n"; exit(1); } delete ToNotOptimize; // We are done with this module... if (EmitBytecode) { std::cout << " Program as tested: "; BD.EmitProgressBytecode("linked", true); delete BD.Program; BD.Program = OldProgram; return false; // We don't need to actually execute the program here. } std::cout << " Checking to see if the merged program executes correctly: "; // Eighth step: Execute the program. If it does not match the expected // output, then 'Funcs' are being misoptimized! bool Broken = BD.diffProgram(Output); delete BD.Program; // Delete the hacked up program BD.Program = OldProgram; // Restore the original std::cout << (Broken ? "nope.\n" : "yup.\n"); return Broken; } /// debugMiscompilation - This method is used when the passes selected are not /// crashing, but the generated output is semantically different from the /// input. /// bool BugDriver::debugMiscompilation() { std::cout << "*** Debugging miscompilation!\n"; // Set up the execution environment, selecting a method to run LLVM bytecode. if (initializeExecutionEnvironment()) return true; // Run the raw input to see where we are coming from. If a reference output // was specified, make sure that the raw output matches it. If not, it's a // problem in the front-end or whatever produced the input code. // bool CreatedOutput = false; if (Output.empty()) { std::cout << "Generating reference output from raw program..."; Output = executeProgram("bugpoint.reference.out"); CreatedOutput = true; std::cout << " done! Reference output is: bugpoint.reference.out.\n"; } else if (diffProgram(Output)) { std::cout << "\n*** Input program does not match reference diff!\n" << " Must be problem with input source!\n"; return false; // Problem found } // Figure out which transformations miscompile the input program. unsigned OldSize = PassesToRun.size(); ReduceMiscompilingPasses(*this).reduceList(PassesToRun); // Make sure something was miscompiled... if (PassesToRun.size() == OldSize) { std::cerr << "*** Optimized program matches reference output! No problem " << "detected...\nbugpoint can't help you with your problem!\n"; return false; } std::cout << "\n*** Found miscompiling pass" << (PassesToRun.size() == 1 ? "" : "es") << ": " << getPassesString(PassesToRun) << "\n"; EmitProgressBytecode("passinput"); // Okay, now that we have reduced the list of passes which are causing the // failure, see if we can pin down which functions are being // miscompiled... first build a list of all of the non-external functions in // the program. std::vector<Function*> MiscompiledFunctions; for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I) if (!I->isExternal()) MiscompiledFunctions.push_back(I); // Do the reduction... ReduceMiscompilingFunctions(*this).reduceList(MiscompiledFunctions); std::cout << "\n*** The following functions are being miscompiled: "; PrintFunctionList(MiscompiledFunctions); std::cout << "\n"; // Output a bunch of bytecode files for the user... ReduceMiscompilingFunctions(*this).TestFuncs(MiscompiledFunctions, true); if (CreatedOutput) removeFile(Output); return false; } <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "GPUBlurFilter.h" #include "Bitmap.h" #include "../base/ObjectCounter.h" #include "../base/MathHelper.h" #include <iostream> using namespace std; namespace avg { OGLShaderPtr GPUBlurFilter::s_pHorizShader; OGLShaderPtr GPUBlurFilter::s_pVertShader; GPUBlurFilter::GPUBlurFilter(const IntPoint& size, PixelFormat pfSrc, double stdDev) : GPUFilter(size, pfSrc), m_StdDev(stdDev) { ObjectCounter::get()->incRef(&typeid(*this)); init(); } GPUBlurFilter::GPUBlurFilter(PBOImagePtr pSrcPBO, FBOImagePtr pDestFBO, double stdDev) : GPUFilter(pSrcPBO, pDestFBO), m_StdDev(stdDev) { ObjectCounter::get()->incRef(&typeid(*this)); init(); } void GPUBlurFilter::init() { IntPoint size = getSrcPBO()->getSize(); m_pGaussCurvePBO = PBOImagePtr(new PBOImage(IntPoint(255, 1), I8, GL_FLOAT, false, false)); m_pInterFBO = FBOImagePtr(new FBOImage(size, B8G8R8A8, GL_FLOAT, false, false)); if (!s_pHorizShader) { initShaders(); } calcKernel(); m_pGaussCurvePBO->setImage(m_Kernel); // dumpKernel(); } GPUBlurFilter::~GPUBlurFilter() { ObjectCounter::get()->decRef(&typeid(*this)); } void GPUBlurFilter::applyOnGPU() { m_pInterFBO->activate(); s_pHorizShader->activate(); s_pHorizShader->setUniformIntParam("radius", (m_KernelWidth-1)/2); s_pHorizShader->setUniformIntParam("Texture", 0); s_pHorizShader->setUniformIntParam("kernelTex", 1); m_pGaussCurvePBO->activateTex(GL_TEXTURE1); getSrcPBO()->draw(); getDestFBO()->activate(); s_pVertShader->activate(); s_pVertShader->setUniformIntParam("radius", (m_KernelWidth-1)/2); s_pVertShader->setUniformIntParam("Texture", 0); s_pHorizShader->setUniformIntParam("kernelTex", 1); m_pInterFBO->draw(); getDestFBO()->deactivate(); } void GPUBlurFilter::initShaders() { string sProgramHead = "#extension GL_ARB_texture_rectangle : enable\n" "uniform sampler2DRect Texture;\n" "uniform int radius;\n" "uniform sampler2DRect kernelTex;\n" ; string sHorizProgram = sProgramHead + "void main(void)\n" "{\n" " vec4 sum = vec4(0,0,0,0);\n" " for (int i=-radius; i<=radius; ++i) {\n" " vec4 tex = texture2DRect(Texture, gl_TexCoord[0].st+vec2(i,0));\n" " float coeff = texture2DRect(kernelTex, vec2(float(i+radius)+0.5,0)).r;\n" " sum += tex*coeff;\n" " }\n" " gl_FragColor = sum;\n" "}\n" ; s_pHorizShader = OGLShaderPtr(new OGLShader(sHorizProgram)); string sVertProgram = sProgramHead + "void main(void)\n" "{\n" " vec4 sum = vec4(0,0,0,0);\n" " for (int i=-radius; i<=radius; ++i) {\n" " vec4 tex = texture2DRect(Texture, gl_TexCoord[0].st+vec2(0,i));\n" " float coeff = texture2DRect(kernelTex, vec2(float(i+radius)+0.5,0)).r;\n" " sum += tex*coeff;\n" " }\n" " gl_FragColor = sum;\n" "}\n" ; s_pVertShader = OGLShaderPtr(new OGLShader(sVertProgram)); } void GPUBlurFilter::dumpKernel() { cerr << "Gauss, std dev " << m_StdDev << endl; cerr << " Kernel width: " << m_KernelWidth << endl; float sum = 0; for (int i=0; i<m_KernelWidth; ++i) { sum += m_Kernel[i]; cerr << " " << m_Kernel[i] << endl; } cerr << "Sum of coefficients: " << sum << endl; } void GPUBlurFilter::calcKernel() { int KernelCenter = int(ceil(m_StdDev*3)); m_KernelWidth = KernelCenter*2+1; assert (m_KernelWidth < 256); float sum = 0; for (int i=0; i<= KernelCenter; ++i) { m_Kernel[KernelCenter+i] = float(exp(-i*i/(2*m_StdDev*m_StdDev)) /sqrt(2*PI*m_StdDev*m_StdDev)); sum += m_Kernel[KernelCenter+i]; if (i != 0) { m_Kernel[KernelCenter-i] = m_Kernel[KernelCenter+i]; sum += m_Kernel[KernelCenter-i]; } } // Make sure the sum of coefficients is 1 despite the inaccuracies // introduced by using a kernel of finite size. for (int i=0; i<=m_KernelWidth; ++i) { m_Kernel[i] /= sum; } } } // namespace <commit_msg>graphics/GPUBlurFilter.cpp: fixed bug when setting parameters for gaussian blur<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2008 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "GPUBlurFilter.h" #include "Bitmap.h" #include "../base/ObjectCounter.h" #include "../base/MathHelper.h" #include <iostream> using namespace std; namespace avg { OGLShaderPtr GPUBlurFilter::s_pHorizShader; OGLShaderPtr GPUBlurFilter::s_pVertShader; GPUBlurFilter::GPUBlurFilter(const IntPoint& size, PixelFormat pfSrc, double stdDev) : GPUFilter(size, pfSrc), m_StdDev(stdDev) { ObjectCounter::get()->incRef(&typeid(*this)); init(); } GPUBlurFilter::GPUBlurFilter(PBOImagePtr pSrcPBO, FBOImagePtr pDestFBO, double stdDev) : GPUFilter(pSrcPBO, pDestFBO), m_StdDev(stdDev) { ObjectCounter::get()->incRef(&typeid(*this)); init(); } void GPUBlurFilter::init() { IntPoint size = getSrcPBO()->getSize(); m_pGaussCurvePBO = PBOImagePtr(new PBOImage(IntPoint(255, 1), I8, GL_FLOAT, false, false)); m_pInterFBO = FBOImagePtr(new FBOImage(size, B8G8R8A8, GL_FLOAT, false, false)); if (!s_pHorizShader) { initShaders(); } calcKernel(); m_pGaussCurvePBO->setImage(m_Kernel); // dumpKernel(); } GPUBlurFilter::~GPUBlurFilter() { ObjectCounter::get()->decRef(&typeid(*this)); } void GPUBlurFilter::applyOnGPU() { m_pInterFBO->activate(); s_pHorizShader->activate(); s_pHorizShader->setUniformIntParam("radius", (m_KernelWidth-1)/2); s_pHorizShader->setUniformIntParam("Texture", 0); s_pHorizShader->setUniformIntParam("kernelTex", 1); m_pGaussCurvePBO->activateTex(GL_TEXTURE1); getSrcPBO()->draw(); getDestFBO()->activate(); s_pVertShader->activate(); s_pVertShader->setUniformIntParam("radius", (m_KernelWidth-1)/2); s_pVertShader->setUniformIntParam("Texture", 0); s_pVertShader->setUniformIntParam("kernelTex", 1); m_pInterFBO->draw(); getDestFBO()->deactivate(); } void GPUBlurFilter::initShaders() { string sProgramHead = "#extension GL_ARB_texture_rectangle : enable\n" "uniform sampler2DRect Texture;\n" "uniform int radius;\n" "uniform sampler2DRect kernelTex;\n" ; string sHorizProgram = sProgramHead + "void main(void)\n" "{\n" " vec4 sum = vec4(0,0,0,0);\n" " for (int i=-radius; i<=radius; ++i) {\n" " vec4 tex = texture2DRect(Texture, gl_TexCoord[0].st+vec2(i,0));\n" " float coeff = texture2DRect(kernelTex, vec2(float(i+radius)+0.5,0)).r;\n" " sum += tex*coeff;\n" " }\n" " gl_FragColor = sum;\n" "}\n" ; s_pHorizShader = OGLShaderPtr(new OGLShader(sHorizProgram)); string sVertProgram = sProgramHead + "void main(void)\n" "{\n" " vec4 sum = vec4(0,0,0,0);\n" " for (int i=-radius; i<=radius; ++i) {\n" " vec4 tex = texture2DRect(Texture, gl_TexCoord[0].st+vec2(0,i));\n" " float coeff = texture2DRect(kernelTex, vec2(float(i+radius)+0.5,0)).r;\n" " sum += tex*coeff;\n" " }\n" " gl_FragColor = sum;\n" "}\n" ; s_pVertShader = OGLShaderPtr(new OGLShader(sVertProgram)); } void GPUBlurFilter::dumpKernel() { cerr << "Gauss, std dev " << m_StdDev << endl; cerr << " Kernel width: " << m_KernelWidth << endl; float sum = 0; for (int i=0; i<m_KernelWidth; ++i) { sum += m_Kernel[i]; cerr << " " << m_Kernel[i] << endl; } cerr << "Sum of coefficients: " << sum << endl; } void GPUBlurFilter::calcKernel() { int KernelCenter = int(ceil(m_StdDev*3)); m_KernelWidth = KernelCenter*2+1; assert (m_KernelWidth < 256); float sum = 0; for (int i=0; i<= KernelCenter; ++i) { m_Kernel[KernelCenter+i] = float(exp(-i*i/(2*m_StdDev*m_StdDev)) /sqrt(2*PI*m_StdDev*m_StdDev)); sum += m_Kernel[KernelCenter+i]; if (i != 0) { m_Kernel[KernelCenter-i] = m_Kernel[KernelCenter+i]; sum += m_Kernel[KernelCenter-i]; } } // Make sure the sum of coefficients is 1 despite the inaccuracies // introduced by using a kernel of finite size. for (int i=0; i<=m_KernelWidth; ++i) { m_Kernel[i] /= sum; } } } // namespace <|endoftext|>
<commit_before>void twoscales() { //example of macro illustrating how to superimpose two histograms //with different scales in the "same" pad. // To see the output of this macro, click begin_html <a href="gif/twoscales.gif" >here</a> end_html TCanvas *c1 = new TCanvas("c1","hists with different scales",600,400); //create/fill draw h1 gStyle->SetOptStat(kFALSE); TH1F *h1 = new TH1F("h1","my histogram",100,-3,3); Int_t i; for (i=0;i<10000;i++) h1->Fill(gRandom->Gaus(0,1)); h1->Draw(); c1->Update(); //create hint1 filled with the bins integral of h1 TH1F *hint1 = new TH1F("hint1","h1 bins integral",100,-3,3); Float_t sum = 0; for (i=1;i<=100;i++) { sum += h1->GetBinContent(i); hint1->SetBinContent(i,sum); } //scale hint1 to the pad coordinates Float_t rightmax = 1.1*hint1->GetMaximum(); Float_t scale = gPad->GetUymax()/rightmax; hint1->SetLineColor(kRed); hint1->Scale(scale); hint1->Draw("same"); //draw an axis on the right side TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(), gPad->GetUxmax(), gPad->GetUymax(),0,rightmax,510,"+L"); axis->SetLineColor(kRed); axis->SetTextColor(kRed); axis->Draw(); } <commit_msg>Add include files for classes used by this tutorial to support the call via .x twoscales.C++<commit_after>#include "TCanvas.h" #include "TStyle.h" #include "TH1.h" #include "TGaxis.h" #include "TRandom.h" void twoscales() { //example of macro illustrating how to superimpose two histograms //with different scales in the "same" pad. // To see the output of this macro, click begin_html <a href="gif/twoscales.gif" >here</a> end_html TCanvas *c1 = new TCanvas("c1","hists with different scales",600,400); //create/fill draw h1 gStyle->SetOptStat(kFALSE); TH1F *h1 = new TH1F("h1","my histogram",100,-3,3); Int_t i; for (i=0;i<10000;i++) h1->Fill(gRandom->Gaus(0,1)); h1->Draw(); c1->Update(); //create hint1 filled with the bins integral of h1 TH1F *hint1 = new TH1F("hint1","h1 bins integral",100,-3,3); Float_t sum = 0; for (i=1;i<=100;i++) { sum += h1->GetBinContent(i); hint1->SetBinContent(i,sum); } //scale hint1 to the pad coordinates Float_t rightmax = 1.1*hint1->GetMaximum(); Float_t scale = gPad->GetUymax()/rightmax; hint1->SetLineColor(kRed); hint1->Scale(scale); hint1->Draw("same"); //draw an axis on the right side TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(), gPad->GetUxmax(), gPad->GetUymax(),0,rightmax,510,"+L"); axis->SetLineColor(kRed); axis->SetTextColor(kRed); axis->Draw(); } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author ([email protected]) \authors ([email protected]) \date 10.05.2009 \brief common- \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdocommon.h" #include "utils/rdofile.h" #include "utils/rdotime.h" #include "utils/test/utils_common_test/resource.h" // -------------------------------------------------------------------------------- const tstring s_testFileName(_T("test_file")); const tstring s_resourceStr1(_T("test_101")); const tstring s_resourceStr2(_T("test_102 22")); const tstring s_resourceStr3(_T("test_103 test_101 33 test_102 22")); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_ResourceFormat) { tstring str1 = rdo::format(IDS_STRING101); BOOST_CHECK(str1 == s_resourceStr1); tstring str2 = rdo::format(IDS_STRING102, 22); BOOST_CHECK(str2 == s_resourceStr2); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); BOOST_CHECK(str3 == s_resourceStr3); } #endif // OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { tstring file(_T("/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { tstring file(_T("/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { tstring file(_T(":/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { tstring file(_T(":/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { tstring file(_T(":\\rdo\\ \\files\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\rdo\\ \\files\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { tstring file(_T(":\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<tstring> name_set; for(int i = 0; i < 15; ++i) { tstring file_name = rdo::File::getTempFileName(); BOOST_CHECK(name_set.find(file_name) == name_set.end()); name_set.insert(file_name); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); std::cout << _T("Today: ") << timeValue.asString() << _T(" is not it?"); } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <commit_msg> - тест сервера автосборки<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author ([email protected]) \authors ([email protected]) \date 10.05.2009 \brief common- \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdocommon.h" #include "utils/rdofile.h" #include "utils/rdotime.h" #include "utils/test/utils_common_test/resource.h" // -------------------------------------------------------------------------------- const tstring s_testFileName(_T("test_file")); const tstring s_resourceStr1(_T("test_101")); const tstring s_resourceStr2(_T("test_102 22")); const tstring s_resourceStr3(_T("test_103 test_101 33 test_102 22")); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_ResourceFormat) { tstring str1 = rdo::format(IDS_STRING101); BOOST_CHECK(str1 == s_resourceStr1); tstring str2 = rdo::format(IDS_STRING102, 22); BOOST_CHECK(str2 == s_resourceStr2); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); BOOST_CHECK(str3 == s_resourceStr3); } #endif // OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { tstring file(_T("/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr3")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { tstring file(_T("/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { tstring file(_T(":/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { tstring file(_T(":/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { tstring file(_T(":\\rdo\\ \\files\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\rdo\\ \\files\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { tstring file(_T(":\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<tstring> name_set; for(int i = 0; i < 15; ++i) { tstring file_name = rdo::File::getTempFileName(); BOOST_CHECK(name_set.find(file_name) == name_set.end()); name_set.insert(file_name); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); std::cout << _T("Today: ") << timeValue.asString() << _T(" is not it?"); } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <|endoftext|>
<commit_before>#include "sinXScrollDemo.h" #include "vrambatcher.h" #include <cmath> #include <nds/arm9/input.h> SinXScrollDemo::SinXScrollDemo() : offset(0), amplitude(1) {} void SinXScrollDemo::AcceptInput() { auto keys = keysCurrent(); if(keys & KEY_X && amplitude > MIN_AMPLITUDE) { amplitude -= 0.01; } else if(keys & KEY_Y && amplitude < MAX_AMPLITUDE) { amplitude += 0.01; } if(keys & KEY_UP && speed < MAX_SPEED) { speed += 0.01; } else if(keys & KEY_DOWN && speed > MIN_SPEED) { speed -= 0.01; } if(keys & KEY_LEFT && lineSpeed > MIN_LINESPEED) { lineSpeed -= 0.01; } else if(keys & KEY_RIGHT && lineSpeed < MAX_LINESPEED) { lineSpeed += 0.01; } } void SinXScrollDemo::Load() { setupDefaultBG(); } void SinXScrollDemo::Unload() {} void SinXScrollDemo::PrepareFrame(VramBatcher &batcher) { offset += speed; float lineOffset = offset; for (int scanline = 0; scanline < SCREEN_HEIGHT; ++scanline) { int xscroll = std::sin(lineOffset)*amplitude; batcher.AddPoke(scanline, xscroll, &REG_BG0HOFS); lineOffset += lineSpeed; } }<commit_msg>Limits for x scroll demo<commit_after>#include "sinXScrollDemo.h" #include "vrambatcher.h" #include <cmath> #include <nds/arm9/input.h> #define MIN_AMPLITUDE 0 #define MAX_AMPLITUDE 256 #define MAX_SPEED 0.2 #define MIN_SPEED 0 #define MAX_LINESPEED 0.2 #define MIN_LINESPEED 0 SinXScrollDemo::SinXScrollDemo() : offset(0), amplitude(1) {} void SinXScrollDemo::AcceptInput() { auto keys = keysCurrent(); if(keys & KEY_X && amplitude > MIN_AMPLITUDE) { amplitude -= 0.01; } else if(keys & KEY_Y && amplitude < MAX_AMPLITUDE) { amplitude += 0.01; } if(keys & KEY_UP && speed < MAX_SPEED) { speed += 0.01; } else if(keys & KEY_DOWN && speed > MIN_SPEED) { speed -= 0.01; } if(keys & KEY_LEFT && lineSpeed > MIN_LINESPEED) { lineSpeed -= 0.01; } else if(keys & KEY_RIGHT && lineSpeed < MAX_LINESPEED) { lineSpeed += 0.01; } } void SinXScrollDemo::Load() { setupDefaultBG(); } void SinXScrollDemo::Unload() {} void SinXScrollDemo::PrepareFrame(VramBatcher &batcher) { offset += speed; float lineOffset = offset; for (int scanline = 0; scanline < SCREEN_HEIGHT; ++scanline) { int xscroll = std::sin(lineOffset)*amplitude; batcher.AddPoke(scanline, xscroll, &REG_BG0HOFS); lineOffset += lineSpeed; } }<|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_GRID_PROVIDER_HH #define DUNE_STUFF_GRID_PROVIDER_HH #include <memory> #include <dune/grid/sgrid.hh> #include <dune/stuff/common/configtree.hh> #include "provider/interface.hh" #include "provider/cube.hh" //#include "provider/gmsh.hh" //#include "provider/starcd.hh" namespace Dune { namespace Stuff { //#if HAVE_DUNE_GRID template< class GridType = Dune::SGrid< 2, 2 > > class GridProviders { public: static std::vector< std::string > available() { return { "gridprovider.cube" //#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG //#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID // , "gridprovider.gmsh" //#endif //#endif // , "gridprovider.starcd" }; } // ... available() static Common::ConfigTree default_config(const std::string type, const std::string subname = "") { namespace Providers = Stuff::Grid::Providers; if (type == Providers::Cube< GridType >::static_id()) { return Providers::Cube< GridType >::default_config(subname); // } //#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG //#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID // else if (type == "gridprovider.gmsh") { // return GridProviderGmsh< GridType >::default_config(subname); // } //#endif //#endif // else if (type == "gridprovider.starcd") { // return GridProviderStarCD< GridType >::default_config(subname); } else DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given, "'" << type << "' is not a valid grid.provider!"); } // ... default_config(...) static std::unique_ptr< Stuff::Grid::ProviderInterface< GridType > > create(const std::string& type = available()[0], const Common::ConfigTree config = default_config(available()[0])) { namespace Providers = Stuff::Grid::Providers; if (type == Providers::Cube< GridType >::static_id()) return Providers::Cube< GridType >::create(config); //#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG //#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID // else if (type == "gridprovider.gmsh") // return GridProviderGmsh< GridType >::create(config); //#endif //#endif // else if (type == "gridprovider.starcd") // return GridProviderStarCD< GridType >::create(config); else DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given, "'" << type << "' is not a valid grid.provider!"); } // ... create(...) }; // class GridProviders //#endif // HAVE_DUNE_GRID } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_HH <commit_msg>[grid.provider] updated exceptions and ids<commit_after>// This file is part of the dune-stuff project: // https://users.dune-project.org/projects/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_STUFF_GRID_PROVIDER_HH #define DUNE_STUFF_GRID_PROVIDER_HH #include <memory> #include <dune/grid/sgrid.hh> #include <dune/stuff/common/configtree.hh> #include "provider/interface.hh" #include "provider/cube.hh" //#include "provider/gmsh.hh" //#include "provider/starcd.hh" namespace Dune { namespace Stuff { //#if HAVE_DUNE_GRID template< class GridType = Dune::SGrid< 2, 2 > > class GridProviders { public: typedef Stuff::Grid::ProviderInterface< GridType > InterfaceType; static std::vector< std::string > available() { namespace Providers = Stuff::Grid::Providers; return { Providers::Cube< GridType >::static_id() //#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG //#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID // , "gridprovider.gmsh" //#endif //#endif // , "gridprovider.starcd" }; } // ... available() static Common::ConfigTree default_config(const std::string type, const std::string subname = "") { namespace Providers = Stuff::Grid::Providers; if (type == Providers::Cube< GridType >::static_id()) { return Providers::Cube< GridType >::default_config(subname); // } //#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG //#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID // else if (type == "gridprovider.gmsh") { // return GridProviderGmsh< GridType >::default_config(subname); // } //#endif //#endif // else if (type == "gridprovider.starcd") { // return GridProviderStarCD< GridType >::default_config(subname); } else DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given, "'" << type << "' is not a valid " << InterfaceType::static_id() << "!"); } // ... default_config(...) static std::unique_ptr< InterfaceType > create(const std::string& type = available()[0], const Common::ConfigTree config = default_config(available()[0])) { namespace Providers = Stuff::Grid::Providers; if (type == Providers::Cube< GridType >::static_id()) return Providers::Cube< GridType >::create(config); //#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG //#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID // else if (type == "gridprovider.gmsh") // return GridProviderGmsh< GridType >::create(config); //#endif //#endif // else if (type == "gridprovider.starcd") // return GridProviderStarCD< GridType >::create(config); else DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given, "'" << type << "' is not a valid " << InterfaceType::static_id() << "!"); } // ... create(...) }; // class GridProviders //#endif // HAVE_DUNE_GRID } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_HH <|endoftext|>
<commit_before>#include "test_common.hh" #include <memory> #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> #include <dune/stuff/function/interface.hh> #include <dune/stuff/function/expression.hh> #include <dune/stuff/function/checkerboard.hh> #include <dune/stuff/function/spe10.hh> #include <dune/stuff/function/constant.hh> #include <dune/stuff/function/affineparametric/checkerboard.hh> using namespace Dune::Stuff; typedef testing::Types< FunctionExpression< double, 1, double, 1 > , FunctionCheckerboard< double, 1, double, 1 > , FunctionCheckerboard< double, 2, double, 1 > , FunctionCheckerboard< double, 3, double, 1 > , FunctionConstant< double, 1, double, 1 > , FunctionConstant< double, 2, double, 1 > , FunctionConstant< double, 3, double, 1 > // , FunctionSpe10Model1< double, 2, double, 1 > // <- this makes only sense, if the data file is present > Functions; typedef testing::Types< AffineParametricFunctionCheckerboard< double, 1, double > , AffineParametricFunctionCheckerboard< double, 2, double > , AffineParametricFunctionCheckerboard< double, 3, double > > AffineParametricFunctions; typedef testing::Types< FunctionConstant< double, 1, double, 1 > , FunctionConstant< double, 2, double, 1 > , FunctionConstant< double, 3, double, 1 > > TimedependentFunctions; template< class FunctionType > struct FunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; void check() const { DomainType x(1); RangeType ret(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); function->evaluate(x, ret); } }; // struct FunctionTest template< class FunctionType > struct ParametricFunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; typedef typename FunctionType::ParamFieldType ParamFieldType; static const int maxParamDim = FunctionType::maxParamDim; typedef typename FunctionType::ParamType ParamType; void check() const { DomainType x(1); RangeType ret(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); const bool parametric = function->parametric(); assert(parametric); const size_t paramSize = function->paramSize(); assert(paramSize > 0); const std::vector< ParamType >& paramRange = function->paramRange(); assert(paramRange.size() == 2); assert(paramRange[0].size() == paramSize); assert(paramRange[1].size() == paramSize); const std::vector< std::string >& paramExplanation = function->paramExplanation(); assert(paramExplanation.size() == paramSize); function->evaluate(x, paramRange[0], ret); } }; // struct ParametricFunctionTest template< class FunctionType > struct AffineParametricFunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; typedef typename FunctionType::ParamFieldType ParamFieldType; static const int maxParamDim = FunctionType::maxParamDim; typedef typename FunctionType::ParamType ParamType; typedef typename FunctionType::ComponentType ComponentType; typedef typename FunctionType::CoefficientType CoefficientType; void check() const { DomainType x(1); RangeType ret(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); const bool parametric = function->parametric(); assert(parametric); const size_t paramSize = function->paramSize(); assert(paramSize > 0); const std::vector< ParamType >& paramRange = function->paramRange(); assert(paramRange.size() == 2); assert(paramRange[0].size() == paramSize); assert(paramRange[1].size() == paramSize); const std::vector< std::string >& paramExplanation = function->paramExplanation(); assert(paramExplanation.size() == paramSize); function->evaluate(x, paramRange[0], ret); const bool affineParametric = function->affineparametric(); assert(affineParametric); const std::vector< std::shared_ptr< const ComponentType > >& components = function->components(); const std::vector< std::shared_ptr< const CoefficientType > >& coefficients = function->coefficients(); assert(components.size() == coefficients.size()); const bool hasAffinePart = function->hasAffinePart(); if (hasAffinePart) const std::shared_ptr< ComponentType >& DUNE_UNUSED(affinePart) = function->affinePart(); } }; // struct AffineParametricFunctionTest template< class FunctionType > struct TimedependentFunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; void check() const { DomainType x(1); RangeType ret(0); double t(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); function->evaluate(x, t, ret); } }; // struct TimedependentFunctionTest TYPED_TEST_CASE(FunctionTest, Functions); TYPED_TEST(FunctionTest, Function) { this->check(); } TYPED_TEST_CASE(ParametricFunctionTest, AffineParametricFunctions); TYPED_TEST(ParametricFunctionTest, ParametricFunction) { this->check(); } TYPED_TEST_CASE(AffineParametricFunctionTest, AffineParametricFunctions); TYPED_TEST(AffineParametricFunctionTest, AffineParametricFunction) { this->check(); } TYPED_TEST_CASE(TimedependentFunctionTest, TimedependentFunctions); TYPED_TEST(TimedependentFunctionTest, TimedependentFunction) { this->check(); } int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <commit_msg>[test.function] added test of fixed function<commit_after>#include "test_common.hh" #include <memory> #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> #include <dune/stuff/function/interface.hh> #include <dune/stuff/function/expression.hh> #include <dune/stuff/function/checkerboard.hh> #include <dune/stuff/function/spe10.hh> #include <dune/stuff/function/constant.hh> #include <dune/stuff/function/affineparametric/checkerboard.hh> #include <dune/stuff/function/fixed.hh> using namespace Dune::Stuff; typedef testing::Types< FunctionExpression< double, 1, double, 1 > , FunctionCheckerboard< double, 1, double, 1 > , FunctionCheckerboard< double, 2, double, 1 > , FunctionCheckerboard< double, 3, double, 1 > , FunctionConstant< double, 1, double, 1 > , FunctionConstant< double, 2, double, 1 > , FunctionConstant< double, 3, double, 1 > // , FunctionSpe10Model1< double, 2, double, 1 > // <- this makes only sense, if the data file is present > Functions; typedef testing::Types< AffineParametricFunctionCheckerboard< double, 1, double > , AffineParametricFunctionCheckerboard< double, 2, double > , AffineParametricFunctionCheckerboard< double, 3, double > > AffineParametricFunctions; typedef testing::Types< FunctionConstant< double, 1, double, 1 > , FunctionConstant< double, 2, double, 1 > , FunctionConstant< double, 3, double, 1 > > TimedependentFunctions; template< class FunctionType > struct FunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; void check() const { DomainType x(1); RangeType ret(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); function->evaluate(x, ret); } }; // struct FunctionTest template< class FunctionType > struct ParametricFunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; typedef typename FunctionType::ParamFieldType ParamFieldType; static const int maxParamDim = FunctionType::maxParamDim; typedef typename FunctionType::ParamType ParamType; typedef FunctionFixedParameter< DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols > FixedParameterFunctionType; void check() const { DomainType x(1); RangeType ret(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); const bool parametric = function->parametric(); assert(parametric); const size_t paramSize = function->paramSize(); assert(paramSize > 0); const std::vector< ParamType >& paramRange = function->paramRange(); assert(paramRange.size() == 2); assert(paramRange[0].size() == paramSize); assert(paramRange[1].size() == paramSize); const std::vector< std::string >& paramExplanation = function->paramExplanation(); assert(paramExplanation.size() == paramSize); function->evaluate(x, paramRange[0], ret); const FixedParameterFunctionType fixedFunction(function, paramRange[0]); const std::string DUNE_UNUSED(f_name) = fixedFunction.name(); const int DUNE_UNUSED(f_order) = fixedFunction.order(); const bool f_parametric = fixedFunction.parametric(); assert(!f_parametric); fixedFunction.evaluate(x, ret); } }; // struct ParametricFunctionTest template< class FunctionType > struct AffineParametricFunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; typedef typename FunctionType::ParamFieldType ParamFieldType; static const int maxParamDim = FunctionType::maxParamDim; typedef typename FunctionType::ParamType ParamType; typedef typename FunctionType::ComponentType ComponentType; typedef typename FunctionType::CoefficientType CoefficientType; void check() const { DomainType x(1); RangeType ret(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); const bool parametric = function->parametric(); assert(parametric); const size_t paramSize = function->paramSize(); assert(paramSize > 0); const std::vector< ParamType >& paramRange = function->paramRange(); assert(paramRange.size() == 2); assert(paramRange[0].size() == paramSize); assert(paramRange[1].size() == paramSize); const std::vector< std::string >& paramExplanation = function->paramExplanation(); assert(paramExplanation.size() == paramSize); function->evaluate(x, paramRange[0], ret); const bool affineParametric = function->affineparametric(); assert(affineParametric); const std::vector< std::shared_ptr< const ComponentType > >& components = function->components(); const std::vector< std::shared_ptr< const CoefficientType > >& coefficients = function->coefficients(); assert(components.size() == coefficients.size()); const bool hasAffinePart = function->hasAffinePart(); if (hasAffinePart) const std::shared_ptr< ComponentType >& DUNE_UNUSED(affinePart) = function->affinePart(); } }; // struct AffineParametricFunctionTest template< class FunctionType > struct TimedependentFunctionTest : public ::testing::Test { typedef typename FunctionType::DomainFieldType DomainFieldType; static const int dimDomain = FunctionType::dimDomain; typedef typename FunctionType::DomainType DomainType; typedef typename FunctionType::RangeFieldType RangeFieldType; static const int dimRangeRows = FunctionType::dimRangeRows; static const int dimRangeCols = FunctionType::dimRangeCols; typedef typename FunctionType::RangeType RangeType; typedef FunctionFixedTime< DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols > FixedTimeFunctionType; void check() const { DomainType x(1); RangeType ret(0); double t(0); const std::shared_ptr< const FunctionType > function(FunctionType::create(FunctionType::createSampleDescription())); const std::string DUNE_UNUSED(name) = function->name(); const int DUNE_UNUSED(order) = function->order(); function->evaluate(x, t, ret); const FixedTimeFunctionType fixedFunction(function, 0); const std::string DUNE_UNUSED(f_name) = fixedFunction.name(); const int DUNE_UNUSED(f_order) = fixedFunction.order(); fixedFunction.evaluate(x, ret); } }; // struct TimedependentFunctionTest TYPED_TEST_CASE(FunctionTest, Functions); TYPED_TEST(FunctionTest, Function) { this->check(); } TYPED_TEST_CASE(ParametricFunctionTest, AffineParametricFunctions); TYPED_TEST(ParametricFunctionTest, ParametricFunction) { this->check(); } TYPED_TEST_CASE(AffineParametricFunctionTest, AffineParametricFunctions); TYPED_TEST(AffineParametricFunctionTest, AffineParametricFunction) { this->check(); } TYPED_TEST_CASE(TimedependentFunctionTest, TimedependentFunctions); TYPED_TEST(TimedependentFunctionTest, TimedependentFunction) { this->check(); } int main(int argc, char** argv) { test_init(argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: FindVolumeMountPointClose.cpp,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2003-04-08 15:52:48 $ * * 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): _______________________________________ * * ************************************************************************/ #include "macros.h" DEFINE_DEFAULT_THUNK( kernel32, TRYLOAD, BOOL, WINAPI, FindVolumeMountPointClose, (HANDLE hFindVolumeMountPoint ) )<commit_msg>INTEGRATION: CWS ooo19126 (1.2.340); FILE MERGED 2005/09/05 17:45:36 rt 1.2.340.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FindVolumeMountPointClose.cpp,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:15:47 $ * * 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 * ************************************************************************/ #include "macros.h" DEFINE_DEFAULT_THUNK( kernel32, TRYLOAD, BOOL, WINAPI, FindVolumeMountPointClose, (HANDLE hFindVolumeMountPoint ) )<|endoftext|>
<commit_before>/* * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved. */ #include "objparser.h" #include <sstream> class Exception { public: Exception(const char* msg) : m_msg(msg) {} const char* getMsg() { return m_msg.c_str(); } private: std::string m_msg; }; void skipToNextLine( std::istream& stream ) { stream.ignore(20000, '\n'); } bool parsingError( std::istream& stream ) { return !stream.good() || stream.fail(); } bool skipSpaces( std::istream& stream ) { char c = 0; while( stream.good() ) { char pc = stream.peek(); if( pc == ' ' || pc == '\t' || pc == '\r' ) stream.get(c); else break; } return c != 0; } void skipMandatorySpaces( std::istream& stream ) { if( !skipSpaces(stream) ) throw Exception("space expected"); } template<int Dim> void getV( V<Dim>& v, std::istream& stream ) { for( int i = 0; i < Dim; ++i ) { skipMandatorySpaces( stream ); stream >> v.v[i]; if( parsingError( stream ) ) throw Exception("float value expected"); } } void ObjParser::ParseV( std::istream& stream ) { V3 v; getV( v, stream ); m_points.push_back( v ); skipToNextLine( stream );// [jeromecg 20110728] Ignore 4D coords for now } void ObjParser::ParseN( std::istream& stream ) { V3 v; getV( v, stream ); m_normals.push_back( v ); skipToNextLine( stream ); } void ObjParser::ParseT( std::istream& stream ) { V2 v; getV( v, stream ); m_texCoords.push_back( v ); skipToNextLine( stream );// [jeromecg 20110728] Ignore 3D coords for now } void ObjParser::ParseF( std::istream& stream ) { int nbFacePts = 0; int initalFacePt = (int)m_triangleIndices.size(); if( m_pointIndices.size() < m_points.size() ) m_pointIndices.resize( m_points.size() ); while( true ) { bool hadSpaces = skipSpaces( stream ); if( stream.peek() == '\n' ) { skipToNextLine( stream ); break; } else if( !hadSpaces ) throw Exception("space expected"); PointIndices indices; stream >> indices.m_point; if( parsingError( stream ) ) throw Exception("int value expected"); --indices.m_point; if( indices.m_point < 0 || indices.m_point > (int)m_points.size() ) throw Exception("out of range point index"); char c = 0; stream.get(c); if(c == '/') { if(stream.peek() != '/') { stream >> indices.m_texCoord; if( parsingError( stream ) ) throw Exception("int value expected"); --indices.m_texCoord; if( indices.m_texCoord < 0 || indices.m_texCoord > (int)m_texCoords.size() ) throw Exception("out of range texture index"); } c = 0; stream.get(c); if(c != '/') stream.unget(); else { stream >> indices.m_normal; if( parsingError( stream ) ) throw Exception("int value expected"); --indices.m_normal; if( indices.m_normal < 0 || indices.m_normal > (int)m_normals.size() ) throw Exception("out of range normal index"); } } // [jeromecg 20110728] Check if we need to unshare the vertex data // Note: this would be more complex (and might have to be done later) if we were taking smoothing groups into account... int ptIndex = indices.m_point; if( !m_pointIndices[indices.m_point].isInitialized() ) { m_pointIndices[indices.m_point] = indices; } else if( m_pointIndices[indices.m_point] != indices ) { ptIndex = (int)m_pointIndices.size(); m_pointIndices.push_back( indices ); } nbFacePts++; if( nbFacePts <= 3 ) { m_triangleIndices.push_back( ptIndex ); } else { //Simple triangulation: 0 1 2 / 0 2 3 / 0 3 4... int first = m_triangleIndices[initalFacePt]; int second = m_triangleIndices.back(); m_triangleIndices.push_back( first ); m_triangleIndices.push_back( second ); m_triangleIndices.push_back( ptIndex ); } } if( nbFacePts < 3 ) throw Exception("face has less than 3 points"); } void ObjParser::ComputeMissingNormals() { //Quick check if any normal is missing size_t i; for( i = 0; i < m_triangleIndices.size(); ++i ) { if( m_pointIndices[ m_triangleIndices[i] ].m_normal == INT_MAX ) break; } if( i == m_triangleIndices.size() ) return; // [jeromecg 20110728] Make it simple for now: if any normal is missing, recompute them all. // [jeromecg 20110728] TODO: take smoothing groups into account // Compute triangle normals size_t nbTriangles = m_triangleIndices.size() / 3; std::vector< V3 > triangleNormals; triangleNormals.resize( nbTriangles ); for( i = 0; i < nbTriangles; ++i ) { V3 v1 = m_points[ m_pointIndices[ m_triangleIndices[ i*3+1 ] ].m_point ] - m_points[ m_pointIndices[ m_triangleIndices[ i*3 ] ].m_point ]; V3 v2 = m_points[ m_pointIndices[ m_triangleIndices[ i*3+2 ] ].m_point ] - m_points[ m_pointIndices[ m_triangleIndices[ i*3 ] ].m_point ]; triangleNormals[i] = v1.Cross( v2 ); triangleNormals[i].Normalize(); } // Compute point normals by simply averaging adjacent triangle normals m_normals.resize( m_points.size(), V3( 0, 0, 0 ) ); for( i = 0; i < m_triangleIndices.size(); ++i ) { int ptIndex = m_pointIndices[ m_triangleIndices[i] ].m_point; m_normals[ptIndex] = m_normals[ptIndex] + triangleNormals[i/3]; } for( i = 0; i < m_normals.size(); ++i ) { m_normals[i].Normalize(); m_pointIndices[i].m_normal = i; } } ObjParser::ObjParser( std::istream& stream ) { // [jeromecg 20110728] Right now this parser is very simple as it agglomerates all points and faces in 1 big object, // ignoring materials, groups, smoothing groups, etc. int lineCount = 0; try { while( stream.good() ) { char c = 0; stream.get(c); switch( c ) { case '\n': case '\r': case ' ': case '\t': break; case 'v': { char nextC; stream.get(nextC); switch( nextC ) { case 'p': skipToNextLine( stream );//patch: ignore break; case 'n': ParseN( stream ); break; case 't': ParseT( stream ); break; default: stream.unget(); ParseV( stream ); } break; } case 'f': ParseF( stream ); break; default: skipToNextLine( stream ); } ++lineCount; } ComputeMissingNormals(); } catch ( Exception e ) { std::stringstream sstr; sstr << "Error while parsing .obj file at line " << lineCount << ": " << e.getMsg(); m_errors.push_back( sstr.str() ); } catch ( ... ) { std::stringstream sstr; sstr << "Unexpected error while parsing .obj file at line " << lineCount; m_errors.push_back( sstr.str() ); } } void ObjParser::GetTriangleIndices(int triIndex, int& i1, int& i2, int& i3)const { i1 = m_triangleIndices[triIndex*3]; i2 = m_triangleIndices[triIndex*3+1]; i3 = m_triangleIndices[triIndex*3+2]; } V3 ObjParser::GetPoint(int ptIndex)const { int index = m_pointIndices[ptIndex].m_point; if( index == INT_MAX ) return V3( 0, 0, 0 ); else return m_points[ index ]; } V3 ObjParser::GetNormal(int ptIndex)const { int index = m_pointIndices[ptIndex].m_normal; if( index == INT_MAX ) return V3( 0, 1, 0 ); else return m_normals[ index ]; } V2 ObjParser::GetTextureCoord(int ptIndex)const { int index = m_pointIndices[ptIndex].m_texCoord; if( index == INT_MAX ) return V2( 0, 0 ); else return m_texCoords[ index ]; } <commit_msg>Various fixes for .obj loader.<commit_after>/* * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved. */ #include "objparser.h" #include <sstream> class Exception { public: Exception(const char* msg) : m_msg(msg) {} const char* getMsg() { return m_msg.c_str(); } private: std::string m_msg; }; bool IsSeparator( char c ) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; } void skipToNextLine( std::istream& stream ) { char c = 0; while( stream.good() ) { stream.get(c); if(c == '\n' || c == '\r') { char pc = stream.peek(); if(pc != c && (pc == '\n' || pc == '\r')) stream.get(c); break; } } } bool parsingError( std::istream& stream ) { return !stream.good() || stream.fail(); } bool skipSpaces( std::istream& stream ) { char c = 0; while( stream.good() ) { char pc = stream.peek(); if( pc == ' ' || pc == '\t' ) stream.get(c); else break; } return c != 0; } void skipMandatorySpaces( std::istream& stream ) { if( !skipSpaces(stream) ) throw Exception("space expected"); } template<int Dim> void getV( V<Dim>& v, std::istream& stream ) { for( int i = 0; i < Dim; ++i ) { skipMandatorySpaces( stream ); stream >> v.v[i]; if( parsingError( stream ) ) throw Exception("float value expected"); } } void ObjParser::ParseV( std::istream& stream ) { V3 v; getV( v, stream ); m_points.push_back( v ); skipToNextLine( stream );// [jeromecg 20110728] Ignore 4D coords for now } void ObjParser::ParseN( std::istream& stream ) { V3 v; getV( v, stream ); m_normals.push_back( v ); skipToNextLine( stream ); } void ObjParser::ParseT( std::istream& stream ) { V2 v; getV( v, stream ); m_texCoords.push_back( v ); skipToNextLine( stream );// [jeromecg 20110728] Ignore 3D coords for now } void ObjParser::ParseF( std::istream& stream ) { int nbFacePts = 0; int initalFacePt = (int)m_triangleIndices.size(); if( m_pointIndices.size() < m_points.size() ) m_pointIndices.resize( m_points.size() ); while( true ) { bool hadSpaces = skipSpaces( stream ); char pc = stream.peek(); if( pc == '\n' || pc == '\r' ) { skipToNextLine( stream ); break; } else if( !hadSpaces ) throw Exception("space expected"); PointIndices indices; stream >> indices.m_point; if( parsingError( stream ) ) throw Exception("int value expected"); --indices.m_point; if( indices.m_point < 0 || indices.m_point > (int)m_points.size() ) throw Exception("out of range point index"); char c = 0; stream.get(c); if(c == '/') { if( !IsSeparator( stream.peek() ) && stream.peek() != '/' ) { stream >> indices.m_texCoord; if( parsingError( stream ) ) throw Exception("int value expected"); --indices.m_texCoord; if( indices.m_texCoord < 0 || indices.m_texCoord > (int)m_texCoords.size() ) throw Exception("out of range texture index"); } c = 0; stream.get(c); if(c == '/') { if( !IsSeparator( stream.peek() ) ) { stream >> indices.m_normal; if( parsingError( stream ) ) throw Exception("int value expected"); --indices.m_normal; if( indices.m_normal < 0 || indices.m_normal > (int)m_normals.size() ) throw Exception("out of range normal index"); } } else stream.unget(); } else stream.unget(); // [jeromecg 20110728] Check if we need to unshare the vertex data // Note: this would be more complex (and might have to be done later) if we were taking smoothing groups into account... int ptIndex = indices.m_point; if( !m_pointIndices[indices.m_point].isInitialized() ) { m_pointIndices[indices.m_point] = indices; } else if( m_pointIndices[indices.m_point] != indices ) { ptIndex = (int)m_pointIndices.size(); m_pointIndices.push_back( indices ); } nbFacePts++; if( nbFacePts <= 3 ) { m_triangleIndices.push_back( ptIndex ); } else { //Simple triangulation: 0 1 2 / 0 2 3 / 0 3 4... int first = m_triangleIndices[initalFacePt]; int second = m_triangleIndices.back(); m_triangleIndices.push_back( first ); m_triangleIndices.push_back( second ); m_triangleIndices.push_back( ptIndex ); } } if( nbFacePts < 3 ) throw Exception("face has less than 3 points"); } void ObjParser::ComputeMissingNormals() { //Quick check if any normal is missing size_t i; for( i = 0; i < m_triangleIndices.size(); ++i ) { if( m_pointIndices[ m_triangleIndices[i] ].m_normal == INT_MAX ) break; } if( i == m_triangleIndices.size() ) return; // [jeromecg 20110728] Make it simple for now: if any normal is missing, recompute them all. // [jeromecg 20110728] TODO: take smoothing groups into account // Compute triangle normals size_t nbTriangles = m_triangleIndices.size() / 3; std::vector< V3 > triangleNormals; triangleNormals.resize( nbTriangles ); for( i = 0; i < nbTriangles; ++i ) { V3 v1 = m_points[ m_pointIndices[ m_triangleIndices[ i*3+1 ] ].m_point ] - m_points[ m_pointIndices[ m_triangleIndices[ i*3 ] ].m_point ]; V3 v2 = m_points[ m_pointIndices[ m_triangleIndices[ i*3+2 ] ].m_point ] - m_points[ m_pointIndices[ m_triangleIndices[ i*3 ] ].m_point ]; triangleNormals[i] = v1.Cross( v2 ); triangleNormals[i].Normalize(); } // Compute point normals by simply averaging adjacent triangle normals m_normals.resize( m_points.size(), V3( 0, 0, 0 ) ); for( i = 0; i < m_triangleIndices.size(); ++i ) { int ptIndex = m_pointIndices[ m_triangleIndices[i] ].m_point; m_normals[ptIndex] = m_normals[ptIndex] + triangleNormals[i/3]; } for( i = 0; i < m_normals.size(); ++i ) { m_normals[i].Normalize(); m_pointIndices[i].m_normal = i; } } ObjParser::ObjParser( std::istream& stream ) { // [jeromecg 20110728] Right now this parser is very simple as it agglomerates all points and faces in 1 big object, // ignoring materials, groups, smoothing groups, etc. int lineCount = 0; try { while( stream.good() ) { char c = 0; stream.get(c); switch( c ) { case '\n': case '\r': case ' ': case '\t': break; case 'v': { char nextC; stream.get(nextC); switch( nextC ) { case 'p': skipToNextLine( stream );//patch: ignore break; case 'n': ParseN( stream ); break; case 't': ParseT( stream ); break; default: stream.unget(); ParseV( stream ); } break; } case 'f': ParseF( stream ); break; default: skipToNextLine( stream ); } ++lineCount; } ComputeMissingNormals(); } catch ( Exception e ) { std::stringstream sstr; sstr << "Error while parsing .obj file at line " << lineCount << ": " << e.getMsg(); m_errors.push_back( sstr.str() ); } catch ( ... ) { std::stringstream sstr; sstr << "Unexpected error while parsing .obj file at line " << lineCount; m_errors.push_back( sstr.str() ); } } void ObjParser::GetTriangleIndices(int triIndex, int& i1, int& i2, int& i3)const { i1 = m_triangleIndices[triIndex*3]; i2 = m_triangleIndices[triIndex*3+1]; i3 = m_triangleIndices[triIndex*3+2]; } V3 ObjParser::GetPoint(int ptIndex)const { int index = m_pointIndices[ptIndex].m_point; if( index == INT_MAX ) return V3( 0, 0, 0 ); else return m_points[ index ]; } V3 ObjParser::GetNormal(int ptIndex)const { int index = m_pointIndices[ptIndex].m_normal; if( index == INT_MAX ) return V3( 0, 1, 0 ); else return m_normals[ index ]; } V2 ObjParser::GetTextureCoord(int ptIndex)const { int index = m_pointIndices[ptIndex].m_texCoord; if( index == INT_MAX ) return V2( 0, 0 ); else return m_texCoords[ index ]; } <|endoftext|>
<commit_before>void RichBatch(const Int_t iNevents,const Bool_t isDebug,const char *sConfigFileName) { if(isDebug) gAlice->SetDebug(1); Info("my/RichBatch.C","%i event(s) requested, debug %i,config file %s",iNevents,isDebug,sConfigFileName); TStopwatch sw;TDatime time; AliSimulation *pSim=new AliSimulation; pSim->Run(iNevents); delete pSim; AliReconstruction *pRec=new AliReconstruction; pRec->Run(); delete pRec; AliRunLoader* runLoader = AliRunLoader::Open(); runLoader->LoadgAlice(); ((AliRICH*)runLoader->GetAliRun()->GetDetector("RICH"))->ControlPlots(); cout<<"\nInfo in <my/RichBatch.C>: Start time: ";time.Print(); cout<<"Info in <my/RichBatch.C>: Stop time: ";time.Set(); time.Print(); cout<<"Info in <my/RichBatch.C>: Time used: ";sw.Print(); gSystem->Exec("touch ZZZ______finished_______ZZZ"); } <commit_msg>new way to provide control plots<commit_after>void RichBatch(const Int_t iNevents,const Bool_t isDebug,const char *sConfigFileName) { if(isDebug) gAlice->SetDebug(1); Info("my/RichBatch.C","%i event(s) requested, debug %i,config file %s",iNevents,isDebug,sConfigFileName); TStopwatch sw;TDatime time; AliSimulation *pSim=new AliSimulation; pSim->Run(iNevents); delete pSim; AliReconstruction *pRec=new AliReconstruction; pRec->SetRunLocalReconstruction("RICH"); pRec->SetFillESD("RICH"); pRec->Run(); delete pRec; AliRunLoader* pAL = AliRunLoader::Open(); pAL->LoadgAlice(); AliRICH *pRICH=(AliRICH*)pAL->GetAliRun()->GetDetector("RICH"); if(pRICH) pRICH->ControlPlots(); cout<<"\nInfo in <my/RichBatch.C>: Start time: ";time.Print(); cout<<"Info in <my/RichBatch.C>: Stop time: ";time.Set(); time.Print(); cout<<"Info in <my/RichBatch.C>: Time used: ";sw.Print(); gSystem->Exec("touch ZZZ______finished_______ZZZ"); } <|endoftext|>
<commit_before>// implementation for refinable.h #include <algorithm> #include <cmath> #include <iostream> #include <utils/array1d.h> #include <algebra/matrix.h> #include <numerics/eigenvalues.h> #include <numerics/differences.h> namespace WaveletTL { template <class MASK> template <unsigned int DERIVATIVE> SampledMapping<1> RefinableFunction<MASK>::evaluate(const int j, const int k, const int a, const int b, const int resolution) const { Grid<1> grid(a, b, (b-a)*(1<<resolution)); Array1D<double> values((b-a)*(1<<resolution)+1); for (unsigned int i(0); i < values.size(); i++) values[i] = 0; if (DERIVATIVE == 0u) { // First we sample the generator on a fine dyadic grid, // the wavelet values can then be derived very easily const int kbegin(begin().index()), kend(rbegin().index()); if (kend - kbegin == 1) { // The corresponding generator is the Haar generator, // which we know explicitly. // (the following for loops can be sped up a bit, since we // know the grid points exactly) for (unsigned int i(0); i < grid.size(); i++) { if (k*ldexp(1.0,-j) <= grid.points()[i] && grid.points()[i] < (k+1)*ldexp(1.0,-j)) values[i] = sqrt(ldexp(1.0,j)); } } else { // First we compute the values of the original refinable function // (without the j and k parameter). In the end, we will need the // following dyadic resolution: int reshelp = std::max(0, resolution-j); Array1D<double> svalues((kend-kbegin)*(1<<reshelp)+1); for (unsigned int i(0); i < svalues.size(); i++) svalues[i] = 0; // Compute the exact values of phi on the integer numbers. // We assume that phi is continuous, so that // phi(kbegin) = phi(kend) = 0 // For the remaining point values we set up an eigenvalue problem. Matrix<double> A(kend-kbegin-1, kend-kbegin-1); for (int m(kbegin+1); m < kend; m++) for (int n(kbegin+1); n < kend; n++) A(m-kbegin-1, n-kbegin-1) = get_coefficient(2*m-n); // We assume that the largest eigenvalue of A is 1, // so a power iteration should converge to the values of // phi at the integer points. Vector<double> eigenvalues(A.row_dimension(), true); eigenvalues = 1; unsigned int iterations; PowerIteration(A, eigenvalues, 1e-6, 100, iterations); // neglects return value // normalize eigenvector to sum 1 (Strang-Fix condition 0) double sum(0); for (unsigned int m(0); m < eigenvalues.size(); m++) sum += eigenvalues[m]; eigenvalues.scale(1.0 / sum); // insert integer point values for (unsigned int m(0); m < eigenvalues.size(); m++) svalues[(1<<reshelp)*(m+1)] = eigenvalues[m]; // for the remaining points we use the refinement equation of phi for (int j1(1); j1 <= reshelp; j1++) { // we have to compute the values of phi at the odd multiples of 2^j1 for (int l((1<<j1)*kbegin+1); l < (1<<j1)*kend; l += 2) { for (int m(kbegin); m <= kend; m++) { // the following code can be sped up a bit // (by skipping the trivial entries) if ((1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin >= 0 && (1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin < (int) svalues.size()) svalues[(1<<(reshelp-j1))*l-(1<<reshelp)*kbegin] += get_coefficient(m) * svalues[(1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin]; } } } // Now we can calculate the values of \phi_{j,k} at the target resolution // from those of \phi if (j > resolution) { // This is a special case, since phi has been sampled at a resolution // which we wouldn't have needed: resolution = 0 for (unsigned int m(0); m < values.size(); m++) { int help = (1<<j)*a+m*(1<<(j-resolution))-k-kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = sqrt(ldexp(1.0,j)) * svalues[help]; } } else { for (unsigned int m(0); m < values.size(); m++) { int help = (1<<resolution)*a+m-(1<<reshelp)*k-(1<<reshelp)*kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = sqrt(ldexp(1.0,j)) * svalues[help]; } } } } else { /* To evaluate the n-th derivative of phi, we will use the following important fact: 1) If a^*(z) = a(z)*2/(1+z), then there exists an a^*-refinable function \phi^* such that \phi'(k) = \phi^*(k) - \phi^*(k-1). 2) If a^*(z) = a(z)*(1+z)/2, then there exists an a^*-refinable function \phi^* such that (\phi^*)'(k) = \phi(k+1) - \phi(k). References: [R92] P.G. Lemari\'e-Rieusset: Analyses multi-r\'esolutions non orthogonales (...), Revista Mat. Iberoamericana, 8 (1992), 221-236 */ LaurentPolynomial<double> mask(*this); LaurentPolynomial<double> factor; factor.set_coefficient(0, 0.5); factor.set_coefficient(1, 0.5); // factor(z) = (1+z)/2 this->divide(factor.power(DERIVATIVE), mask); const int kbegin(begin().index()), kend(rbegin().index()); const int kstarend(kend - (int) DERIVATIVE); // we compute the values of the corresponding refinable function phi^* // (without the j and k parameter). In the end, we will need the // following dyadic resolution: int reshelp = std::max(0, resolution-j); Array1D<double> svalues((kend-kbegin)*(1<<reshelp)+1); for (unsigned int i(0); i < svalues.size(); i++) svalues[i] = 0; // Compute the exact values of phi^* on the integer numbers. // We assume that either phi^* is the Haar function or it is // at least continuous, so that // phi^*(kbegin) = phi^*(kend) = 0 InfiniteVector<double, int> phistar; if (kstarend-kbegin-1>0) { // For the remaining point values we set up an eigenvalue problem. Matrix<double> A(kstarend-kbegin-1, kstarend-kbegin-1); for (int m1(kbegin+1); m1 < kstarend; m1++) for (int m2(kbegin+1); m2 < kstarend; m2++) A(m1-kbegin-1, m2-kbegin-1) = mask.get_coefficient(2*m1-m2); // We assume that the largest eigenvalue of A is 1, // so a power iteration should converge to the values of // phi at the integer points. Vector<double> eigenvalues(A.row_dimension(), true); eigenvalues = 1; unsigned int iterations; PowerIteration(A, eigenvalues, 1e-6, 100, iterations); // neglect return value // normalize eigenvector to sum 1 (Strang-Fix condition 0) double sum(0); for (unsigned int m(0); m < eigenvalues.size(); m++) sum += eigenvalues[m]; eigenvalues.scale(1.0 / sum); // extract integer point values for (unsigned int m(0); m < eigenvalues.size(); m++) phistar[kbegin+m+1] = eigenvalues[m]; } else // derivative is Haar function { phistar[kbegin] = 1.0; } InfiniteVector<double, int> phi(backward_difference<DERIVATIVE>(phistar)); for (InfiniteVector<double, int>::const_iterator it(phi.begin()); it != phi.end(); ++it) { svalues[(1<<reshelp)*(it.index()-kbegin)] = *it; } // for the remaining points we use the refinement equation of phi for (int j1(1); j1 <= reshelp; j1++) { // we have to compute the values of phi at the odd multiples of 2^j1 for (int l((1<<j1)*kbegin+1); l < (1<<j1)*kend; l += 2) { for (int m(kbegin); m <= kend; m++) { // the following code can be sped up a bit // (by skipping the trivial entries) if ((1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin >= 0 && (1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin < (int) svalues.size()) svalues[(1<<(reshelp-j1))*l-(1<<reshelp)*kbegin] += (1<<DERIVATIVE) * get_coefficient(m) * svalues[(1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin]; } } } // Now we can calculate the values of \phi_{j,k} at the target resolution // from those of \phi if (j > resolution) { // This is a special case, since phi has been sampled at a resolution // which we wouldn't have needed: resolution = 0 for (unsigned int m(0); m < values.size(); m++) { int help = (1<<j)*a+m*(1<<(j-resolution))-k-kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = ldexp(1.0, j*DERIVATIVE) * sqrt(ldexp(1.0,j)) * svalues[help]; } } else { for (unsigned int m(0); m < values.size(); m++) { int help = (1<<resolution)*a+m-(1<<reshelp)*k-(1<<reshelp)*kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = ldexp(1.0, j*DERIVATIVE) * sqrt(ldexp(1.0,j)) * svalues[help]; } } } return SampledMapping<1>(grid, values); } } <commit_msg>fixed gcc 3.4 incompatibility<commit_after>// implementation for refinable.h #include <algorithm> #include <cmath> #include <iostream> #include <utils/array1d.h> #include <algebra/matrix.h> #include <numerics/eigenvalues.h> #include <numerics/differences.h> namespace WaveletTL { template <class MASK> template <unsigned int DERIVATIVE> SampledMapping<1> RefinableFunction<MASK>::evaluate(const int j, const int k, const int a, const int b, const int resolution) const { Grid<1> grid(a, b, (b-a)*(1<<resolution)); Array1D<double> values((b-a)*(1<<resolution)+1); for (unsigned int i(0); i < values.size(); i++) values[i] = 0; if (DERIVATIVE == 0u) { // First we sample the generator on a fine dyadic grid, // the wavelet values can then be derived very easily const int kbegin(LaurentPolynomial<double>::begin().index()), kend(LaurentPolynomial<double>::rbegin().index()); if (kend - kbegin == 1) { // The corresponding generator is the Haar generator, // which we know explicitly. // (the following for loops can be sped up a bit, since we // know the grid points exactly) for (unsigned int i(0); i < grid.size(); i++) { if (k*ldexp(1.0,-j) <= grid.points()[i] && grid.points()[i] < (k+1)*ldexp(1.0,-j)) values[i] = sqrt(ldexp(1.0,j)); } } else { // First we compute the values of the original refinable function // (without the j and k parameter). In the end, we will need the // following dyadic resolution: int reshelp = std::max(0, resolution-j); Array1D<double> svalues((kend-kbegin)*(1<<reshelp)+1); for (unsigned int i(0); i < svalues.size(); i++) svalues[i] = 0; // Compute the exact values of phi on the integer numbers. // We assume that phi is continuous, so that // phi(kbegin) = phi(kend) = 0 // For the remaining point values we set up an eigenvalue problem. Matrix<double> A(kend-kbegin-1, kend-kbegin-1); for (int m(kbegin+1); m < kend; m++) for (int n(kbegin+1); n < kend; n++) A(m-kbegin-1, n-kbegin-1) = LaurentPolynomial<double>::get_coefficient(2*m-n); // We assume that the largest eigenvalue of A is 1, // so a power iteration should converge to the values of // phi at the integer points. Vector<double> eigenvalues(A.row_dimension(), true); eigenvalues = 1; unsigned int iterations; PowerIteration(A, eigenvalues, 1e-6, 100, iterations); // neglects return value // normalize eigenvector to sum 1 (Strang-Fix condition 0) double sum(0); for (unsigned int m(0); m < eigenvalues.size(); m++) sum += eigenvalues[m]; eigenvalues.scale(1.0 / sum); // insert integer point values for (unsigned int m(0); m < eigenvalues.size(); m++) svalues[(1<<reshelp)*(m+1)] = eigenvalues[m]; // for the remaining points we use the refinement equation of phi for (int j1(1); j1 <= reshelp; j1++) { // we have to compute the values of phi at the odd multiples of 2^j1 for (int l((1<<j1)*kbegin+1); l < (1<<j1)*kend; l += 2) { for (int m(kbegin); m <= kend; m++) { // the following code can be sped up a bit // (by skipping the trivial entries) if ((1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin >= 0 && (1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin < (int) svalues.size()) svalues[(1<<(reshelp-j1))*l-(1<<reshelp)*kbegin] += LaurentPolynomial<double>::get_coefficient(m) * svalues[(1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin]; } } } // Now we can calculate the values of \phi_{j,k} at the target resolution // from those of \phi if (j > resolution) { // This is a special case, since phi has been sampled at a resolution // which we wouldn't have needed: resolution = 0 for (unsigned int m(0); m < values.size(); m++) { int help = (1<<j)*a+m*(1<<(j-resolution))-k-kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = sqrt(ldexp(1.0,j)) * svalues[help]; } } else { for (unsigned int m(0); m < values.size(); m++) { int help = (1<<resolution)*a+m-(1<<reshelp)*k-(1<<reshelp)*kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = sqrt(ldexp(1.0,j)) * svalues[help]; } } } } else { /* To evaluate the n-th derivative of phi, we will use the following important fact: 1) If a^*(z) = a(z)*2/(1+z), then there exists an a^*-refinable function \phi^* such that \phi'(k) = \phi^*(k) - \phi^*(k-1). 2) If a^*(z) = a(z)*(1+z)/2, then there exists an a^*-refinable function \phi^* such that (\phi^*)'(k) = \phi(k+1) - \phi(k). References: [R92] P.G. Lemari\'e-Rieusset: Analyses multi-r\'esolutions non orthogonales (...), Revista Mat. Iberoamericana, 8 (1992), 221-236 */ LaurentPolynomial<double> mask(*this); LaurentPolynomial<double> factor; factor.set_coefficient(0, 0.5); factor.set_coefficient(1, 0.5); // factor(z) = (1+z)/2 this->divide(factor.power(DERIVATIVE), mask); const int kbegin(LaurentPolynomial<double>::begin().index()), kend(LaurentPolynomial<double>::rbegin().index()); const int kstarend(kend - (int) DERIVATIVE); // we compute the values of the corresponding refinable function phi^* // (without the j and k parameter). In the end, we will need the // following dyadic resolution: int reshelp = std::max(0, resolution-j); Array1D<double> svalues((kend-kbegin)*(1<<reshelp)+1); for (unsigned int i(0); i < svalues.size(); i++) svalues[i] = 0; // Compute the exact values of phi^* on the integer numbers. // We assume that either phi^* is the Haar function or it is // at least continuous, so that // phi^*(kbegin) = phi^*(kend) = 0 InfiniteVector<double, int> phistar; if (kstarend-kbegin-1>0) { // For the remaining point values we set up an eigenvalue problem. Matrix<double> A(kstarend-kbegin-1, kstarend-kbegin-1); for (int m1(kbegin+1); m1 < kstarend; m1++) for (int m2(kbegin+1); m2 < kstarend; m2++) A(m1-kbegin-1, m2-kbegin-1) = mask.get_coefficient(2*m1-m2); // We assume that the largest eigenvalue of A is 1, // so a power iteration should converge to the values of // phi at the integer points. Vector<double> eigenvalues(A.row_dimension(), true); eigenvalues = 1; unsigned int iterations; PowerIteration(A, eigenvalues, 1e-6, 100, iterations); // neglect return value // normalize eigenvector to sum 1 (Strang-Fix condition 0) double sum(0); for (unsigned int m(0); m < eigenvalues.size(); m++) sum += eigenvalues[m]; eigenvalues.scale(1.0 / sum); // extract integer point values for (unsigned int m(0); m < eigenvalues.size(); m++) phistar[kbegin+m+1] = eigenvalues[m]; } else // derivative is Haar function { phistar[kbegin] = 1.0; } InfiniteVector<double, int> phi(backward_difference<DERIVATIVE>(phistar)); for (InfiniteVector<double, int>::const_iterator it(phi.begin()); it != phi.end(); ++it) { svalues[(1<<reshelp)*(it.index()-kbegin)] = *it; } // for the remaining points we use the refinement equation of phi for (int j1(1); j1 <= reshelp; j1++) { // we have to compute the values of phi at the odd multiples of 2^j1 for (int l((1<<j1)*kbegin+1); l < (1<<j1)*kend; l += 2) { for (int m(kbegin); m <= kend; m++) { // the following code can be sped up a bit // (by skipping the trivial entries) if ((1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin >= 0 && (1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin < (int) svalues.size()) svalues[(1<<(reshelp-j1))*l-(1<<reshelp)*kbegin] += (1<<DERIVATIVE) * LaurentPolynomial<double>::get_coefficient(m) * svalues[(1<<(reshelp-(j1-1)))*(l-(1<<(j1-1))*m)-(1<<reshelp)*kbegin]; } } } // Now we can calculate the values of \phi_{j,k} at the target resolution // from those of \phi if (j > resolution) { // This is a special case, since phi has been sampled at a resolution // which we wouldn't have needed: resolution = 0 for (unsigned int m(0); m < values.size(); m++) { int help = (1<<j)*a+m*(1<<(j-resolution))-k-kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = ldexp(1.0, j*DERIVATIVE) * sqrt(ldexp(1.0,j)) * svalues[help]; } } else { for (unsigned int m(0); m < values.size(); m++) { int help = (1<<resolution)*a+m-(1<<reshelp)*k-(1<<reshelp)*kbegin; if (help >= 0 && help < (int) svalues.size()) values[m] = ldexp(1.0, j*DERIVATIVE) * sqrt(ldexp(1.0,j)) * svalues[help]; } } } return SampledMapping<1>(grid, values); } } <|endoftext|>
<commit_before>// regimes.cpp : examples of working with posit regimes // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include "common.hpp" #include <posit> // test reporting helper int ReportTestResult(int nrOfFailedTests, std::string description, std::string test_operation) { if (nrOfFailedTests > 0) { std::cout << description << " " << test_operation << " FAIL " << nrOfFailedTests << " failed test cases" << std::endl; } else { std::cout << description << " " << test_operation << " PASS" << std::endl; } return nrOfFailedTests; } /* Regime range example for a posit<6,es> regime scale 00000 ~ associated with either 0 or NaR (Not a Real) 00001 -4 0001- -3 001-- -2 01--- -1 10--- 0 110-- 1 1110- 2 11110 3 11111 4 */ template<size_t nbits, size_t es> int ValidateRegimeOperations(std::string tag, bool bReportIndividualTestCases) { const int NR_TEST_CASES = nbits; int nrOfFailedTestCases = 0; sw::unum::regime<nbits, es> r; for (int k = -NR_TEST_CASES; k < NR_TEST_CASES + 1; k++) { int reference = r.regime_size(k); size_t nrRegimeBits = r.assign_regime_pattern(k); if (nrRegimeBits != reference) { nrOfFailedTestCases++; if (bReportIndividualTestCases) std::cout << "FAIL: k = " << std::setw(3) << k << " regime is " << r << " bits " << nrRegimeBits << " reference " << reference << std::endl; } else { //if (bReportIndividualTestCases) std::cout << "PASS: k = " << std::setw(3) << k << " regime is " << r << " bits " << nrRegimeBits << " reference " << reference << std::endl; } } return nrOfFailedTestCases; } template<size_t nbits, size_t es> int ValidateInwardProjection(std::string tag, bool bReportIndividualTestCases) { int nrOfFailedTests = 0; unsigned useed_scale = unsigned(1) << es; sw::unum::posit<nbits, es> p; // k represents the regime encoding int size = int(nbits); for (int k = -size + 1; k <= size - 1; k++) { int scale = k*useed_scale; bool inward = p.check_inward_projection_range(k*useed_scale); bool reference = k < 0 ? k == -size + 1 : k == size - 1; if (inward != reference) { nrOfFailedTests++; std::cout << "FAIL : k = " << setw(3) << k << " scale = " << std::setw(3) << scale << " inward projection range " << inward << " reference " << reference << std::endl; } std::cout << "k = " << setw(3) << k << " scale = " << std::setw(3) << scale << " inward projection range " << inward << std::endl; } return nrOfFailedTests; } template<size_t nbits, size_t es> int ValidateRegimeScales(std::string tag, bool bReportIndividualTestCases) { int nrOfFailedTests = 0; int useed_scale = int(1) << es; // int because we are doing int math with it sw::unum::regime<nbits, es> r1; sw::unum::posit<nbits, es> p; // for check_inward_projection_range // scale represents the binary scale of a value to test int size = int(nbits); for (int k = (-size + 1); k <= (size - 1); k++) { int scale = k*useed_scale; r1.assign_regime_pattern(k); if (r1.scale() != scale) { if (p.check_inward_projection_range(scale)) { if (r1.scale() == (k - 1)*useed_scale || r1.scale() == (k + 1)*useed_scale) { continue; } } nrOfFailedTests++; std::cout << "k = " << std::setw(3) << k << " scale = " << std::setw(3) << scale << " calc k " << std::setw(3) << r1.regime_k() << " bits " << r1 << ":scale=" << r1.scale() << " clamp " << p.check_inward_projection_range(scale) << std::endl; } } return nrOfFailedTests; } #define MANUAL_TESTING 0 #define STRESS_TESTING 0 int main(int argc, char** argv) try { using namespace std; bool bReportIndividualTestCases = false; int nrOfFailedTestCases = 0; std::string tag = "Regime conversion failed"; #if MANUAL_TESTING // generate individual testcases to hand trace/debug #if 0 regime<10, 2> r; for (int k = -7; k < 9; k++) { int regime_size = r.assign_regime_pattern(k); cout << "k = " << setw(3) << k << " regime is " << r << " regime size is " << regime_size << " bits" << endl; } #endif nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "regimes"); return 0; nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "regimes"); #else cout << "Regime tests" << endl; // TEST REGIME DECODE nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<3, 0>(tag, bReportIndividualTestCases), "regime<3,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<4, 0>(tag, bReportIndividualTestCases), "regime<4,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<4, 1>(tag, bReportIndividualTestCases), "regime<4,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<5, 0>(tag, bReportIndividualTestCases), "regime<5,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<5, 1>(tag, bReportIndividualTestCases), "regime<5,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<5, 2>(tag, bReportIndividualTestCases), "regime<5,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 0>(tag, bReportIndividualTestCases), "regime<6,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 1>(tag, bReportIndividualTestCases), "regime<6,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 2>(tag, bReportIndividualTestCases), "regime<6,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 3>(tag, bReportIndividualTestCases), "regime<6,3>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 0>(tag, bReportIndividualTestCases), "regime<7,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 1>(tag, bReportIndividualTestCases), "regime<7,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 2>(tag, bReportIndividualTestCases), "regime<7,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 3>(tag, bReportIndividualTestCases), "regime<7,3>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 0>(tag, bReportIndividualTestCases), "regime<8,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 1>(tag, bReportIndividualTestCases), "regime<8,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 2>(tag, bReportIndividualTestCases), "regime<8,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 3>(tag, bReportIndividualTestCases), "regime<8,3>", "regime"); // TEST REGIME CONVERSION // DIFFERENT WAY TO TEST REGIME CONSTRUCTION nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 0>(tag, bReportIndividualTestCases), "posit<16,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 1>(tag, bReportIndividualTestCases), "posit<16,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 2>(tag, bReportIndividualTestCases), "posit<16,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 3>(tag, bReportIndividualTestCases), "posit<16,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 4>(tag, bReportIndividualTestCases), "posit<16,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 5>(tag, bReportIndividualTestCases), "posit<16,5>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 0>(tag, bReportIndividualTestCases), "posit<32,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 1>(tag, bReportIndividualTestCases), "posit<32,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 2>(tag, bReportIndividualTestCases), "posit<32,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 3>(tag, bReportIndividualTestCases), "posit<32,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 4>(tag, bReportIndividualTestCases), "posit<32,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 5>(tag, bReportIndividualTestCases), "posit<32,5>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 0>(tag, bReportIndividualTestCases), "posit<64,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 1>(tag, bReportIndividualTestCases), "posit<64,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 2>(tag, bReportIndividualTestCases), "posit<64,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 3>(tag, bReportIndividualTestCases), "posit<64,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 4>(tag, bReportIndividualTestCases), "posit<64,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 5>(tag, bReportIndividualTestCases), "posit<64,5>", "scales"); #endif return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } <commit_msg>Compilation fix<commit_after>// regimes.cpp : examples of working with posit regimes // // Copyright (C) 2017-2018 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include "common.hpp" #include <posit> // test reporting helper int ReportTestResult(int nrOfFailedTests, std::string description, std::string test_operation) { if (nrOfFailedTests > 0) { std::cout << description << " " << test_operation << " FAIL " << nrOfFailedTests << " failed test cases" << std::endl; } else { std::cout << description << " " << test_operation << " PASS" << std::endl; } return nrOfFailedTests; } /* Regime range example for a posit<6,es> regime scale 00000 ~ associated with either 0 or NaR (Not a Real) 00001 -4 0001- -3 001-- -2 01--- -1 10--- 0 110-- 1 1110- 2 11110 3 11111 4 */ template<size_t nbits, size_t es> int ValidateRegimeOperations(std::string tag, bool bReportIndividualTestCases) { const int NR_TEST_CASES = nbits; int nrOfFailedTestCases = 0; sw::unum::regime<nbits, es> r; for (int k = -NR_TEST_CASES; k < NR_TEST_CASES + 1; k++) { int reference = r.regime_size(k); size_t nrRegimeBits = r.assign_regime_pattern(k); if (nrRegimeBits != reference) { nrOfFailedTestCases++; if (bReportIndividualTestCases) std::cout << "FAIL: k = " << std::setw(3) << k << " regime is " << r << " bits " << nrRegimeBits << " reference " << reference << std::endl; } else { //if (bReportIndividualTestCases) std::cout << "PASS: k = " << std::setw(3) << k << " regime is " << r << " bits " << nrRegimeBits << " reference " << reference << std::endl; } } return nrOfFailedTestCases; } template<size_t nbits, size_t es> int ValidateInwardProjection(std::string tag, bool bReportIndividualTestCases) { int nrOfFailedTests = 0; unsigned useed_scale = unsigned(1) << es; sw::unum::posit<nbits, es> p; // k represents the regime encoding int size = int(nbits); for (int k = -size + 1; k <= size - 1; k++) { int scale = k*useed_scale; bool inward = p.check_inward_projection_range(k*useed_scale); bool reference = k < 0 ? k == -size + 1 : k == size - 1; if (inward != reference) { nrOfFailedTests++; std::cout << "FAIL : k = " << std::setw(3) << k << " scale = " << std::setw(3) << scale << " inward projection range " << inward << " reference " << reference << std::endl; } std::cout << "k = " << std::setw(3) << k << " scale = " << std::setw(3) << scale << " inward projection range " << inward << std::endl; } return nrOfFailedTests; } template<size_t nbits, size_t es> int ValidateRegimeScales(std::string tag, bool bReportIndividualTestCases) { int nrOfFailedTests = 0; int useed_scale = int(1) << es; // int because we are doing int math with it sw::unum::regime<nbits, es> r1; sw::unum::posit<nbits, es> p; // for check_inward_projection_range // scale represents the binary scale of a value to test int size = int(nbits); for (int k = (-size + 1); k <= (size - 1); k++) { int scale = k*useed_scale; r1.assign_regime_pattern(k); if (r1.scale() != scale) { if (p.check_inward_projection_range(scale)) { if (r1.scale() == (k - 1)*useed_scale || r1.scale() == (k + 1)*useed_scale) { continue; } } nrOfFailedTests++; std::cout << "k = " << std::setw(3) << k << " scale = " << std::setw(3) << scale << " calc k " << std::setw(3) << r1.regime_k() << " bits " << r1 << ":scale=" << r1.scale() << " clamp " << p.check_inward_projection_range(scale) << std::endl; } } return nrOfFailedTests; } #define MANUAL_TESTING 0 #define STRESS_TESTING 0 int main(int argc, char** argv) try { using namespace std; bool bReportIndividualTestCases = false; int nrOfFailedTestCases = 0; std::string tag = "Regime conversion failed"; #if MANUAL_TESTING // generate individual testcases to hand trace/debug #if 0 regime<10, 2> r; for (int k = -7; k < 9; k++) { int regime_size = r.assign_regime_pattern(k); cout << "k = " << setw(3) << k << " regime is " << r << " regime size is " << regime_size << " bits" << endl; } #endif nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "regimes"); return 0; nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "regimes"); nrOfFailedTestCases += ReportTestResult(ValidateInwardProjection<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "regimes"); #else cout << "Regime tests" << endl; // TEST REGIME DECODE nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<3, 0>(tag, bReportIndividualTestCases), "regime<3,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<4, 0>(tag, bReportIndividualTestCases), "regime<4,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<4, 1>(tag, bReportIndividualTestCases), "regime<4,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<5, 0>(tag, bReportIndividualTestCases), "regime<5,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<5, 1>(tag, bReportIndividualTestCases), "regime<5,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<5, 2>(tag, bReportIndividualTestCases), "regime<5,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 0>(tag, bReportIndividualTestCases), "regime<6,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 1>(tag, bReportIndividualTestCases), "regime<6,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 2>(tag, bReportIndividualTestCases), "regime<6,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<6, 3>(tag, bReportIndividualTestCases), "regime<6,3>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 0>(tag, bReportIndividualTestCases), "regime<7,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 1>(tag, bReportIndividualTestCases), "regime<7,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 2>(tag, bReportIndividualTestCases), "regime<7,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<7, 3>(tag, bReportIndividualTestCases), "regime<7,3>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 0>(tag, bReportIndividualTestCases), "regime<8,0>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 1>(tag, bReportIndividualTestCases), "regime<8,1>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 2>(tag, bReportIndividualTestCases), "regime<8,2>", "regime"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeOperations<8, 3>(tag, bReportIndividualTestCases), "regime<8,3>", "regime"); // TEST REGIME CONVERSION // DIFFERENT WAY TO TEST REGIME CONSTRUCTION nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 0>(tag, bReportIndividualTestCases), "posit<16,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 1>(tag, bReportIndividualTestCases), "posit<16,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 2>(tag, bReportIndividualTestCases), "posit<16,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 3>(tag, bReportIndividualTestCases), "posit<16,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 4>(tag, bReportIndividualTestCases), "posit<16,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<16, 5>(tag, bReportIndividualTestCases), "posit<16,5>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 0>(tag, bReportIndividualTestCases), "posit<32,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 1>(tag, bReportIndividualTestCases), "posit<32,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 2>(tag, bReportIndividualTestCases), "posit<32,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 3>(tag, bReportIndividualTestCases), "posit<32,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 4>(tag, bReportIndividualTestCases), "posit<32,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<32, 5>(tag, bReportIndividualTestCases), "posit<32,5>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 0>(tag, bReportIndividualTestCases), "posit<64,0>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 1>(tag, bReportIndividualTestCases), "posit<64,1>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 2>(tag, bReportIndividualTestCases), "posit<64,2>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 3>(tag, bReportIndividualTestCases), "posit<64,3>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 4>(tag, bReportIndividualTestCases), "posit<64,4>", "scales"); nrOfFailedTestCases += ReportTestResult(ValidateRegimeScales<64, 5>(tag, bReportIndividualTestCases), "posit<64,5>", "scales"); #endif return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <stdint.h> #include <stdio.h> #include "image.hpp" #include "state_writer.hpp" #include "com_ptr.hpp" #include "d3d9state.hpp" #include "d3dstate.hpp" namespace d3dstate { static image::Image * getSurfaceImage(IDirect3DDevice9 *pDevice, IDirect3DSurface9 *pSurface) { image::Image *image = NULL; HRESULT hr; if (!pSurface) { return NULL; } D3DSURFACE_DESC Desc; hr = pSurface->GetDesc(&Desc); assert(SUCCEEDED(hr)); D3DLOCKED_RECT LockedRect; hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY); if (FAILED(hr)) { return NULL; } image = ConvertImage(Desc.Format, LockedRect.pBits, LockedRect.Pitch, Desc.Width, Desc.Height); pSurface->UnlockRect(); return image; } static image::Image * getRenderTargetImage(IDirect3DDevice9 *pDevice, IDirect3DSurface9 *pRenderTarget) { HRESULT hr; if (!pRenderTarget) { return NULL; } D3DSURFACE_DESC Desc; hr = pRenderTarget->GetDesc(&Desc); assert(SUCCEEDED(hr)); com_ptr<IDirect3DSurface9> pStagingSurface; hr = pDevice->CreateOffscreenPlainSurface(Desc.Width, Desc.Height, Desc.Format, D3DPOOL_SYSTEMMEM, &pStagingSurface, NULL); if (FAILED(hr)) { return NULL; } hr = pDevice->GetRenderTargetData(pRenderTarget, pStagingSurface); if (FAILED(hr)) { std::cerr << "warning: GetRenderTargetData failed\n"; return NULL; } return getSurfaceImage(pDevice, pStagingSurface); } image::Image * getRenderTargetImage(IDirect3DDevice9 *pDevice) { HRESULT hr; com_ptr<IDirect3DSurface9> pRenderTarget; hr = pDevice->GetRenderTarget(0, &pRenderTarget); if (FAILED(hr)) { return NULL; } assert(pRenderTarget); return getRenderTargetImage(pDevice, pRenderTarget); } image::Image * getRenderTargetImage(IDirect3DSwapChain9 *pSwapChain) { HRESULT hr; com_ptr<IDirect3DDevice9> pDevice; hr = pSwapChain->GetDevice(&pDevice); if (FAILED(hr)) { return NULL; } // TODO: Use GetFrontBufferData instead?? com_ptr<IDirect3DSurface9> pBackBuffer; hr = pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer); if (FAILED(hr)) { return NULL; } assert(pBackBuffer); return getRenderTargetImage(pDevice, pBackBuffer); } static image::Image * getTextureImage(IDirect3DDevice9 *pDevice, IDirect3DBaseTexture9 *pTexture, D3DCUBEMAP_FACES FaceType, UINT Level) { HRESULT hr; if (!pTexture) { return NULL; } com_ptr<IDirect3DSurface9> pSurface; D3DRESOURCETYPE Type = pTexture->GetType(); switch (Type) { case D3DRTYPE_TEXTURE: assert(FaceType == D3DCUBEMAP_FACE_POSITIVE_X); hr = reinterpret_cast<IDirect3DTexture9 *>(pTexture)->GetSurfaceLevel(Level, &pSurface); break; case D3DRTYPE_CUBETEXTURE: hr = reinterpret_cast<IDirect3DCubeTexture9 *>(pTexture)->GetCubeMapSurface(FaceType, Level, &pSurface); break; default: /* TODO: support volume textures */ return NULL; } if (FAILED(hr) || !pSurface) { return NULL; } D3DSURFACE_DESC Desc; hr = pSurface->GetDesc(&Desc); assert(SUCCEEDED(hr)); if (Desc.Pool != D3DPOOL_DEFAULT || Desc.Usage & D3DUSAGE_DYNAMIC) { // Lockable texture return getSurfaceImage(pDevice, pSurface); } else if (Desc.Usage & D3DUSAGE_RENDERTARGET) { // Rendertarget texture return getRenderTargetImage(pDevice, pSurface); } else { // D3D constraints are such there is not much else that can be done. return NULL; } } void dumpTextures(StateWriter &writer, IDirect3DDevice9 *pDevice) { HRESULT hr; writer.beginMember("textures"); writer.beginObject(); for (DWORD Stage = 0; Stage < 16; ++Stage) { com_ptr<IDirect3DBaseTexture9> pTexture; hr = pDevice->GetTexture(Stage, &pTexture); if (FAILED(hr)) { continue; } if (!pTexture) { continue; } D3DRESOURCETYPE Type = pTexture->GetType(); DWORD NumFaces = Type == D3DRTYPE_CUBETEXTURE ? 6 : 1; DWORD NumLevels = pTexture->GetLevelCount(); for (DWORD Face = 0; Face < NumFaces; ++Face) { for (DWORD Level = 0; Level < NumLevels; ++Level) { image::Image *image; image = getTextureImage(pDevice, pTexture, static_cast<D3DCUBEMAP_FACES>(Face), Level); if (image) { char label[128]; if (Type == D3DRTYPE_CUBETEXTURE) { _snprintf(label, sizeof label, "PS_RESOURCE_%lu_FACE_%lu_LEVEL_%lu", Stage, Face, Level); } else { _snprintf(label, sizeof label, "PS_RESOURCE_%lu_LEVEL_%lu", Stage, Level); } writer.beginMember(label); writer.writeImage(image); writer.endMember(); // PS_RESOURCE_* delete image; } } } } writer.endObject(); writer.endMember(); // textures } void dumpFramebuffer(StateWriter &writer, IDirect3DDevice9 *pDevice) { HRESULT hr; writer.beginMember("framebuffer"); writer.beginObject(); D3DCAPS9 Caps; pDevice->GetDeviceCaps(&Caps); for (UINT i = 0; i < Caps.NumSimultaneousRTs; ++i) { com_ptr<IDirect3DSurface9> pRenderTarget; hr = pDevice->GetRenderTarget(i, &pRenderTarget); if (FAILED(hr)) { continue; } if (!pRenderTarget) { continue; } image::Image *image; image = getRenderTargetImage(pDevice, pRenderTarget); if (image) { char label[64]; _snprintf(label, sizeof label, "RENDER_TARGET_%u", i); writer.beginMember(label); writer.writeImage(image); writer.endMember(); // RENDER_TARGET_* delete image; } } com_ptr<IDirect3DSurface9> pDepthStencil; hr = pDevice->GetDepthStencilSurface(&pDepthStencil); if (SUCCEEDED(hr) && pDepthStencil) { image::Image *image; image = getSurfaceImage(pDevice, pDepthStencil); if (image) { writer.beginMember("DEPTH_STENCIL"); writer.writeImage(image); writer.endMember(); // RENDER_TARGET_* delete image; } } writer.endObject(); writer.endMember(); // framebuffer } } /* namespace d3dstate */ <commit_msg>d3dretrace: Dump D3DFORMAT in D3D9 traces<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <stdint.h> #include <stdio.h> #include "image.hpp" #include "state_writer.hpp" #include "com_ptr.hpp" #include "d3d9state.hpp" #include "d3dstate.hpp" namespace d3dstate { static image::Image * getSurfaceImage(IDirect3DDevice9 *pDevice, IDirect3DSurface9 *pSurface, struct StateWriter::ImageDesc &imageDesc) { image::Image *image = NULL; HRESULT hr; if (!pSurface) { return NULL; } D3DSURFACE_DESC Desc; hr = pSurface->GetDesc(&Desc); assert(SUCCEEDED(hr)); D3DLOCKED_RECT LockedRect; hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY); if (FAILED(hr)) { return NULL; } image = ConvertImage(Desc.Format, LockedRect.pBits, LockedRect.Pitch, Desc.Width, Desc.Height); pSurface->UnlockRect(); imageDesc.format = formatToString(Desc.Format); return image; } static image::Image * getRenderTargetImage(IDirect3DDevice9 *pDevice, IDirect3DSurface9 *pRenderTarget, struct StateWriter::ImageDesc &imageDesc) { HRESULT hr; if (!pRenderTarget) { return NULL; } D3DSURFACE_DESC Desc; hr = pRenderTarget->GetDesc(&Desc); assert(SUCCEEDED(hr)); com_ptr<IDirect3DSurface9> pStagingSurface; hr = pDevice->CreateOffscreenPlainSurface(Desc.Width, Desc.Height, Desc.Format, D3DPOOL_SYSTEMMEM, &pStagingSurface, NULL); if (FAILED(hr)) { return NULL; } hr = pDevice->GetRenderTargetData(pRenderTarget, pStagingSurface); if (FAILED(hr)) { std::cerr << "warning: GetRenderTargetData failed\n"; return NULL; } return getSurfaceImage(pDevice, pStagingSurface, imageDesc); } image::Image * getRenderTargetImage(IDirect3DDevice9 *pDevice) { HRESULT hr; struct StateWriter::ImageDesc imageDesc; com_ptr<IDirect3DSurface9> pRenderTarget; hr = pDevice->GetRenderTarget(0, &pRenderTarget); if (FAILED(hr)) { return NULL; } assert(pRenderTarget); return getRenderTargetImage(pDevice, pRenderTarget, imageDesc); } image::Image * getRenderTargetImage(IDirect3DSwapChain9 *pSwapChain) { HRESULT hr; struct StateWriter::ImageDesc imageDesc; com_ptr<IDirect3DDevice9> pDevice; hr = pSwapChain->GetDevice(&pDevice); if (FAILED(hr)) { return NULL; } // TODO: Use GetFrontBufferData instead?? com_ptr<IDirect3DSurface9> pBackBuffer; hr = pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer); if (FAILED(hr)) { return NULL; } assert(pBackBuffer); return getRenderTargetImage(pDevice, pBackBuffer, imageDesc); } static image::Image * getTextureImage(IDirect3DDevice9 *pDevice, IDirect3DBaseTexture9 *pTexture, D3DCUBEMAP_FACES FaceType, UINT Level, struct StateWriter::ImageDesc &imageDesc) { HRESULT hr; if (!pTexture) { return NULL; } com_ptr<IDirect3DSurface9> pSurface; D3DRESOURCETYPE Type = pTexture->GetType(); switch (Type) { case D3DRTYPE_TEXTURE: assert(FaceType == D3DCUBEMAP_FACE_POSITIVE_X); hr = reinterpret_cast<IDirect3DTexture9 *>(pTexture)->GetSurfaceLevel(Level, &pSurface); break; case D3DRTYPE_CUBETEXTURE: hr = reinterpret_cast<IDirect3DCubeTexture9 *>(pTexture)->GetCubeMapSurface(FaceType, Level, &pSurface); break; default: /* TODO: support volume textures */ return NULL; } if (FAILED(hr) || !pSurface) { return NULL; } D3DSURFACE_DESC Desc; hr = pSurface->GetDesc(&Desc); assert(SUCCEEDED(hr)); if (Desc.Pool != D3DPOOL_DEFAULT || Desc.Usage & D3DUSAGE_DYNAMIC) { // Lockable texture return getSurfaceImage(pDevice, pSurface, imageDesc); } else if (Desc.Usage & D3DUSAGE_RENDERTARGET) { // Rendertarget texture return getRenderTargetImage(pDevice, pSurface, imageDesc); } else { // D3D constraints are such there is not much else that can be done. return NULL; } } void dumpTextures(StateWriter &writer, IDirect3DDevice9 *pDevice) { HRESULT hr; writer.beginMember("textures"); writer.beginObject(); for (DWORD Stage = 0; Stage < 16; ++Stage) { com_ptr<IDirect3DBaseTexture9> pTexture; hr = pDevice->GetTexture(Stage, &pTexture); if (FAILED(hr)) { continue; } if (!pTexture) { continue; } D3DRESOURCETYPE Type = pTexture->GetType(); DWORD NumFaces = Type == D3DRTYPE_CUBETEXTURE ? 6 : 1; DWORD NumLevels = pTexture->GetLevelCount(); for (DWORD Face = 0; Face < NumFaces; ++Face) { for (DWORD Level = 0; Level < NumLevels; ++Level) { image::Image *image; struct StateWriter::ImageDesc imageDesc; image = getTextureImage(pDevice, pTexture, static_cast<D3DCUBEMAP_FACES>(Face), Level, imageDesc); if (image) { char label[128]; if (Type == D3DRTYPE_CUBETEXTURE) { _snprintf(label, sizeof label, "PS_RESOURCE_%lu_FACE_%lu_LEVEL_%lu", Stage, Face, Level); } else { _snprintf(label, sizeof label, "PS_RESOURCE_%lu_LEVEL_%lu", Stage, Level); } writer.beginMember(label); writer.writeImage(image, imageDesc); writer.endMember(); // PS_RESOURCE_* delete image; } } } } writer.endObject(); writer.endMember(); // textures } void dumpFramebuffer(StateWriter &writer, IDirect3DDevice9 *pDevice) { HRESULT hr; writer.beginMember("framebuffer"); writer.beginObject(); D3DCAPS9 Caps; pDevice->GetDeviceCaps(&Caps); for (UINT i = 0; i < Caps.NumSimultaneousRTs; ++i) { com_ptr<IDirect3DSurface9> pRenderTarget; hr = pDevice->GetRenderTarget(i, &pRenderTarget); if (FAILED(hr)) { continue; } if (!pRenderTarget) { continue; } image::Image *image; struct StateWriter::ImageDesc imageDesc; image = getRenderTargetImage(pDevice, pRenderTarget, imageDesc); if (image) { char label[64]; _snprintf(label, sizeof label, "RENDER_TARGET_%u", i); writer.beginMember(label); writer.writeImage(image, imageDesc); writer.endMember(); // RENDER_TARGET_* delete image; } } com_ptr<IDirect3DSurface9> pDepthStencil; hr = pDevice->GetDepthStencilSurface(&pDepthStencil); if (SUCCEEDED(hr) && pDepthStencil) { image::Image *image; struct StateWriter::ImageDesc imageDesc; image = getSurfaceImage(pDevice, pDepthStencil, imageDesc); if (image) { writer.beginMember("DEPTH_STENCIL"); writer.writeImage(image, imageDesc); writer.endMember(); // DEPTH_STENCIL delete image; } } writer.endObject(); writer.endMember(); // framebuffer } } /* namespace d3dstate */ <|endoftext|>
<commit_before><commit_msg>Workaround for ObjCIvarDecl problem<commit_after><|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 "ui/gfx/color_utils.h" #include <math.h> #if defined(OS_WIN) #include <windows.h> #endif #include <algorithm> #include "base/basictypes.h" #include "base/logging.h" #include "build/build_config.h" #if defined(OS_WIN) #include "skia/ext/skia_utils_win.h" #endif #include "third_party/skia/include/core/SkBitmap.h" namespace color_utils { // Helper functions ----------------------------------------------------------- namespace { int calcHue(double temp1, double temp2, double hue) { if (hue < 0.0) ++hue; else if (hue > 1.0) --hue; double result = temp1; if (hue * 6.0 < 1.0) result = temp1 + (temp2 - temp1) * hue * 6.0; else if (hue * 2.0 < 1.0) result = temp2; else if (hue * 3.0 < 2.0) result = temp1 + (temp2 - temp1) * (2.0 / 3.0 - hue) * 6.0; // Scale the result from 0 - 255 and round off the value. return static_cast<int>(result * 255 + .5); } int GetLumaForColor(SkColor* color) { int luma = static_cast<int>((0.3 * SkColorGetR(*color)) + (0.59 * SkColorGetG(*color)) + (0.11 * SkColorGetB(*color))); return std::max(std::min(luma, 255), 0); } // Next two functions' formulas from: // http://www.w3.org/TR/WCAG20/#relativeluminancedef // http://www.w3.org/TR/WCAG20/#contrast-ratiodef double ConvertSRGB(double eight_bit_component) { const double component = eight_bit_component / 255.0; return (component <= 0.03928) ? (component / 12.92) : pow((component + 0.055) / 1.055, 2.4); } SkColor LumaInvertColor(const SkColor& color) { HSL hsl; SkColorToHSL(color, &hsl); hsl.l = 1.0 - hsl.l; return HSLToSkColor(hsl, 255); } double ContrastRatio(double foreground_luminance, double background_luminance) { // NOTE: Only pass in numbers obtained from RelativeLuminance(), since those // are guaranteed to be > 0 and thus not cause a divide-by-zero error here. return (foreground_luminance > background_luminance) ? (foreground_luminance / background_luminance) : (background_luminance / foreground_luminance); } } // namespace // ---------------------------------------------------------------------------- double RelativeLuminance(SkColor color) { return (0.2126 * ConvertSRGB(SkColorGetR(color))) + (0.7152 * ConvertSRGB(SkColorGetG(color))) + (0.0722 * ConvertSRGB(SkColorGetB(color))) + 0.05; } void SkColorToHSL(SkColor c, HSL* hsl) { double r = static_cast<double>(SkColorGetR(c)) / 255.0; double g = static_cast<double>(SkColorGetG(c)) / 255.0; double b = static_cast<double>(SkColorGetB(c)) / 255.0; double vmax = std::max(std::max(r, g), b); double vmin = std::min(std::min(r, g), b); double delta = vmax - vmin; hsl->l = (vmax + vmin) / 2; if (delta) { double dr = (((vmax - r) / 6.0) + (delta / 2.0)) / delta; double dg = (((vmax - g) / 6.0) + (delta / 2.0)) / delta; double db = (((vmax - b) / 6.0) + (delta / 2.0)) / delta; // We need to compare for the max value because comparing vmax to r, // g or b can sometimes result in values overflowing registers. if (r >= g && r >= b) hsl->h = db - dg; else if (g >= r && g >= b) hsl->h = (1.0 / 3.0) + dr - db; else // (b >= r && b >= g) hsl->h = (2.0 / 3.0) + dg - dr; if (hsl->h < 0.0) ++hsl->h; else if (hsl->h > 1.0) --hsl->h; hsl->s = delta / ((hsl->l < 0.5) ? (vmax + vmin) : (2 - vmax - vmin)); } else { hsl->h = hsl->s = 0; } } SkColor HSLToSkColor(const HSL& hsl, SkAlpha alpha) { double hue = hsl.h; double saturation = hsl.s; double lightness = hsl.l; // If there's no color, we don't care about hue and can do everything based // on brightness. if (!saturation) { uint8 light; if (lightness < 0) light = 0; else if (lightness >= 1.0) light = 255; else light = SkDoubleToFixed(lightness) >> 8; return SkColorSetARGB(alpha, light, light, light); } double temp2 = (lightness < 0.5) ? (lightness * (1.0 + saturation)) : (lightness + saturation - (lightness * saturation)); double temp1 = 2.0 * lightness - temp2; return SkColorSetARGB(alpha, calcHue(temp1, temp2, hue + 1.0 / 3.0), calcHue(temp1, temp2, hue), calcHue(temp1, temp2, hue - 1.0 / 3.0)); } SkColor HSLShift(SkColor color, const HSL& shift) { HSL hsl; int alpha = SkColorGetA(color); SkColorToHSL(color, &hsl); // Replace the hue with the tint's hue. if (shift.h >= 0) hsl.h = shift.h; // Change the saturation. if (shift.s >= 0) { if (shift.s <= 0.5) hsl.s *= shift.s * 2.0; else hsl.s += (1.0 - hsl.s) * ((shift.s - 0.5) * 2.0); } SkColor result = HSLToSkColor(hsl, alpha); if (shift.l < 0) return result; // Lightness shifts in the style of popular image editors aren't // actually represented in HSL - the L value does have some effect // on saturation. double r = static_cast<double>(SkColorGetR(result)); double g = static_cast<double>(SkColorGetG(result)); double b = static_cast<double>(SkColorGetB(result)); if (shift.l <= 0.5) { r *= (shift.l * 2.0); g *= (shift.l * 2.0); b *= (shift.l * 2.0); } else { r += (255.0 - r) * ((shift.l - 0.5) * 2.0); g += (255.0 - g) * ((shift.l - 0.5) * 2.0); b += (255.0 - b) * ((shift.l - 0.5) * 2.0); } return SkColorSetARGB(alpha, static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } bool IsColorCloseToTransparent(SkAlpha alpha) { const int kCloseToBoundary = 64; return alpha < kCloseToBoundary; } bool IsColorCloseToGrey(int r, int g, int b) { const int kAverageBoundary = 15; int average = (r + g + b) / 3; return (abs(r - average) < kAverageBoundary) && (abs(g - average) < kAverageBoundary) && (abs(b - average) < kAverageBoundary); } SkColor GetAverageColorOfFavicon(SkBitmap* favicon, SkAlpha alpha) { int r = 0, g = 0, b = 0; SkAutoLockPixels favicon_lock(*favicon); SkColor* pixels = static_cast<SkColor*>(favicon->getPixels()); // Assume ARGB_8888 format. DCHECK(favicon->getConfig() == SkBitmap::kARGB_8888_Config); SkColor* current_color = pixels; DCHECK(favicon->width() <= 16 && favicon->height() <= 16); int pixel_count = favicon->width() * favicon->height(); int color_count = 0; for (int i = 0; i < pixel_count; ++i, ++current_color) { // Disregard this color if it is close to black, close to white, or close // to transparent since any of those pixels do not contribute much to the // color makeup of this icon. int cr = SkColorGetR(*current_color); int cg = SkColorGetG(*current_color); int cb = SkColorGetB(*current_color); if (IsColorCloseToTransparent(SkColorGetA(*current_color)) || IsColorCloseToGrey(cr, cg, cb)) continue; r += cr; g += cg; b += cb; ++color_count; } return color_count ? SkColorSetARGB(alpha, r / color_count, g / color_count, b / color_count) : SkColorSetARGB(alpha, 0, 0, 0); } void BuildLumaHistogram(SkBitmap* bitmap, int histogram[256]) { SkAutoLockPixels bitmap_lock(*bitmap); // Assume ARGB_8888 format. DCHECK(bitmap->getConfig() == SkBitmap::kARGB_8888_Config); int pixel_width = bitmap->width(); int pixel_height = bitmap->height(); for (int y = 0; y < pixel_height; ++y) { SkColor* current_color = static_cast<uint32_t*>(bitmap->getAddr32(0, y)); for (int x = 0; x < pixel_width; ++x, ++current_color) histogram[GetLumaForColor(current_color)]++; } } SkColor AlphaBlend(SkColor foreground, SkColor background, SkAlpha alpha) { if (alpha == 0) return background; if (alpha == 255) return foreground; int f_alpha = SkColorGetA(foreground); int b_alpha = SkColorGetA(background); double normalizer = (f_alpha * alpha + b_alpha * (255 - alpha)) / 255.0; if (normalizer == 0.0) return SkColorSetARGB(0, 0, 0, 0); double f_weight = f_alpha * alpha / normalizer; double b_weight = b_alpha * (255 - alpha) / normalizer; double r = (SkColorGetR(foreground) * f_weight + SkColorGetR(background) * b_weight) / 255.0; double g = (SkColorGetG(foreground) * f_weight + SkColorGetG(background) * b_weight) / 255.0; double b = (SkColorGetB(foreground) * f_weight + SkColorGetB(background) * b_weight) / 255.0; return SkColorSetARGB(static_cast<int>(normalizer), static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } SkColor GetReadableColor(SkColor foreground, SkColor background) { const SkColor foreground2 = LumaInvertColor(foreground); const double background_luminance = RelativeLuminance(background); return (ContrastRatio(RelativeLuminance(foreground), background_luminance) >= ContrastRatio(RelativeLuminance(foreground2), background_luminance)) ? foreground : foreground2; } SkColor GetSysSkColor(int which) { #if defined(OS_WIN) return skia::COLORREFToSkColor(GetSysColor(which)); #else NOTIMPLEMENTED(); return SK_ColorLTGRAY; #endif } } // namespace color_utils <commit_msg>Take 2 at fixing a double overflow bug in RGB->HSL conversion.<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 "ui/gfx/color_utils.h" #include <math.h> #if defined(OS_WIN) #include <windows.h> #endif #include <algorithm> #include "base/basictypes.h" #include "base/logging.h" #include "build/build_config.h" #if defined(OS_WIN) #include "skia/ext/skia_utils_win.h" #endif #include "third_party/skia/include/core/SkBitmap.h" namespace color_utils { // Helper functions ----------------------------------------------------------- namespace { int calcHue(double temp1, double temp2, double hue) { if (hue < 0.0) ++hue; else if (hue > 1.0) --hue; double result = temp1; if (hue * 6.0 < 1.0) result = temp1 + (temp2 - temp1) * hue * 6.0; else if (hue * 2.0 < 1.0) result = temp2; else if (hue * 3.0 < 2.0) result = temp1 + (temp2 - temp1) * (2.0 / 3.0 - hue) * 6.0; // Scale the result from 0 - 255 and round off the value. return static_cast<int>(result * 255 + .5); } int GetLumaForColor(SkColor* color) { int luma = static_cast<int>((0.3 * SkColorGetR(*color)) + (0.59 * SkColorGetG(*color)) + (0.11 * SkColorGetB(*color))); return std::max(std::min(luma, 255), 0); } // Next two functions' formulas from: // http://www.w3.org/TR/WCAG20/#relativeluminancedef // http://www.w3.org/TR/WCAG20/#contrast-ratiodef double ConvertSRGB(double eight_bit_component) { const double component = eight_bit_component / 255.0; return (component <= 0.03928) ? (component / 12.92) : pow((component + 0.055) / 1.055, 2.4); } SkColor LumaInvertColor(const SkColor& color) { HSL hsl; SkColorToHSL(color, &hsl); hsl.l = 1.0 - hsl.l; return HSLToSkColor(hsl, 255); } double ContrastRatio(double foreground_luminance, double background_luminance) { // NOTE: Only pass in numbers obtained from RelativeLuminance(), since those // are guaranteed to be > 0 and thus not cause a divide-by-zero error here. return (foreground_luminance > background_luminance) ? (foreground_luminance / background_luminance) : (background_luminance / foreground_luminance); } } // namespace // ---------------------------------------------------------------------------- double RelativeLuminance(SkColor color) { return (0.2126 * ConvertSRGB(SkColorGetR(color))) + (0.7152 * ConvertSRGB(SkColorGetG(color))) + (0.0722 * ConvertSRGB(SkColorGetB(color))) + 0.05; } void SkColorToHSL(SkColor c, HSL* hsl) { double r = static_cast<double>(SkColorGetR(c)) / 255.0; double g = static_cast<double>(SkColorGetG(c)) / 255.0; double b = static_cast<double>(SkColorGetB(c)) / 255.0; double vmax = std::max(std::max(r, g), b); double vmin = std::min(std::min(r, g), b); double delta = vmax - vmin; hsl->l = (vmax + vmin) / 2; if (SkColorGetR(c) == SkColorGetG(c) && SkColorGetR(c) == SkColorGetB(c)) { hsl->h = hsl->s = 0; } else { double dr = (((vmax - r) / 6.0) + (delta / 2.0)) / delta; double dg = (((vmax - g) / 6.0) + (delta / 2.0)) / delta; double db = (((vmax - b) / 6.0) + (delta / 2.0)) / delta; // We need to compare for the max value because comparing vmax to r, // g or b can sometimes result in values overflowing registers. if (r >= g && r >= b) hsl->h = db - dg; else if (g >= r && g >= b) hsl->h = (1.0 / 3.0) + dr - db; else // (b >= r && b >= g) hsl->h = (2.0 / 3.0) + dg - dr; if (hsl->h < 0.0) ++hsl->h; else if (hsl->h > 1.0) --hsl->h; hsl->s = delta / ((hsl->l < 0.5) ? (vmax + vmin) : (2 - vmax - vmin)); } } SkColor HSLToSkColor(const HSL& hsl, SkAlpha alpha) { double hue = hsl.h; double saturation = hsl.s; double lightness = hsl.l; // If there's no color, we don't care about hue and can do everything based // on brightness. if (!saturation) { uint8 light; if (lightness < 0) light = 0; else if (lightness >= 1.0) light = 255; else light = SkDoubleToFixed(lightness) >> 8; return SkColorSetARGB(alpha, light, light, light); } double temp2 = (lightness < 0.5) ? (lightness * (1.0 + saturation)) : (lightness + saturation - (lightness * saturation)); double temp1 = 2.0 * lightness - temp2; return SkColorSetARGB(alpha, calcHue(temp1, temp2, hue + 1.0 / 3.0), calcHue(temp1, temp2, hue), calcHue(temp1, temp2, hue - 1.0 / 3.0)); } SkColor HSLShift(SkColor color, const HSL& shift) { HSL hsl; int alpha = SkColorGetA(color); SkColorToHSL(color, &hsl); // Replace the hue with the tint's hue. if (shift.h >= 0) hsl.h = shift.h; // Change the saturation. if (shift.s >= 0) { if (shift.s <= 0.5) hsl.s *= shift.s * 2.0; else hsl.s += (1.0 - hsl.s) * ((shift.s - 0.5) * 2.0); } SkColor result = HSLToSkColor(hsl, alpha); if (shift.l < 0) return result; // Lightness shifts in the style of popular image editors aren't // actually represented in HSL - the L value does have some effect // on saturation. double r = static_cast<double>(SkColorGetR(result)); double g = static_cast<double>(SkColorGetG(result)); double b = static_cast<double>(SkColorGetB(result)); if (shift.l <= 0.5) { r *= (shift.l * 2.0); g *= (shift.l * 2.0); b *= (shift.l * 2.0); } else { r += (255.0 - r) * ((shift.l - 0.5) * 2.0); g += (255.0 - g) * ((shift.l - 0.5) * 2.0); b += (255.0 - b) * ((shift.l - 0.5) * 2.0); } return SkColorSetARGB(alpha, static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } bool IsColorCloseToTransparent(SkAlpha alpha) { const int kCloseToBoundary = 64; return alpha < kCloseToBoundary; } bool IsColorCloseToGrey(int r, int g, int b) { const int kAverageBoundary = 15; int average = (r + g + b) / 3; return (abs(r - average) < kAverageBoundary) && (abs(g - average) < kAverageBoundary) && (abs(b - average) < kAverageBoundary); } SkColor GetAverageColorOfFavicon(SkBitmap* favicon, SkAlpha alpha) { int r = 0, g = 0, b = 0; SkAutoLockPixels favicon_lock(*favicon); SkColor* pixels = static_cast<SkColor*>(favicon->getPixels()); // Assume ARGB_8888 format. DCHECK(favicon->getConfig() == SkBitmap::kARGB_8888_Config); SkColor* current_color = pixels; DCHECK(favicon->width() <= 16 && favicon->height() <= 16); int pixel_count = favicon->width() * favicon->height(); int color_count = 0; for (int i = 0; i < pixel_count; ++i, ++current_color) { // Disregard this color if it is close to black, close to white, or close // to transparent since any of those pixels do not contribute much to the // color makeup of this icon. int cr = SkColorGetR(*current_color); int cg = SkColorGetG(*current_color); int cb = SkColorGetB(*current_color); if (IsColorCloseToTransparent(SkColorGetA(*current_color)) || IsColorCloseToGrey(cr, cg, cb)) continue; r += cr; g += cg; b += cb; ++color_count; } return color_count ? SkColorSetARGB(alpha, r / color_count, g / color_count, b / color_count) : SkColorSetARGB(alpha, 0, 0, 0); } void BuildLumaHistogram(SkBitmap* bitmap, int histogram[256]) { SkAutoLockPixels bitmap_lock(*bitmap); // Assume ARGB_8888 format. DCHECK(bitmap->getConfig() == SkBitmap::kARGB_8888_Config); int pixel_width = bitmap->width(); int pixel_height = bitmap->height(); for (int y = 0; y < pixel_height; ++y) { SkColor* current_color = static_cast<uint32_t*>(bitmap->getAddr32(0, y)); for (int x = 0; x < pixel_width; ++x, ++current_color) histogram[GetLumaForColor(current_color)]++; } } SkColor AlphaBlend(SkColor foreground, SkColor background, SkAlpha alpha) { if (alpha == 0) return background; if (alpha == 255) return foreground; int f_alpha = SkColorGetA(foreground); int b_alpha = SkColorGetA(background); double normalizer = (f_alpha * alpha + b_alpha * (255 - alpha)) / 255.0; if (normalizer == 0.0) return SkColorSetARGB(0, 0, 0, 0); double f_weight = f_alpha * alpha / normalizer; double b_weight = b_alpha * (255 - alpha) / normalizer; double r = (SkColorGetR(foreground) * f_weight + SkColorGetR(background) * b_weight) / 255.0; double g = (SkColorGetG(foreground) * f_weight + SkColorGetG(background) * b_weight) / 255.0; double b = (SkColorGetB(foreground) * f_weight + SkColorGetB(background) * b_weight) / 255.0; return SkColorSetARGB(static_cast<int>(normalizer), static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } SkColor GetReadableColor(SkColor foreground, SkColor background) { const SkColor foreground2 = LumaInvertColor(foreground); const double background_luminance = RelativeLuminance(background); return (ContrastRatio(RelativeLuminance(foreground), background_luminance) >= ContrastRatio(RelativeLuminance(foreground2), background_luminance)) ? foreground : foreground2; } SkColor GetSysSkColor(int which) { #if defined(OS_WIN) return skia::COLORREFToSkColor(GetSysColor(which)); #else NOTIMPLEMENTED(); return SK_ColorLTGRAY; #endif } } // namespace color_utils <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "ui/gfx/color_utils.h" #include <math.h> #if defined(OS_WIN) #include <windows.h> #endif #include <algorithm> #include "base/basictypes.h" #include "base/logging.h" #include "build/build_config.h" #if defined(OS_WIN) #include "skia/ext/skia_utils_win.h" #endif #include "third_party/skia/include/core/SkBitmap.h" namespace color_utils { // Helper functions ----------------------------------------------------------- namespace { int calcHue(double temp1, double temp2, double hue) { if (hue < 0.0) ++hue; else if (hue > 1.0) --hue; double result = temp1; if (hue * 6.0 < 1.0) result = temp1 + (temp2 - temp1) * hue * 6.0; else if (hue * 2.0 < 1.0) result = temp2; else if (hue * 3.0 < 2.0) result = temp1 + (temp2 - temp1) * (2.0 / 3.0 - hue) * 6.0; // Scale the result from 0 - 255 and round off the value. return static_cast<int>(result * 255 + .5); } // Next two functions' formulas from: // http://www.w3.org/TR/WCAG20/#relativeluminancedef // http://www.w3.org/TR/WCAG20/#contrast-ratiodef double ConvertSRGB(double eight_bit_component) { const double component = eight_bit_component / 255.0; return (component <= 0.03928) ? (component / 12.92) : pow((component + 0.055) / 1.055, 2.4); } SkColor LumaInvertColor(const SkColor& color) { HSL hsl; SkColorToHSL(color, &hsl); hsl.l = 1.0 - hsl.l; return HSLToSkColor(hsl, 255); } double ContrastRatio(double foreground_luminance, double background_luminance) { // NOTE: Only pass in numbers obtained from RelativeLuminance(), since those // are guaranteed to be > 0 and thus not cause a divide-by-zero error here. return (foreground_luminance > background_luminance) ? (foreground_luminance / background_luminance) : (background_luminance / foreground_luminance); } } // namespace // ---------------------------------------------------------------------------- unsigned char GetLuminanceForColor(SkColor color) { int luma = static_cast<int>((0.3 * SkColorGetR(color)) + (0.59 * SkColorGetG(color)) + (0.11 * SkColorGetB(color))); return std::max(std::min(luma, 255), 0); } double RelativeLuminance(SkColor color) { return (0.2126 * ConvertSRGB(SkColorGetR(color))) + (0.7152 * ConvertSRGB(SkColorGetG(color))) + (0.0722 * ConvertSRGB(SkColorGetB(color))) + 0.05; } void SkColorToHSL(SkColor c, HSL* hsl) { double r = static_cast<double>(SkColorGetR(c)) / 255.0; double g = static_cast<double>(SkColorGetG(c)) / 255.0; double b = static_cast<double>(SkColorGetB(c)) / 255.0; double vmax = std::max(std::max(r, g), b); double vmin = std::min(std::min(r, g), b); double delta = vmax - vmin; hsl->l = (vmax + vmin) / 2; if (SkColorGetR(c) == SkColorGetG(c) && SkColorGetR(c) == SkColorGetB(c)) { hsl->h = hsl->s = 0; } else { double dr = (((vmax - r) / 6.0) + (delta / 2.0)) / delta; double dg = (((vmax - g) / 6.0) + (delta / 2.0)) / delta; double db = (((vmax - b) / 6.0) + (delta / 2.0)) / delta; // We need to compare for the max value because comparing vmax to r, // g or b can sometimes result in values overflowing registers. if (r >= g && r >= b) hsl->h = db - dg; else if (g >= r && g >= b) hsl->h = (1.0 / 3.0) + dr - db; else // (b >= r && b >= g) hsl->h = (2.0 / 3.0) + dg - dr; if (hsl->h < 0.0) ++hsl->h; else if (hsl->h > 1.0) --hsl->h; hsl->s = delta / ((hsl->l < 0.5) ? (vmax + vmin) : (2 - vmax - vmin)); } } SkColor HSLToSkColor(const HSL& hsl, SkAlpha alpha) { double hue = hsl.h; double saturation = hsl.s; double lightness = hsl.l; // If there's no color, we don't care about hue and can do everything based // on brightness. if (!saturation) { uint8 light; if (lightness < 0) light = 0; else if (lightness >= 1.0) light = 255; else light = SkDoubleToFixed(lightness) >> 8; return SkColorSetARGB(alpha, light, light, light); } double temp2 = (lightness < 0.5) ? (lightness * (1.0 + saturation)) : (lightness + saturation - (lightness * saturation)); double temp1 = 2.0 * lightness - temp2; return SkColorSetARGB(alpha, calcHue(temp1, temp2, hue + 1.0 / 3.0), calcHue(temp1, temp2, hue), calcHue(temp1, temp2, hue - 1.0 / 3.0)); } SkColor HSLShift(SkColor color, const HSL& shift) { HSL hsl; int alpha = SkColorGetA(color); SkColorToHSL(color, &hsl); // Replace the hue with the tint's hue. if (shift.h >= 0) hsl.h = shift.h; // Change the saturation. if (shift.s >= 0) { if (shift.s <= 0.5) hsl.s *= shift.s * 2.0; else hsl.s += (1.0 - hsl.s) * ((shift.s - 0.5) * 2.0); } SkColor result = HSLToSkColor(hsl, alpha); if (shift.l < 0) return result; // Lightness shifts in the style of popular image editors aren't // actually represented in HSL - the L value does have some effect // on saturation. double r = static_cast<double>(SkColorGetR(result)); double g = static_cast<double>(SkColorGetG(result)); double b = static_cast<double>(SkColorGetB(result)); if (shift.l <= 0.5) { r *= (shift.l * 2.0); g *= (shift.l * 2.0); b *= (shift.l * 2.0); } else { r += (255.0 - r) * ((shift.l - 0.5) * 2.0); g += (255.0 - g) * ((shift.l - 0.5) * 2.0); b += (255.0 - b) * ((shift.l - 0.5) * 2.0); } return SkColorSetARGB(alpha, static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } bool IsColorCloseToTransparent(SkAlpha alpha) { const int kCloseToBoundary = 64; return alpha < kCloseToBoundary; } bool IsColorCloseToGrey(int r, int g, int b) { const int kAverageBoundary = 15; int average = (r + g + b) / 3; return (abs(r - average) < kAverageBoundary) && (abs(g - average) < kAverageBoundary) && (abs(b - average) < kAverageBoundary); } SkColor GetAverageColorOfFavicon(SkBitmap* favicon, SkAlpha alpha) { int r = 0, g = 0, b = 0; SkAutoLockPixels favicon_lock(*favicon); SkColor* pixels = static_cast<SkColor*>(favicon->getPixels()); // Assume ARGB_8888 format. DCHECK(favicon->getConfig() == SkBitmap::kARGB_8888_Config); SkColor* current_color = pixels; DCHECK(favicon->width() <= 16 && favicon->height() <= 16); int pixel_count = favicon->width() * favicon->height(); int color_count = 0; for (int i = 0; i < pixel_count; ++i, ++current_color) { // Disregard this color if it is close to black, close to white, or close // to transparent since any of those pixels do not contribute much to the // color makeup of this icon. int cr = SkColorGetR(*current_color); int cg = SkColorGetG(*current_color); int cb = SkColorGetB(*current_color); if (IsColorCloseToTransparent(SkColorGetA(*current_color)) || IsColorCloseToGrey(cr, cg, cb)) continue; r += cr; g += cg; b += cb; ++color_count; } return color_count ? SkColorSetARGB(alpha, r / color_count, g / color_count, b / color_count) : SkColorSetARGB(alpha, 0, 0, 0); } void BuildLumaHistogram(SkBitmap* bitmap, int histogram[256]) { SkAutoLockPixels bitmap_lock(*bitmap); // Assume ARGB_8888 format. DCHECK(bitmap->getConfig() == SkBitmap::kARGB_8888_Config); int pixel_width = bitmap->width(); int pixel_height = bitmap->height(); for (int y = 0; y < pixel_height; ++y) { SkColor* current_color = static_cast<uint32_t*>(bitmap->getAddr32(0, y)); for (int x = 0; x < pixel_width; ++x, ++current_color) histogram[GetLuminanceForColor(*current_color)]++; } } SkColor AlphaBlend(SkColor foreground, SkColor background, SkAlpha alpha) { if (alpha == 0) return background; if (alpha == 255) return foreground; int f_alpha = SkColorGetA(foreground); int b_alpha = SkColorGetA(background); double normalizer = (f_alpha * alpha + b_alpha * (255 - alpha)) / 255.0; if (normalizer == 0.0) return SkColorSetARGB(0, 0, 0, 0); double f_weight = f_alpha * alpha / normalizer; double b_weight = b_alpha * (255 - alpha) / normalizer; double r = (SkColorGetR(foreground) * f_weight + SkColorGetR(background) * b_weight) / 255.0; double g = (SkColorGetG(foreground) * f_weight + SkColorGetG(background) * b_weight) / 255.0; double b = (SkColorGetB(foreground) * f_weight + SkColorGetB(background) * b_weight) / 255.0; return SkColorSetARGB(static_cast<int>(normalizer), static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } SkColor GetReadableColor(SkColor foreground, SkColor background) { const SkColor foreground2 = LumaInvertColor(foreground); const double background_luminance = RelativeLuminance(background); return (ContrastRatio(RelativeLuminance(foreground), background_luminance) >= ContrastRatio(RelativeLuminance(foreground2), background_luminance)) ? foreground : foreground2; } SkColor GetSysSkColor(int which) { #if defined(OS_WIN) return skia::COLORREFToSkColor(GetSysColor(which)); #else NOTIMPLEMENTED(); return SK_ColorLTGRAY; #endif } } // namespace color_utils <commit_msg>Check for no pixels after calling lockPixels(). If so, we return rather than dereferencing null.<commit_after>// Copyright (c) 2011 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 "ui/gfx/color_utils.h" #include <math.h> #if defined(OS_WIN) #include <windows.h> #endif #include <algorithm> #include "base/basictypes.h" #include "base/logging.h" #include "build/build_config.h" #if defined(OS_WIN) #include "skia/ext/skia_utils_win.h" #endif #include "third_party/skia/include/core/SkBitmap.h" namespace color_utils { // Helper functions ----------------------------------------------------------- namespace { int calcHue(double temp1, double temp2, double hue) { if (hue < 0.0) ++hue; else if (hue > 1.0) --hue; double result = temp1; if (hue * 6.0 < 1.0) result = temp1 + (temp2 - temp1) * hue * 6.0; else if (hue * 2.0 < 1.0) result = temp2; else if (hue * 3.0 < 2.0) result = temp1 + (temp2 - temp1) * (2.0 / 3.0 - hue) * 6.0; // Scale the result from 0 - 255 and round off the value. return static_cast<int>(result * 255 + .5); } // Next two functions' formulas from: // http://www.w3.org/TR/WCAG20/#relativeluminancedef // http://www.w3.org/TR/WCAG20/#contrast-ratiodef double ConvertSRGB(double eight_bit_component) { const double component = eight_bit_component / 255.0; return (component <= 0.03928) ? (component / 12.92) : pow((component + 0.055) / 1.055, 2.4); } SkColor LumaInvertColor(const SkColor& color) { HSL hsl; SkColorToHSL(color, &hsl); hsl.l = 1.0 - hsl.l; return HSLToSkColor(hsl, 255); } double ContrastRatio(double foreground_luminance, double background_luminance) { // NOTE: Only pass in numbers obtained from RelativeLuminance(), since those // are guaranteed to be > 0 and thus not cause a divide-by-zero error here. return (foreground_luminance > background_luminance) ? (foreground_luminance / background_luminance) : (background_luminance / foreground_luminance); } } // namespace // ---------------------------------------------------------------------------- unsigned char GetLuminanceForColor(SkColor color) { int luma = static_cast<int>((0.3 * SkColorGetR(color)) + (0.59 * SkColorGetG(color)) + (0.11 * SkColorGetB(color))); return std::max(std::min(luma, 255), 0); } double RelativeLuminance(SkColor color) { return (0.2126 * ConvertSRGB(SkColorGetR(color))) + (0.7152 * ConvertSRGB(SkColorGetG(color))) + (0.0722 * ConvertSRGB(SkColorGetB(color))) + 0.05; } void SkColorToHSL(SkColor c, HSL* hsl) { double r = static_cast<double>(SkColorGetR(c)) / 255.0; double g = static_cast<double>(SkColorGetG(c)) / 255.0; double b = static_cast<double>(SkColorGetB(c)) / 255.0; double vmax = std::max(std::max(r, g), b); double vmin = std::min(std::min(r, g), b); double delta = vmax - vmin; hsl->l = (vmax + vmin) / 2; if (SkColorGetR(c) == SkColorGetG(c) && SkColorGetR(c) == SkColorGetB(c)) { hsl->h = hsl->s = 0; } else { double dr = (((vmax - r) / 6.0) + (delta / 2.0)) / delta; double dg = (((vmax - g) / 6.0) + (delta / 2.0)) / delta; double db = (((vmax - b) / 6.0) + (delta / 2.0)) / delta; // We need to compare for the max value because comparing vmax to r, // g or b can sometimes result in values overflowing registers. if (r >= g && r >= b) hsl->h = db - dg; else if (g >= r && g >= b) hsl->h = (1.0 / 3.0) + dr - db; else // (b >= r && b >= g) hsl->h = (2.0 / 3.0) + dg - dr; if (hsl->h < 0.0) ++hsl->h; else if (hsl->h > 1.0) --hsl->h; hsl->s = delta / ((hsl->l < 0.5) ? (vmax + vmin) : (2 - vmax - vmin)); } } SkColor HSLToSkColor(const HSL& hsl, SkAlpha alpha) { double hue = hsl.h; double saturation = hsl.s; double lightness = hsl.l; // If there's no color, we don't care about hue and can do everything based // on brightness. if (!saturation) { uint8 light; if (lightness < 0) light = 0; else if (lightness >= 1.0) light = 255; else light = SkDoubleToFixed(lightness) >> 8; return SkColorSetARGB(alpha, light, light, light); } double temp2 = (lightness < 0.5) ? (lightness * (1.0 + saturation)) : (lightness + saturation - (lightness * saturation)); double temp1 = 2.0 * lightness - temp2; return SkColorSetARGB(alpha, calcHue(temp1, temp2, hue + 1.0 / 3.0), calcHue(temp1, temp2, hue), calcHue(temp1, temp2, hue - 1.0 / 3.0)); } SkColor HSLShift(SkColor color, const HSL& shift) { HSL hsl; int alpha = SkColorGetA(color); SkColorToHSL(color, &hsl); // Replace the hue with the tint's hue. if (shift.h >= 0) hsl.h = shift.h; // Change the saturation. if (shift.s >= 0) { if (shift.s <= 0.5) hsl.s *= shift.s * 2.0; else hsl.s += (1.0 - hsl.s) * ((shift.s - 0.5) * 2.0); } SkColor result = HSLToSkColor(hsl, alpha); if (shift.l < 0) return result; // Lightness shifts in the style of popular image editors aren't // actually represented in HSL - the L value does have some effect // on saturation. double r = static_cast<double>(SkColorGetR(result)); double g = static_cast<double>(SkColorGetG(result)); double b = static_cast<double>(SkColorGetB(result)); if (shift.l <= 0.5) { r *= (shift.l * 2.0); g *= (shift.l * 2.0); b *= (shift.l * 2.0); } else { r += (255.0 - r) * ((shift.l - 0.5) * 2.0); g += (255.0 - g) * ((shift.l - 0.5) * 2.0); b += (255.0 - b) * ((shift.l - 0.5) * 2.0); } return SkColorSetARGB(alpha, static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } bool IsColorCloseToTransparent(SkAlpha alpha) { const int kCloseToBoundary = 64; return alpha < kCloseToBoundary; } bool IsColorCloseToGrey(int r, int g, int b) { const int kAverageBoundary = 15; int average = (r + g + b) / 3; return (abs(r - average) < kAverageBoundary) && (abs(g - average) < kAverageBoundary) && (abs(b - average) < kAverageBoundary); } SkColor GetAverageColorOfFavicon(SkBitmap* favicon, SkAlpha alpha) { int r = 0, g = 0, b = 0; SkAutoLockPixels favicon_lock(*favicon); SkColor* pixels = static_cast<SkColor*>(favicon->getPixels()); if (!pixels) return SkColorSetARGB(alpha, 0, 0, 0); // Assume ARGB_8888 format. DCHECK(favicon->getConfig() == SkBitmap::kARGB_8888_Config); SkColor* current_color = pixels; DCHECK(favicon->width() <= 16 && favicon->height() <= 16); int pixel_count = favicon->width() * favicon->height(); int color_count = 0; for (int i = 0; i < pixel_count; ++i, ++current_color) { // Disregard this color if it is close to black, close to white, or close // to transparent since any of those pixels do not contribute much to the // color makeup of this icon. int cr = SkColorGetR(*current_color); int cg = SkColorGetG(*current_color); int cb = SkColorGetB(*current_color); if (IsColorCloseToTransparent(SkColorGetA(*current_color)) || IsColorCloseToGrey(cr, cg, cb)) continue; r += cr; g += cg; b += cb; ++color_count; } return color_count ? SkColorSetARGB(alpha, r / color_count, g / color_count, b / color_count) : SkColorSetARGB(alpha, 0, 0, 0); } void BuildLumaHistogram(SkBitmap* bitmap, int histogram[256]) { SkAutoLockPixels bitmap_lock(*bitmap); if (!bitmap->getPixels()) return; // Assume ARGB_8888 format. DCHECK(bitmap->getConfig() == SkBitmap::kARGB_8888_Config); int pixel_width = bitmap->width(); int pixel_height = bitmap->height(); for (int y = 0; y < pixel_height; ++y) { SkColor* current_color = static_cast<uint32_t*>(bitmap->getAddr32(0, y)); for (int x = 0; x < pixel_width; ++x, ++current_color) histogram[GetLuminanceForColor(*current_color)]++; } } SkColor AlphaBlend(SkColor foreground, SkColor background, SkAlpha alpha) { if (alpha == 0) return background; if (alpha == 255) return foreground; int f_alpha = SkColorGetA(foreground); int b_alpha = SkColorGetA(background); double normalizer = (f_alpha * alpha + b_alpha * (255 - alpha)) / 255.0; if (normalizer == 0.0) return SkColorSetARGB(0, 0, 0, 0); double f_weight = f_alpha * alpha / normalizer; double b_weight = b_alpha * (255 - alpha) / normalizer; double r = (SkColorGetR(foreground) * f_weight + SkColorGetR(background) * b_weight) / 255.0; double g = (SkColorGetG(foreground) * f_weight + SkColorGetG(background) * b_weight) / 255.0; double b = (SkColorGetB(foreground) * f_weight + SkColorGetB(background) * b_weight) / 255.0; return SkColorSetARGB(static_cast<int>(normalizer), static_cast<int>(r), static_cast<int>(g), static_cast<int>(b)); } SkColor GetReadableColor(SkColor foreground, SkColor background) { const SkColor foreground2 = LumaInvertColor(foreground); const double background_luminance = RelativeLuminance(background); return (ContrastRatio(RelativeLuminance(foreground), background_luminance) >= ContrastRatio(RelativeLuminance(foreground2), background_luminance)) ? foreground : foreground2; } SkColor GetSysSkColor(int which) { #if defined(OS_WIN) return skia::COLORREFToSkColor(GetSysColor(which)); #else NOTIMPLEMENTED(); return SK_ColorLTGRAY; #endif } } // namespace color_utils <|endoftext|>
<commit_before>#ifndef LISP_PTR_HH #define LISP_PTR_HH #include <string> #include <vector> #include <cstdio> #include <unordered_map> enum class Ptr_tag { undefined = -1, boolean = 0, character, cons, symbol, i_procedure, n_procedure, number, string, vector, port, env, vm_op }; class Lisp_ptr { public: constexpr Lisp_ptr() : tag_(Ptr_tag::undefined), u_(){} template<typename T> explicit constexpr Lisp_ptr(T); Lisp_ptr(const Lisp_ptr&) = default; Lisp_ptr(Lisp_ptr&&) = default; ~Lisp_ptr() = default; Lisp_ptr& operator=(const Lisp_ptr&) = default; Lisp_ptr& operator=(Lisp_ptr&&) = default; constexpr Ptr_tag tag() const { return tag_; } template<typename T> constexpr T get() const; explicit constexpr operator bool() const { return (tag_ != Ptr_tag::undefined); } private: union lisp_ptr_u{ constexpr lisp_ptr_u(){} constexpr lisp_ptr_u(void* p) : ptr_(p){} constexpr lisp_ptr_u(const void* p) : cptr_(p){} constexpr lisp_ptr_u(bool b) : b_(b){} constexpr lisp_ptr_u(char c) : c_(c){} constexpr lisp_ptr_u(int i) : i_(i){} constexpr lisp_ptr_u(void(*f)()) : f_(f){} void* ptr_; const void* cptr_; bool b_; char c_; int i_; void (*f_)(void); }; Ptr_tag tag_; lisp_ptr_u u_; }; // typedefs & declarations class Cons; class Symbol; namespace Procedure{ class IProcedure; class NProcedure; } class Number; typedef std::string String; typedef std::vector<Lisp_ptr> Vector; typedef FILE Port; typedef std::unordered_map<Symbol*, Lisp_ptr> Env; typedef void(*VM_op)(); const char* stringify(Ptr_tag); void describe(FILE*, Lisp_ptr); #include "lisp_ptr.i.hh" #endif // LISP_PTR_HH <commit_msg>bitly enum rearrange<commit_after>#ifndef LISP_PTR_HH #define LISP_PTR_HH #include <string> #include <vector> #include <cstdio> #include <unordered_map> enum class Ptr_tag { undefined = 0, boolean, character, cons, symbol, i_procedure, n_procedure, number, string, vector, port, env, vm_op }; class Lisp_ptr { public: constexpr Lisp_ptr() : tag_(Ptr_tag::undefined), u_(){} template<typename T> explicit constexpr Lisp_ptr(T); Lisp_ptr(const Lisp_ptr&) = default; Lisp_ptr(Lisp_ptr&&) = default; ~Lisp_ptr() = default; Lisp_ptr& operator=(const Lisp_ptr&) = default; Lisp_ptr& operator=(Lisp_ptr&&) = default; constexpr Ptr_tag tag() const { return tag_; } template<typename T> constexpr T get() const; explicit constexpr operator bool() const { return (tag_ != Ptr_tag::undefined); } private: union lisp_ptr_u{ constexpr lisp_ptr_u(){} constexpr lisp_ptr_u(void* p) : ptr_(p){} constexpr lisp_ptr_u(const void* p) : cptr_(p){} constexpr lisp_ptr_u(bool b) : b_(b){} constexpr lisp_ptr_u(char c) : c_(c){} constexpr lisp_ptr_u(int i) : i_(i){} constexpr lisp_ptr_u(void(*f)()) : f_(f){} void* ptr_; const void* cptr_; bool b_; char c_; int i_; void (*f_)(void); }; Ptr_tag tag_; lisp_ptr_u u_; }; // typedefs & declarations class Cons; class Symbol; namespace Procedure{ class IProcedure; class NProcedure; } class Number; typedef std::string String; typedef std::vector<Lisp_ptr> Vector; typedef FILE Port; typedef std::unordered_map<Symbol*, Lisp_ptr> Env; typedef void(*VM_op)(); const char* stringify(Ptr_tag); void describe(FILE*, Lisp_ptr); #include "lisp_ptr.i.hh" #endif // LISP_PTR_HH <|endoftext|>
<commit_before>#include "common.hpp" #undef LOG_TRACE #undef LOG_INFO #undef LOG_WARN #undef LOG_ERROR #include <syslog.h> #include <time.h> #include <unistd.h> #include <pthread.h> #define UTIL_CONTEXT util::logging::log_context(__FILE__, __LINE__, __FUNCTION__) // Stub is needed since pthreads // don't know about C++ objects extern "C" void* logproxy_run(void* p) { auto data = static_cast<util::logging::logproxy::threadlocal*>(p); data->proxy->run(data); return 0; } namespace { bool _syslog_open = false; FILE* _logfile = 0; void syslog_stop() { if (_syslog_open) { closelog(); _syslog_open = false; } } void syslog_write(int priority, const char* str, va_list arglist) { if (!_syslog_open) { openlog("util", LOG_CONS, LOG_USER); _syslog_open = true; } ::vsyslog (priority, str, arglist); } void logfile_close() { if (_logfile) { fclose(_logfile); } } void logfile_write(const char* fil, int lin, const char* str, va_list arglist) { if (!_logfile) { _logfile = fopen("util.log", "w"); atexit(logfile_close); } if (_logfile) { fprintf(_logfile, "%s(%d): ", fil, lin); vfprintf(_logfile, str, arglist); fprintf(_logfile, "\n"); } } } namespace util { namespace logging { bool colors = true; int modeflags = LogToConsole; LogLevels loglevel = Trace; pthread_mutex_t _log_mutex = PTHREAD_MUTEX_INITIALIZER; struct log_lock { log_lock() { pthread_mutex_lock(&_log_mutex); } ~log_lock() { pthread_mutex_unlock(&_log_mutex); } }; void set_log_mode(int flags) { log_lock ll; modeflags = flags; if (!(modeflags & LogToConsole)) { syslog_stop(); } if (!(modeflags & LogToFile)) { logfile_close(); } } void set_log_level(LogLevels level) { loglevel = level; } logproxy::logproxy() { inpipe = -1; } logproxy::~logproxy() { close(); } // log context has been lost at this point void logproxy::_eject(const char* str) { log_context("", -1, "").info("%s", str); } // copy complete lines from buf1 to buf2, // then write the completed lines to the log char* logproxy::_consume(char* wptr, ssize_t amt, char*const buf1, char*const buf2) { char* rptr = buf1; while ((rptr - buf1) < amt) { char next = *rptr; if (next == '\n') { if (wptr > buf2) { *wptr = 0; _eject(buf2); } wptr = buf2; } else { if (wptr >= buf2 + PROXY_BUFSIZE - 1) { *wptr = 0; _eject(buf2); wptr = buf2; } *wptr++ = next; } ++rptr; } return wptr; } // loop, reading from the given end of the pipe until it is closed, // writing every line we get to the log void logproxy::run(logproxy::threadlocal* data) { char* wptr = data->buf2; for (;;) { ssize_t amt = read(data->outpipe, data->buf1, PROXY_BUFSIZE); if (amt <= 0) { if (amt < 0) { UTIL_CONTEXT.error("Error in read() on fd %d. %s", data->outpipe, strerror(errno)); } break; } wptr = _consume(wptr, amt, data->buf1, data->buf2); } ::close(data->outpipe); delete data; } // Create a pipe to a thread that writes // everything it gets to the log. It can // then be passed to child processes to replace // stdout/stderr. bool logproxy::create() { int pip[2]; close(); if (pipe(pip) == -1) { UTIL_CONTEXT.error("Failed to create pipe for subprocess logging."); return false; } inpipe = pip[1]; threadlocal* data = new threadlocal; data->proxy = this; data->outpipe = pip[0]; memset(data->buf1, 0, PROXY_BUFSIZE); memset(data->buf2, 0, PROXY_BUFSIZE); pthread_t proxythread; pthread_attr_t detach; pthread_attr_init(&detach); pthread_attr_setdetachstate(&detach, PTHREAD_CREATE_DETACHED); pthread_create(&proxythread, &detach, &logproxy_run, data); pthread_attr_destroy(&detach); return true; } void logproxy::close() { if (inpipe != -1) { ::close(inpipe); inpipe = -1; } } namespace { const char* timenowstring(char* buf) { time_t t; struct tm tid; ::time(&t); ::localtime_r(&t, &tid); strftime (buf, 30, "%x %X", &tid); return buf; } } log_context::log_context(const char* fil, int lin, const char* fun) : _file(fil), _line(lin), _fun(fun) { static const char* prefixes[] = { "../src/", "src/" }; for (size_t i = 0; i < ASIZE(prefixes); ++i) if (strncmp(_file, prefixes[i], strlen(prefixes[i])) == 0) _file += strlen(prefixes[i]); } void log_context::info(const char* fmt, ...) { if (loglevel > Info) return; log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_INFO, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (_line >= 0) fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s\n", timenowstring(tbuf), tmp); fflush(stdout); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void log_context::trace(const char* fmt, ...) { if (loglevel > Trace) return; log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_DEBUG, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (colors) fprintf(stdout, "\e[%dm%s %s(%d): %s\e[0m\n", CYAN, timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void log_context::warn(const char* fmt, ...) { if (loglevel > Warn) return; log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_WARNING, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (colors) fprintf(stdout, "\e[%dm%s %s(%d): %s\e[0m\n", YELLOW, timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); fflush(stdout); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void log_context::error(const char* fmt, ...) { log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_ERR, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (colors) fprintf(stdout, "\e[%dm%s %s(%d): %s\e[0m\n", RED, timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); fflush(stdout); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void cprintf(int color, const char* fmt, ...) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); if (colors) { size_t len = strlen(tmp); bool nl = (tmp[len-1] == '\n'); if (nl) tmp[len-1] = '\0'; printf("\e[%dm%s\e[0m%s", color, tmp, nl?"\n":""); } else printf("%s", tmp); } } } <commit_msg>fix logging filename cleaner<commit_after>#include "common.hpp" #undef LOG_TRACE #undef LOG_INFO #undef LOG_WARN #undef LOG_ERROR #include <syslog.h> #include <time.h> #include <unistd.h> #include <pthread.h> #define UTIL_CONTEXT util::logging::log_context(__FILE__, __LINE__, __FUNCTION__) // Stub is needed since pthreads // don't know about C++ objects extern "C" void* logproxy_run(void* p) { auto data = static_cast<util::logging::logproxy::threadlocal*>(p); data->proxy->run(data); return 0; } namespace { bool _syslog_open = false; FILE* _logfile = 0; void syslog_stop() { if (_syslog_open) { closelog(); _syslog_open = false; } } void syslog_write(int priority, const char* str, va_list arglist) { if (!_syslog_open) { openlog("util", LOG_CONS, LOG_USER); _syslog_open = true; } ::vsyslog (priority, str, arglist); } void logfile_close() { if (_logfile) { fclose(_logfile); } } void logfile_write(const char* fil, int lin, const char* str, va_list arglist) { if (!_logfile) { _logfile = fopen("util.log", "w"); atexit(logfile_close); } if (_logfile) { fprintf(_logfile, "%s(%d): ", fil, lin); vfprintf(_logfile, str, arglist); fprintf(_logfile, "\n"); } } } namespace util { namespace logging { bool colors = true; int modeflags = LogToConsole; LogLevels loglevel = Trace; pthread_mutex_t _log_mutex = PTHREAD_MUTEX_INITIALIZER; struct log_lock { log_lock() { pthread_mutex_lock(&_log_mutex); } ~log_lock() { pthread_mutex_unlock(&_log_mutex); } }; void set_log_mode(int flags) { log_lock ll; modeflags = flags; if (!(modeflags & LogToConsole)) { syslog_stop(); } if (!(modeflags & LogToFile)) { logfile_close(); } } void set_log_level(LogLevels level) { loglevel = level; } logproxy::logproxy() { inpipe = -1; } logproxy::~logproxy() { close(); } // log context has been lost at this point void logproxy::_eject(const char* str) { log_context("", -1, "").info("%s", str); } // copy complete lines from buf1 to buf2, // then write the completed lines to the log char* logproxy::_consume(char* wptr, ssize_t amt, char*const buf1, char*const buf2) { char* rptr = buf1; while ((rptr - buf1) < amt) { char next = *rptr; if (next == '\n') { if (wptr > buf2) { *wptr = 0; _eject(buf2); } wptr = buf2; } else { if (wptr >= buf2 + PROXY_BUFSIZE - 1) { *wptr = 0; _eject(buf2); wptr = buf2; } *wptr++ = next; } ++rptr; } return wptr; } // loop, reading from the given end of the pipe until it is closed, // writing every line we get to the log void logproxy::run(logproxy::threadlocal* data) { char* wptr = data->buf2; for (;;) { ssize_t amt = read(data->outpipe, data->buf1, PROXY_BUFSIZE); if (amt <= 0) { if (amt < 0) { UTIL_CONTEXT.error("Error in read() on fd %d. %s", data->outpipe, strerror(errno)); } break; } wptr = _consume(wptr, amt, data->buf1, data->buf2); } ::close(data->outpipe); delete data; } // Create a pipe to a thread that writes // everything it gets to the log. It can // then be passed to child processes to replace // stdout/stderr. bool logproxy::create() { int pip[2]; close(); if (pipe(pip) == -1) { UTIL_CONTEXT.error("Failed to create pipe for subprocess logging."); return false; } inpipe = pip[1]; threadlocal* data = new threadlocal; data->proxy = this; data->outpipe = pip[0]; memset(data->buf1, 0, PROXY_BUFSIZE); memset(data->buf2, 0, PROXY_BUFSIZE); pthread_t proxythread; pthread_attr_t detach; pthread_attr_init(&detach); pthread_attr_setdetachstate(&detach, PTHREAD_CREATE_DETACHED); pthread_create(&proxythread, &detach, &logproxy_run, data); pthread_attr_destroy(&detach); return true; } void logproxy::close() { if (inpipe != -1) { ::close(inpipe); inpipe = -1; } } namespace { const char* timenowstring(char* buf) { time_t t; struct tm tid; ::time(&t); ::localtime_r(&t, &tid); strftime (buf, 30, "%x %X", &tid); return buf; } } log_context::log_context(const char* fil, int lin, const char* fun) : _file(fil), _line(lin), _fun(fun) { static const char* prefixes[] = { "../src/", "src/" }; for (size_t i = 0; i < ASIZE(prefixes); ++i) { const char* offs = strstr(_file, prefixes[i]); while (offs) { _file = offs + strlen(prefixes[i]); offs = strstr(_file, prefixes[i]); } } } void log_context::info(const char* fmt, ...) { if (loglevel > Info) return; log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_INFO, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (_line >= 0) fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s\n", timenowstring(tbuf), tmp); fflush(stdout); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void log_context::trace(const char* fmt, ...) { if (loglevel > Trace) return; log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_DEBUG, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (colors) fprintf(stdout, "\e[%dm%s %s(%d): %s\e[0m\n", CYAN, timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void log_context::warn(const char* fmt, ...) { if (loglevel > Warn) return; log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_WARNING, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (colors) fprintf(stdout, "\e[%dm%s %s(%d): %s\e[0m\n", YELLOW, timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); fflush(stdout); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void log_context::error(const char* fmt, ...) { log_lock ll; if (modeflags & LogToSyslog) { va_list va_args; va_start(va_args, fmt); syslog_write(LOG_ERR, fmt, va_args); va_end(va_args); } if (modeflags & LogToConsole) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); char tbuf[30]; if (colors) fprintf(stdout, "\e[%dm%s %s(%d): %s\e[0m\n", RED, timenowstring(tbuf), _file, _line, tmp); else fprintf(stdout, "%s %s(%d): %s\n", timenowstring(tbuf), _file, _line, tmp); fflush(stdout); } if (modeflags & LogToFile) { va_list va_args; va_start(va_args, fmt); logfile_write(_file, _line, fmt, va_args); va_end(va_args); } } void cprintf(int color, const char* fmt, ...) { char tmp[2048]; va_list va_args; va_start(va_args, fmt); vsnprintf(tmp, sizeof(tmp), fmt, va_args); va_end(va_args); if (colors) { size_t len = strlen(tmp); bool nl = (tmp[len-1] == '\n'); if (nl) tmp[len-1] = '\0'; printf("\e[%dm%s\e[0m%s", color, tmp, nl?"\n":""); } else printf("%s", tmp); } } } <|endoftext|>
<commit_before>#include <atomic> #include "test.hpp" #include "caf/all.hpp" #include "caf/string_algorithms.hpp" using namespace std; using namespace caf; namespace { atomic<size_t> s_error_count{0}; } size_t caf_error_count() { return s_error_count; } void caf_inc_error_count() { ++s_error_count; } string caf_fill4(size_t value) { string result = to_string(value); while (result.size() < 4) result.insert(result.begin(), '0'); return result; } const char* caf_strip_path(const char* file) { auto res = file; auto i = file; for (char c = *i; c != '\0'; c = *++i) { if (c == '/') { res = i + 1; } } return res; } void caf_unexpected_message(const char* file, size_t line, message t) { CAF_PRINTERRC(file, line, "unexpected message: " << to_string(t)); } void caf_unexpected_timeout(const char* file, size_t line) { CAF_PRINTERRC(file, line, "unexpected timeout"); } vector<string> split(const string& str, char delim, bool keep_empties) { using namespace std; vector<string> result; stringstream strs{str}; string tmp; while (getline(strs, tmp, delim)) { if (!tmp.empty() || keep_empties) result.push_back(move(tmp)); } return result; } void verbose_terminate() { try { throw; } catch (std::exception& e) { CAF_PRINTERR("terminate called after throwing " << to_verbose_string(e)); } catch (...) { CAF_PRINTERR("terminate called after throwing an unknown exception"); } abort(); } void set_default_test_settings() { set_terminate(verbose_terminate); cout.unsetf(ios_base::unitbuf); } std::thread run_program_impl(const char* cpath, std::vector<std::string> args) { string path = cpath; replace_all(path, "'", "\\'"); ostringstream oss; oss << "'" << path << "'"; for (auto& arg : args) { oss << " " << arg; } oss << to_dev_null; string cmdstr = oss.str(); return thread{[cmdstr] { if (system(cmdstr.c_str()) != 0) { CAF_PRINTERR("FATAL: command line failed: " << cmdstr); abort(); } }}; } <commit_msg>Coding style nitpicks<commit_after>#include <atomic> #include "test.hpp" #include "caf/all.hpp" #include "caf/string_algorithms.hpp" using namespace std; using namespace caf; namespace { atomic<size_t> s_error_count{0}; } size_t caf_error_count() { return s_error_count; } void caf_inc_error_count() { ++s_error_count; } string caf_fill4(size_t value) { string result = to_string(value); while (result.size() < 4) result.insert(result.begin(), '0'); return result; } const char* caf_strip_path(const char* file) { auto res = file; auto i = file; for (char c = *i; c != '\0'; c = *++i) { if (c == '/') { res = i + 1; } } return res; } void caf_unexpected_message(const char* file, size_t line, message t) { CAF_PRINTERRC(file, line, "unexpected message: " << to_string(t)); } void caf_unexpected_timeout(const char* file, size_t line) { CAF_PRINTERRC(file, line, "unexpected timeout"); } vector<string> split(const string& str, char delim, bool keep_empties) { using namespace std; vector<string> result; stringstream strs{str}; string tmp; while (getline(strs, tmp, delim)) { if (!tmp.empty() || keep_empties) result.push_back(move(tmp)); } return result; } void verbose_terminate() { try { throw; } catch (std::exception& e) { CAF_PRINTERR("terminate called after throwing " << to_verbose_string(e)); } catch (...) { CAF_PRINTERR("terminate called after throwing an unknown exception"); } abort(); } void set_default_test_settings() { set_terminate(verbose_terminate); cout.unsetf(ios_base::unitbuf); } std::thread run_program_impl(const char* cpath, std::vector<std::string> args) { string path = cpath; replace_all(path, "'", "\\'"); ostringstream oss; oss << "'" << path << "'"; for (auto& arg : args) { oss << " " << arg; } oss << to_dev_null; string cmdstr = oss.str(); return thread{[cmdstr] { if (system(cmdstr.c_str()) != 0) { CAF_PRINTERR("FATAL: command line failed: " << cmdstr); abort(); } }}; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ci_text2.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-15 11:10:40 $ * * 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 * ************************************************************************/ #ifndef ARY_CINFO_CI_TEXT2_HXX #define ARY_CINFO_CI_TEXT2_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS namespace ary { namespace info { class DocumentationDisplay; class DocuToken { public: virtual ~DocuToken() {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const = 0; virtual bool IsWhiteOnly() const = 0; }; class DocuTex2 { public: typedef std::vector< DocuToken * > TokenList; DocuTex2(); virtual ~DocuTex2(); virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; void AddToken( DYN DocuToken & let_drToken ); const TokenList & Tokens() const { return aTokens; } bool IsEmpty() const; const String & TextOfFirstToken() const; String & Access_TextOfFirstToken(); private: TokenList aTokens; }; // IMPLEMENTATION } // namespace info } // namespace ary #endif <commit_msg>INTEGRATION: CWS adc18 (1.5.24); FILE MERGED 2007/10/18 13:10:22 np 1.5.24.1: #i81775#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ci_text2.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-11-02 15:20:24 $ * * 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 * ************************************************************************/ #ifndef ARY_CINFO_CI_TEXT2_HXX #define ARY_CINFO_CI_TEXT2_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS namespace ary { namespace inf { class DocumentationDisplay; class DocuToken { public: virtual ~DocuToken() {} virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const = 0; virtual bool IsWhiteOnly() const = 0; }; class DocuTex2 { public: typedef std::vector< DocuToken * > TokenList; DocuTex2(); virtual ~DocuTex2(); virtual void DisplayAt( DocumentationDisplay & o_rDisplay ) const; void AddToken( DYN DocuToken & let_drToken ); const TokenList & Tokens() const { return aTokens; } bool IsEmpty() const; const String & TextOfFirstToken() const; String & Access_TextOfFirstToken(); private: TokenList aTokens; }; // IMPLEMENTATION } // namespace inf } // namespace ary #endif <|endoftext|>
<commit_before>#include <algorithm> #include <ctime> #include <climits> #include <iostream> #include <string> #include "arg_parser.hpp" #include "alarm/alarm.h" int main(int argc, char* argv[]) { ArgParser input(argc, argv); struct tm alarm_time; if(!strptime(argv[1], "%H:%M", &alarm_time)) return -1; int dow; std::string dow_str = input.getOption("-d"); if(!dow_str.empty()) { dow = std::stoi(dow_str); } else { dow = -1; } std::string alarmid = input.getOption("-n"); if(!alarmid.empty()) alarmid="alarm"; std::string start_date_str = input.getOption("-b"); struct tm start_date; if(!start_date_str.empty()) { if(!strptime(start_date_str.c_str(), "%Y-%m-%d", &start_date)) return -1; } else { time_t rawtime; time(&rawtime); start_date = *localtime(&rawtime); } std::string stop_date_str = input.getOption("-e"); struct tm stop_date; if(!stop_date_str.empty()) { if(!strptime(stop_date_str.c_str(), "%Y-%m-%d", &stop_date)) return -1; } else { time_t rawtime = INT_MAX; stop_date = *localtime(&rawtime); } std::cout << alarmid << " " << dow << " " << asctime(&alarm_time) << std::endl; std::cout << asctime(&start_date); std::cout << asctime(&stop_date); } <commit_msg>Improved formatting, and code cleanup in mkalarm.<commit_after>#include <algorithm> #include <ctime> #include <climits> #include <iostream> #include <string> #include <iomanip> #include "arg_parser.hpp" #include "alarm/alarm.h" enum WeekDay {ALL=-1, SUN, MON, TUE, WED, THU, FRI, SAT}; const std::string wdtostr(WeekDay wd) { switch(wd) { case ALL: return "Everyday"; case SUN: return "Sunday"; case MON: return "Monday"; case TUE: return "Tuesday"; case WED: return "Wednesday"; case THU: return "Sunday"; case FRI: return "Friday"; case SAT: return "Saturday"; } } WeekDay strtowd(std::string str) { if(str == "Sunday" || str == "Sun") { return SUN; } else if(str == "Monday" || str == "Mon") { return MON; } else if(str == "Tuesday" || str == "Tue") { return TUE; } else if(str == "Wednesday" || str == "Wed") { return WED; } else if(str == "Thursday" || str == "Thu") { return THU; } else if(str == "Friday" || str == "Fri") { return FRI; } else if(str == "Saturday" || str == "Sat") { return SAT; } else { return ALL; } } int main(int argc, char* argv[]) { ArgParser input(argc, argv); struct tm alarm_time; if(!strptime(argv[1], "%H:%M", &alarm_time) || input.optionExists("-h")) { std::cerr << "Usage: " << argv[0] << " HH:MM [-d W] [-n id] [-b YYYY-MM-DD] [-e YYYY-MM-DD]" << std::endl; std::cerr << "HH:MM | Alarm time" << std::endl; std::cerr << "-d W | Alarm weekday (Sunday or Sun)" << std::endl; std::cerr << "-n id | Alarm id" << std::endl; std::cerr << "-b YYYY-MM-DD | Alarm start date" << std::endl; std::cerr << "-e YYYY-MM-DD | Alarm end date" << std::endl; return -2; } std::string dow_str = input.getOption("-d"); WeekDay dow; if(!dow_str.empty()) { dow = strtowd(dow_str); } else { dow = WeekDay::ALL; } std::string alarmid = input.getOption("-n"); if(alarmid.empty()) alarmid="alarm"; std::string start_date_str = input.getOption("-b"); struct tm start_date; if(!start_date_str.empty()) { if(!strptime(start_date_str.c_str(), "%Y-%m-%d", &start_date)) return -1; } else { time_t rawtime; time(&rawtime); start_date = *localtime(&rawtime); } std::string stop_date_str = input.getOption("-e"); struct tm stop_date; if(!stop_date_str.empty()) { if(!strptime(stop_date_str.c_str(), "%Y-%m-%d", &stop_date)) return -1; } else { time_t endtime = INT_MAX; stop_date = *localtime(&endtime); } std::cout << alarmid << ' ' << wdtostr(dow) << ' '; std::cout << std::setw(2) << std::setfill('0'); std::cout << alarm_time.tm_hour; std::cout << ':'; std::cout << std::setw(2) << std::setfill('0'); std::cout << alarm_time.tm_min << std::endl; std::cout << "Start Date: "; std::cout << std::setw(4) << std::setfill('0') << 1900 + start_date.tm_year; std::cout << "-"; std::cout << std::setw(2) << std::setfill('0') << start_date.tm_mon; std::cout << "-"; std::cout << std::setw(2) << std::setfill('0') << start_date.tm_mday; std::cout << std::endl; std::cout << "Stop Date: "; std::cout << std::setw(4) << std::setfill('0') << 1900 + stop_date.tm_year; std::cout << "-"; std::cout << std::setw(2) << std::setfill('0') << stop_date.tm_mon; std::cout << "-"; std::cout << std::setw(2) << std::setfill('0') << stop_date.tm_mday; std::cout << std::endl; } <|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/basictypes.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/platform_thread.h" #include "base/shared_memory.h" #include "base/scoped_ptr.h" #include "base/test/multiprocess_test.h" #include "base/time.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" static const int kNumThreads = 5; static const int kNumTasks = 5; namespace base { namespace { // Each thread will open the shared memory. Each thread will take a different 4 // byte int pointer, and keep changing it, with some small pauses in between. // Verify that each thread's value in the shared memory is always correct. class MultipleThreadMain : public PlatformThread::Delegate { public: explicit MultipleThreadMain(int16 id) : id_(id) {} ~MultipleThreadMain() {} static void CleanUp() { SharedMemory memory; memory.Delete(s_test_name_); } // PlatformThread::Delegate interface. void ThreadMain() { mac::ScopedNSAutoreleasePool pool; // noop if not OSX const uint32 kDataSize = 1024; SharedMemory memory; bool rv = memory.CreateNamed(s_test_name_, true, kDataSize); EXPECT_TRUE(rv); rv = memory.Map(kDataSize); EXPECT_TRUE(rv); int *ptr = static_cast<int*>(memory.memory()) + id_; EXPECT_EQ(*ptr, 0); for (int idx = 0; idx < 100; idx++) { *ptr = idx; PlatformThread::Sleep(1); // Short wait. EXPECT_EQ(*ptr, idx); } memory.Close(); } private: int16 id_; static const char* const s_test_name_; DISALLOW_COPY_AND_ASSIGN(MultipleThreadMain); }; const char* const MultipleThreadMain::s_test_name_ = "SharedMemoryOpenThreadTest"; // TODO(port): // This test requires the ability to pass file descriptors between processes. // We haven't done that yet in Chrome for POSIX. #if defined(OS_WIN) // Each thread will open the shared memory. Each thread will take the memory, // and keep changing it while trying to lock it, with some small pauses in // between. Verify that each thread's value in the shared memory is always // correct. class MultipleLockThread : public PlatformThread::Delegate { public: explicit MultipleLockThread(int id) : id_(id) {} ~MultipleLockThread() {} // PlatformThread::Delegate interface. void ThreadMain() { const uint32 kDataSize = sizeof(int); SharedMemoryHandle handle = NULL; { SharedMemory memory1; EXPECT_TRUE(memory1.CreateNamed("SharedMemoryMultipleLockThreadTest", true, kDataSize)); EXPECT_TRUE(memory1.ShareToProcess(GetCurrentProcess(), &handle)); // TODO(paulg): Implement this once we have a posix version of // SharedMemory::ShareToProcess. EXPECT_TRUE(true); } SharedMemory memory2(handle, false); EXPECT_TRUE(memory2.Map(kDataSize)); volatile int* const ptr = static_cast<int*>(memory2.memory()); for (int idx = 0; idx < 20; idx++) { memory2.Lock(); int i = (id_ << 16) + idx; *ptr = i; PlatformThread::Sleep(1); // Short wait. EXPECT_EQ(*ptr, i); memory2.Unlock(); } memory2.Close(); } private: int id_; DISALLOW_COPY_AND_ASSIGN(MultipleLockThread); }; #endif } // namespace TEST(SharedMemoryTest, OpenClose) { const uint32 kDataSize = 1024; std::string test_name = "SharedMemoryOpenCloseTest"; // Open two handles to a memory segment, confirm that they are mapped // separately yet point to the same space. SharedMemory memory1; bool rv = memory1.Delete(test_name); EXPECT_TRUE(rv); rv = memory1.Delete(test_name); EXPECT_TRUE(rv); rv = memory1.Open(test_name, false); EXPECT_FALSE(rv); rv = memory1.CreateNamed(test_name, false, kDataSize); EXPECT_TRUE(rv); rv = memory1.Map(kDataSize); EXPECT_TRUE(rv); SharedMemory memory2; rv = memory2.Open(test_name, false); EXPECT_TRUE(rv); rv = memory2.Map(kDataSize); EXPECT_TRUE(rv); EXPECT_NE(memory1.memory(), memory2.memory()); // Compare the pointers. // Make sure we don't segfault. (it actually happened!) ASSERT_NE(memory1.memory(), static_cast<void*>(NULL)); ASSERT_NE(memory2.memory(), static_cast<void*>(NULL)); // Write data to the first memory segment, verify contents of second. memset(memory1.memory(), '1', kDataSize); EXPECT_EQ(memcmp(memory1.memory(), memory2.memory(), kDataSize), 0); // Close the first memory segment, and verify the second has the right data. memory1.Close(); char *start_ptr = static_cast<char *>(memory2.memory()); char *end_ptr = start_ptr + kDataSize; for (char* ptr = start_ptr; ptr < end_ptr; ptr++) EXPECT_EQ(*ptr, '1'); // Close the second memory segment. memory2.Close(); rv = memory1.Delete(test_name); EXPECT_TRUE(rv); rv = memory2.Delete(test_name); EXPECT_TRUE(rv); } TEST(SharedMemoryTest, OpenExclusive) { const uint32 kDataSize = 1024; const uint32 kDataSize2 = 2048; std::ostringstream test_name_stream; test_name_stream << "SharedMemoryOpenExclusiveTest." << Time::Now().ToDoubleT(); std::string test_name = test_name_stream.str(); // Open two handles to a memory segment and check that open_existing works // as expected. SharedMemory memory1; bool rv = memory1.CreateNamed(test_name, false, kDataSize); EXPECT_TRUE(rv); // Memory1 knows it's size because it created it. EXPECT_EQ(memory1.created_size(), kDataSize); rv = memory1.Map(kDataSize); EXPECT_TRUE(rv); memset(memory1.memory(), 'G', kDataSize); SharedMemory memory2; // Should not be able to create if openExisting is false. rv = memory2.CreateNamed(test_name, false, kDataSize2); EXPECT_FALSE(rv); // Should be able to create with openExisting true. rv = memory2.CreateNamed(test_name, true, kDataSize2); EXPECT_TRUE(rv); // Memory2 shouldn't know the size because we didn't create it. EXPECT_EQ(memory2.created_size(), 0U); // We should be able to map the original size. rv = memory2.Map(kDataSize); EXPECT_TRUE(rv); // Verify that opening memory2 didn't truncate or delete memory 1. char *start_ptr = static_cast<char *>(memory2.memory()); char *end_ptr = start_ptr + kDataSize; for (char* ptr = start_ptr; ptr < end_ptr; ptr++) { EXPECT_EQ(*ptr, 'G'); } memory1.Close(); memory2.Close(); rv = memory1.Delete(test_name); EXPECT_TRUE(rv); } // Create a set of N threads to each open a shared memory segment and write to // it. Verify that they are always reading/writing consistent data. TEST(SharedMemoryTest, MultipleThreads) { MultipleThreadMain::CleanUp(); // On POSIX we have a problem when 2 threads try to create the shmem // (a file) at exactly the same time, since create both creates the // file and zerofills it. We solve the problem for this unit test // (make it not flaky) by starting with 1 thread, then // intentionally don't clean up its shmem before running with // kNumThreads. int threadcounts[] = { 1, kNumThreads }; for (size_t i = 0; i < sizeof(threadcounts) / sizeof(threadcounts); i++) { int numthreads = threadcounts[i]; scoped_array<PlatformThreadHandle> thread_handles; scoped_array<MultipleThreadMain*> thread_delegates; thread_handles.reset(new PlatformThreadHandle[numthreads]); thread_delegates.reset(new MultipleThreadMain*[numthreads]); // Spawn the threads. for (int16 index = 0; index < numthreads; index++) { PlatformThreadHandle pth; thread_delegates[index] = new MultipleThreadMain(index); EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth)); thread_handles[index] = pth; } // Wait for the threads to finish. for (int index = 0; index < numthreads; index++) { PlatformThread::Join(thread_handles[index]); delete thread_delegates[index]; } } MultipleThreadMain::CleanUp(); } // TODO(port): this test requires the MultipleLockThread class // (defined above), which requires the ability to pass file // descriptors between processes. We haven't done that yet in Chrome // for POSIX. #if defined(OS_WIN) // Create a set of threads to each open a shared memory segment and write to it // with the lock held. Verify that they are always reading/writing consistent // data. TEST(SharedMemoryTest, Lock) { PlatformThreadHandle thread_handles[kNumThreads]; MultipleLockThread* thread_delegates[kNumThreads]; // Spawn the threads. for (int index = 0; index < kNumThreads; ++index) { PlatformThreadHandle pth; thread_delegates[index] = new MultipleLockThread(index); EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth)); thread_handles[index] = pth; } // Wait for the threads to finish. for (int index = 0; index < kNumThreads; ++index) { PlatformThread::Join(thread_handles[index]); delete thread_delegates[index]; } } #endif // Allocate private (unique) shared memory with an empty string for a // name. Make sure several of them don't point to the same thing as // we might expect if the names are equal. TEST(SharedMemoryTest, AnonymousPrivate) { int i, j; int count = 4; bool rv; const uint32 kDataSize = 8192; scoped_array<SharedMemory> memories(new SharedMemory[count]); scoped_array<int*> pointers(new int*[count]); ASSERT_TRUE(memories.get()); ASSERT_TRUE(pointers.get()); for (i = 0; i < count; i++) { rv = memories[i].CreateAndMapAnonymous(kDataSize); EXPECT_TRUE(rv); int *ptr = static_cast<int*>(memories[i].memory()); EXPECT_TRUE(ptr); pointers[i] = ptr; } for (i = 0; i < count; i++) { // zero out the first int in each except for i; for that one, make it 100. for (j = 0; j < count; j++) { if (i == j) pointers[j][0] = 100; else pointers[j][0] = 0; } // make sure there is no bleeding of the 100 into the other pointers for (j = 0; j < count; j++) { if (i == j) EXPECT_EQ(100, pointers[j][0]); else EXPECT_EQ(0, pointers[j][0]); } } for (int i = 0; i < count; i++) { memories[i].Close(); } } // On POSIX it is especially important we test shmem across processes, // not just across threads. But the test is enabled on all platforms. class SharedMemoryProcessTest : public base::MultiProcessTest { public: static void CleanUp() { SharedMemory memory; memory.Delete(s_test_name_); } static int TaskTestMain() { int errors = 0; mac::ScopedNSAutoreleasePool pool; // noop if not OSX const uint32 kDataSize = 1024; SharedMemory memory; bool rv = memory.CreateNamed(s_test_name_, true, kDataSize); EXPECT_TRUE(rv); if (rv != true) errors++; rv = memory.Map(kDataSize); EXPECT_TRUE(rv); if (rv != true) errors++; int *ptr = static_cast<int*>(memory.memory()); for (int idx = 0; idx < 20; idx++) { memory.Lock(); int i = (1 << 16) + idx; *ptr = i; PlatformThread::Sleep(10); // Short wait. if (*ptr != i) errors++; memory.Unlock(); } memory.Close(); return errors; } private: static const char* const s_test_name_; }; const char* const SharedMemoryProcessTest::s_test_name_ = "MPMem"; TEST_F(SharedMemoryProcessTest, Tasks) { SharedMemoryProcessTest::CleanUp(); base::ProcessHandle handles[kNumTasks]; for (int index = 0; index < kNumTasks; ++index) { handles[index] = SpawnChild("SharedMemoryTestMain", false); } int exit_code = 0; for (int index = 0; index < kNumTasks; ++index) { EXPECT_TRUE(base::WaitForExitCode(handles[index], &exit_code)); EXPECT_TRUE(exit_code == 0); } SharedMemoryProcessTest::CleanUp(); } MULTIPROCESS_TEST_MAIN(SharedMemoryTestMain) { return SharedMemoryProcessTest::TaskTestMain(); } } // namespace base <commit_msg>Mark SharedMemoryProcessTest.Tasks as flaky on Mac.<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/basictypes.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/platform_thread.h" #include "base/shared_memory.h" #include "base/scoped_ptr.h" #include "base/test/multiprocess_test.h" #include "base/time.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" static const int kNumThreads = 5; static const int kNumTasks = 5; namespace base { namespace { // Each thread will open the shared memory. Each thread will take a different 4 // byte int pointer, and keep changing it, with some small pauses in between. // Verify that each thread's value in the shared memory is always correct. class MultipleThreadMain : public PlatformThread::Delegate { public: explicit MultipleThreadMain(int16 id) : id_(id) {} ~MultipleThreadMain() {} static void CleanUp() { SharedMemory memory; memory.Delete(s_test_name_); } // PlatformThread::Delegate interface. void ThreadMain() { mac::ScopedNSAutoreleasePool pool; // noop if not OSX const uint32 kDataSize = 1024; SharedMemory memory; bool rv = memory.CreateNamed(s_test_name_, true, kDataSize); EXPECT_TRUE(rv); rv = memory.Map(kDataSize); EXPECT_TRUE(rv); int *ptr = static_cast<int*>(memory.memory()) + id_; EXPECT_EQ(*ptr, 0); for (int idx = 0; idx < 100; idx++) { *ptr = idx; PlatformThread::Sleep(1); // Short wait. EXPECT_EQ(*ptr, idx); } memory.Close(); } private: int16 id_; static const char* const s_test_name_; DISALLOW_COPY_AND_ASSIGN(MultipleThreadMain); }; const char* const MultipleThreadMain::s_test_name_ = "SharedMemoryOpenThreadTest"; // TODO(port): // This test requires the ability to pass file descriptors between processes. // We haven't done that yet in Chrome for POSIX. #if defined(OS_WIN) // Each thread will open the shared memory. Each thread will take the memory, // and keep changing it while trying to lock it, with some small pauses in // between. Verify that each thread's value in the shared memory is always // correct. class MultipleLockThread : public PlatformThread::Delegate { public: explicit MultipleLockThread(int id) : id_(id) {} ~MultipleLockThread() {} // PlatformThread::Delegate interface. void ThreadMain() { const uint32 kDataSize = sizeof(int); SharedMemoryHandle handle = NULL; { SharedMemory memory1; EXPECT_TRUE(memory1.CreateNamed("SharedMemoryMultipleLockThreadTest", true, kDataSize)); EXPECT_TRUE(memory1.ShareToProcess(GetCurrentProcess(), &handle)); // TODO(paulg): Implement this once we have a posix version of // SharedMemory::ShareToProcess. EXPECT_TRUE(true); } SharedMemory memory2(handle, false); EXPECT_TRUE(memory2.Map(kDataSize)); volatile int* const ptr = static_cast<int*>(memory2.memory()); for (int idx = 0; idx < 20; idx++) { memory2.Lock(); int i = (id_ << 16) + idx; *ptr = i; PlatformThread::Sleep(1); // Short wait. EXPECT_EQ(*ptr, i); memory2.Unlock(); } memory2.Close(); } private: int id_; DISALLOW_COPY_AND_ASSIGN(MultipleLockThread); }; #endif } // namespace TEST(SharedMemoryTest, OpenClose) { const uint32 kDataSize = 1024; std::string test_name = "SharedMemoryOpenCloseTest"; // Open two handles to a memory segment, confirm that they are mapped // separately yet point to the same space. SharedMemory memory1; bool rv = memory1.Delete(test_name); EXPECT_TRUE(rv); rv = memory1.Delete(test_name); EXPECT_TRUE(rv); rv = memory1.Open(test_name, false); EXPECT_FALSE(rv); rv = memory1.CreateNamed(test_name, false, kDataSize); EXPECT_TRUE(rv); rv = memory1.Map(kDataSize); EXPECT_TRUE(rv); SharedMemory memory2; rv = memory2.Open(test_name, false); EXPECT_TRUE(rv); rv = memory2.Map(kDataSize); EXPECT_TRUE(rv); EXPECT_NE(memory1.memory(), memory2.memory()); // Compare the pointers. // Make sure we don't segfault. (it actually happened!) ASSERT_NE(memory1.memory(), static_cast<void*>(NULL)); ASSERT_NE(memory2.memory(), static_cast<void*>(NULL)); // Write data to the first memory segment, verify contents of second. memset(memory1.memory(), '1', kDataSize); EXPECT_EQ(memcmp(memory1.memory(), memory2.memory(), kDataSize), 0); // Close the first memory segment, and verify the second has the right data. memory1.Close(); char *start_ptr = static_cast<char *>(memory2.memory()); char *end_ptr = start_ptr + kDataSize; for (char* ptr = start_ptr; ptr < end_ptr; ptr++) EXPECT_EQ(*ptr, '1'); // Close the second memory segment. memory2.Close(); rv = memory1.Delete(test_name); EXPECT_TRUE(rv); rv = memory2.Delete(test_name); EXPECT_TRUE(rv); } TEST(SharedMemoryTest, OpenExclusive) { const uint32 kDataSize = 1024; const uint32 kDataSize2 = 2048; std::ostringstream test_name_stream; test_name_stream << "SharedMemoryOpenExclusiveTest." << Time::Now().ToDoubleT(); std::string test_name = test_name_stream.str(); // Open two handles to a memory segment and check that open_existing works // as expected. SharedMemory memory1; bool rv = memory1.CreateNamed(test_name, false, kDataSize); EXPECT_TRUE(rv); // Memory1 knows it's size because it created it. EXPECT_EQ(memory1.created_size(), kDataSize); rv = memory1.Map(kDataSize); EXPECT_TRUE(rv); memset(memory1.memory(), 'G', kDataSize); SharedMemory memory2; // Should not be able to create if openExisting is false. rv = memory2.CreateNamed(test_name, false, kDataSize2); EXPECT_FALSE(rv); // Should be able to create with openExisting true. rv = memory2.CreateNamed(test_name, true, kDataSize2); EXPECT_TRUE(rv); // Memory2 shouldn't know the size because we didn't create it. EXPECT_EQ(memory2.created_size(), 0U); // We should be able to map the original size. rv = memory2.Map(kDataSize); EXPECT_TRUE(rv); // Verify that opening memory2 didn't truncate or delete memory 1. char *start_ptr = static_cast<char *>(memory2.memory()); char *end_ptr = start_ptr + kDataSize; for (char* ptr = start_ptr; ptr < end_ptr; ptr++) { EXPECT_EQ(*ptr, 'G'); } memory1.Close(); memory2.Close(); rv = memory1.Delete(test_name); EXPECT_TRUE(rv); } // Create a set of N threads to each open a shared memory segment and write to // it. Verify that they are always reading/writing consistent data. TEST(SharedMemoryTest, MultipleThreads) { MultipleThreadMain::CleanUp(); // On POSIX we have a problem when 2 threads try to create the shmem // (a file) at exactly the same time, since create both creates the // file and zerofills it. We solve the problem for this unit test // (make it not flaky) by starting with 1 thread, then // intentionally don't clean up its shmem before running with // kNumThreads. int threadcounts[] = { 1, kNumThreads }; for (size_t i = 0; i < sizeof(threadcounts) / sizeof(threadcounts); i++) { int numthreads = threadcounts[i]; scoped_array<PlatformThreadHandle> thread_handles; scoped_array<MultipleThreadMain*> thread_delegates; thread_handles.reset(new PlatformThreadHandle[numthreads]); thread_delegates.reset(new MultipleThreadMain*[numthreads]); // Spawn the threads. for (int16 index = 0; index < numthreads; index++) { PlatformThreadHandle pth; thread_delegates[index] = new MultipleThreadMain(index); EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth)); thread_handles[index] = pth; } // Wait for the threads to finish. for (int index = 0; index < numthreads; index++) { PlatformThread::Join(thread_handles[index]); delete thread_delegates[index]; } } MultipleThreadMain::CleanUp(); } // TODO(port): this test requires the MultipleLockThread class // (defined above), which requires the ability to pass file // descriptors between processes. We haven't done that yet in Chrome // for POSIX. #if defined(OS_WIN) // Create a set of threads to each open a shared memory segment and write to it // with the lock held. Verify that they are always reading/writing consistent // data. TEST(SharedMemoryTest, Lock) { PlatformThreadHandle thread_handles[kNumThreads]; MultipleLockThread* thread_delegates[kNumThreads]; // Spawn the threads. for (int index = 0; index < kNumThreads; ++index) { PlatformThreadHandle pth; thread_delegates[index] = new MultipleLockThread(index); EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth)); thread_handles[index] = pth; } // Wait for the threads to finish. for (int index = 0; index < kNumThreads; ++index) { PlatformThread::Join(thread_handles[index]); delete thread_delegates[index]; } } #endif // Allocate private (unique) shared memory with an empty string for a // name. Make sure several of them don't point to the same thing as // we might expect if the names are equal. TEST(SharedMemoryTest, AnonymousPrivate) { int i, j; int count = 4; bool rv; const uint32 kDataSize = 8192; scoped_array<SharedMemory> memories(new SharedMemory[count]); scoped_array<int*> pointers(new int*[count]); ASSERT_TRUE(memories.get()); ASSERT_TRUE(pointers.get()); for (i = 0; i < count; i++) { rv = memories[i].CreateAndMapAnonymous(kDataSize); EXPECT_TRUE(rv); int *ptr = static_cast<int*>(memories[i].memory()); EXPECT_TRUE(ptr); pointers[i] = ptr; } for (i = 0; i < count; i++) { // zero out the first int in each except for i; for that one, make it 100. for (j = 0; j < count; j++) { if (i == j) pointers[j][0] = 100; else pointers[j][0] = 0; } // make sure there is no bleeding of the 100 into the other pointers for (j = 0; j < count; j++) { if (i == j) EXPECT_EQ(100, pointers[j][0]); else EXPECT_EQ(0, pointers[j][0]); } } for (int i = 0; i < count; i++) { memories[i].Close(); } } // On POSIX it is especially important we test shmem across processes, // not just across threads. But the test is enabled on all platforms. class SharedMemoryProcessTest : public base::MultiProcessTest { public: static void CleanUp() { SharedMemory memory; memory.Delete(s_test_name_); } static int TaskTestMain() { int errors = 0; mac::ScopedNSAutoreleasePool pool; // noop if not OSX const uint32 kDataSize = 1024; SharedMemory memory; bool rv = memory.CreateNamed(s_test_name_, true, kDataSize); EXPECT_TRUE(rv); if (rv != true) errors++; rv = memory.Map(kDataSize); EXPECT_TRUE(rv); if (rv != true) errors++; int *ptr = static_cast<int*>(memory.memory()); for (int idx = 0; idx < 20; idx++) { memory.Lock(); int i = (1 << 16) + idx; *ptr = i; PlatformThread::Sleep(10); // Short wait. if (*ptr != i) errors++; memory.Unlock(); } memory.Close(); return errors; } private: static const char* const s_test_name_; }; const char* const SharedMemoryProcessTest::s_test_name_ = "MPMem"; #if defined(OS_MACOSX) #define MAYBE_Tasks FLAKY_Tasks #else #define MAYBE_Tasks Tasks #endif TEST_F(SharedMemoryProcessTest, MAYBE_Tasks) { SharedMemoryProcessTest::CleanUp(); base::ProcessHandle handles[kNumTasks]; for (int index = 0; index < kNumTasks; ++index) { handles[index] = SpawnChild("SharedMemoryTestMain", false); } int exit_code = 0; for (int index = 0; index < kNumTasks; ++index) { EXPECT_TRUE(base::WaitForExitCode(handles[index], &exit_code)); EXPECT_TRUE(exit_code == 0); } SharedMemoryProcessTest::CleanUp(); } MULTIPROCESS_TEST_MAIN(SharedMemoryTestMain) { return SharedMemoryProcessTest::TaskTestMain(); } } // namespace base <|endoftext|>
<commit_before>#include "command.hh" #include "shared.hh" #include "eval.hh" #include "attr-path.hh" #include "progress-bar.hh" #include <unistd.h> using namespace nix; struct CmdEdit : InstallableCommand { std::string name() override { return "edit"; } std::string description() override { return "open the Nix expression of a Nix package in $EDITOR"; } Examples examples() override { return { Example{ "To open the Nix expression of the GNU Hello package:", "nix edit nixpkgs.hello" }, }; } void run(ref<Store> store) override { auto state = getEvalState(); auto v = installable->toValue(*state); Value * v2; try { auto dummyArgs = state->allocBindings(0); v2 = findAlongAttrPath(*state, "meta.position", *dummyArgs, *v); } catch (Error &) { throw Error("package '%s' has no source location information", installable->what()); } auto pos = state->forceString(*v2); debug("position is %s", pos); auto colon = pos.rfind(':'); if (colon == std::string::npos) throw Error("cannot parse meta.position attribute '%s'", pos); std::string filename(pos, 0, colon); int lineno; try { lineno = std::stoi(std::string(pos, colon + 1)); } catch (std::invalid_argument e) { throw Error("cannot parse line number '%s'", pos); } auto editor = getEnv("EDITOR", "cat"); Strings args{editor}; if (editor.find("emacs") != std::string::npos || editor.find("nano") != std::string::npos || editor.find("vim") != std::string::npos) args.push_back(fmt("+%d", lineno)); args.push_back(filename); stopProgressBar(); execvp(editor.c_str(), stringsToCharPtrs(args).data()); throw SysError("cannot run editor '%s'", editor); } }; static RegisterCommand r1(make_ref<CmdEdit>()); <commit_msg>Handle arguments in $EDITOR<commit_after>#include "command.hh" #include "shared.hh" #include "eval.hh" #include "attr-path.hh" #include "progress-bar.hh" #include <unistd.h> using namespace nix; struct CmdEdit : InstallableCommand { std::string name() override { return "edit"; } std::string description() override { return "open the Nix expression of a Nix package in $EDITOR"; } Examples examples() override { return { Example{ "To open the Nix expression of the GNU Hello package:", "nix edit nixpkgs.hello" }, }; } void run(ref<Store> store) override { auto state = getEvalState(); auto v = installable->toValue(*state); Value * v2; try { auto dummyArgs = state->allocBindings(0); v2 = findAlongAttrPath(*state, "meta.position", *dummyArgs, *v); } catch (Error &) { throw Error("package '%s' has no source location information", installable->what()); } auto pos = state->forceString(*v2); debug("position is %s", pos); auto colon = pos.rfind(':'); if (colon == std::string::npos) throw Error("cannot parse meta.position attribute '%s'", pos); std::string filename(pos, 0, colon); int lineno; try { lineno = std::stoi(std::string(pos, colon + 1)); } catch (std::invalid_argument e) { throw Error("cannot parse line number '%s'", pos); } auto editor = getEnv("EDITOR", "cat"); auto args = tokenizeString<Strings>(editor); if (editor.find("emacs") != std::string::npos || editor.find("nano") != std::string::npos || editor.find("vim") != std::string::npos) args.push_back(fmt("+%d", lineno)); args.push_back(filename); stopProgressBar(); execvp(args.front().c_str(), stringsToCharPtrs(args).data()); throw SysError("cannot run editor '%s'", editor); } }; static RegisterCommand r1(make_ref<CmdEdit>()); <|endoftext|>
<commit_before>#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "../ext/doctest.h" #include "../nmea_parser.h" using namespace nmea; using doctest::Approx; TEST_CASE("GxRMC parser") { RmcData data; uint8_t crc; // From NL-8002U NAVILOCK Multi GNSS Receiver ublox 8 CHECK(parse("$GNRMC,031649.50,A,4958.42331,N,00909.23445,E,1.039,,250516,,,A*6F", &data, &crc) == true); CHECK(data.talker_id == 'N'); CHECK(data.utc_time_hour == 3); CHECK(data.utc_time_minute == 16); CHECK(Approx(data.utc_time_second) == 49.5); CHECK(data.status == 'A'); CHECK(data.degrees_lat == 49); CHECK(Approx(data.minutes_lat) == 58.42331); CHECK(data.direction_lat == 'N'); CHECK(data.degrees_long == 9); CHECK(Approx(data.minutes_long) == 9.23445); CHECK(data.direction_long == 'E'); CHECK(Approx(data.speed_over_ground) == 1.039); CHECK(Approx(data.track_angle) == 0); CHECK(data.date_day == 25); CHECK(data.date_month == 5); CHECK(data.date_year == 16); CHECK(data.magnetic_variation == 0); CHECK(data.direction_mv == '0'); CHECK(data.mode_indicator == 'A'); // Generic // NMEA 2.3 (and later) examples CHECK(parse("$GPRMC,052848,A,4958.43074,N,00909.25157,E,0.371,,240516,,,A*5C", &data, &crc) == true); CHECK(parse("$GNRMC,052848.40,A,4958.43074,N,00909.25157,E,0.371,0.451,240516,,,D*43", &data, &crc) == true); CHECK(parse("$GLRMC,052848.40,V,4958.43074,S,00909.25157,W,,,240516,,,E*5D", &data, &crc) == true); CHECK(parse("$GARMC,052848.40,A,4958.43074,N,00909.25157,E,,0.451,240516,0.332,E,N*04", &data, &crc) == true); CHECK(parse("$GBRMC,052848.40,A,4958.43074,N,00909.25157,E,0.371,,240516,,,S*76", &data, &crc) == true); CHECK(parse("$GPRMC,052848,A,4958.43074,N,00909.25157,E,0.371,,240516,,,F*5B", &data, &crc) == true); CHECK(parse("$GPRMC,052848,A,4958.43074,N,00909.25157,E,0.371,,240516,,,R*4F", &data, &crc) == true); // NMEA pre 2.3 (no mode indicator) CHECK(parse("$GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,130694,004.2,W*70", &data, &crc) == true); } TEST_CASE("GxGGA parser") { GgaData data; uint8_t crc; // From NL-8002U NAVILOCK Multi GNSS Receiver ublox 8 CHECK(parse("$GNGGA,031649.50,4958.42331,N,00909.23445,E,1,09,1.08,156.1,M,47.7,M,,*4A", &data, &crc) == true); CHECK(data.talker_id == 'N'); CHECK(data.utc_time_hour == 3); CHECK(data.utc_time_minute == 16); CHECK(Approx(data.utc_time_second) == 49.5); CHECK(data.degrees_lat == 49); CHECK(Approx(data.minutes_lat) == 58.42331); CHECK(data.direction_lat == 'N'); CHECK(data.degrees_long == 9); CHECK(Approx(data.minutes_long) == 9.23445); CHECK(data.direction_long == 'E'); CHECK(data.fix_flag == 1); CHECK(data.satellites_used == 9); CHECK(Approx(data.hor_dilution_of_precision) == 1.08); CHECK(Approx(data.altitude) == 156.1); CHECK(Approx(data.geoidal_separation) == 47.7); CHECK(Approx(data.age_of_dgps_data) == 0); CHECK(data.reference_station_id == 0); // Generic CHECK(parse("$GPGGA,152835.00,5554.0114,N,03732.5007,E,1,13,00.8,170.4,M,14.5,M,,*5E", &data, &crc) == true); CHECK(parse("$GNGGA,150947.00,5554.0083,N,03732.502,E,1,15,00.6,190.6,M,14.5,M,,*78", &data, &crc) == true); CHECK(parse("$GPGGA,151114.00,5554.0093,N,03732.5027,E,1,11,00.7,196.4,M,14.5,M,,*5E", &data, &crc) == true); CHECK(parse("$GLGGA,150626.00,5554.0097,N,03732.4979,E,1,06,01.2,192.6,M,14.5,M,,*46", &data, &crc) == true); } TEST_CASE("GxGSV parser") { GsvData data; uint8_t crc; // From NL-8002U NAVILOCK Multi GNSS Receiver ublox 8 // GPS satellites // Check first message (1/3) CHECK(parse("$GPGSV,3,1,12,02,36,299,24,03,17,119,10,05,05,298,,06,51,230,23*77", &data, &crc) == true); CHECK(data.talker_id == 'P'); CHECK(data.total_messages == 3); CHECK(data.message_number == 1); CHECK(data.satellites_in_view == 12); CHECK(data.first.has_data == true); CHECK(data.first.satellite_prn_number == 2); CHECK(data.first.elevation == 36); CHECK(data.first.azimuth == 299); CHECK(data.first.snr == 24); CHECK(data.second.has_data == true); CHECK(data.second.satellite_prn_number == 3); CHECK(data.second.elevation == 17); CHECK(data.second.azimuth == 119); CHECK(data.second.snr == 10); CHECK(data.third.has_data == true); CHECK(data.third.satellite_prn_number == 5); CHECK(data.third.elevation == 5); CHECK(data.third.azimuth == 298); CHECK(data.third.snr == 0); CHECK(data.fourth.has_data == true); CHECK(data.fourth.satellite_prn_number == 6); CHECK(data.fourth.elevation == 51); CHECK(data.fourth.azimuth == 230); CHECK(data.fourth.snr == 23); CHECK(crc == 0x77); // Check second message (2/3) CHECK(parse("$GPGSV,3,2,12,07,42,173,22,09,81,053,16,16,15,069,,19,00,233,*78", &data, &crc) == true); CHECK(data.talker_id == 'P'); CHECK(data.total_messages == 3); CHECK(data.message_number == 2); CHECK(data.satellites_in_view == 12); CHECK(data.first.has_data == true); CHECK(data.first.satellite_prn_number == 7); CHECK(data.first.elevation == 42); CHECK(data.first.azimuth == 173); CHECK(data.first.snr == 22); CHECK(data.second.has_data == true); CHECK(data.second.satellite_prn_number == 9); CHECK(data.second.elevation == 81); CHECK(data.second.azimuth == 53); CHECK(data.second.snr == 16); CHECK(data.third.has_data == true); CHECK(data.third.satellite_prn_number == 16); CHECK(data.third.elevation == 15); CHECK(data.third.azimuth == 69); CHECK(data.third.snr == 0); CHECK(data.fourth.has_data == true); CHECK(data.fourth.satellite_prn_number == 19); CHECK(data.fourth.elevation == 0); CHECK(data.fourth.azimuth == 233); CHECK(data.fourth.snr == 0); CHECK(crc == 0x78); // Check third message (3/3) CHECK(parse("$GPGSV,3,3,12,23,49,068,19,26,12,041,,29,04,345,,30,17,190,18*7B", &data, &crc) == true); CHECK(data.talker_id == 'P'); CHECK(data.total_messages == 3); CHECK(data.message_number == 3); CHECK(data.satellites_in_view == 12); CHECK(data.first.has_data == true); CHECK(data.first.satellite_prn_number == 23); CHECK(data.first.elevation == 49); CHECK(data.first.azimuth == 68); CHECK(data.first.snr == 19); CHECK(data.second.has_data == true); CHECK(data.second.satellite_prn_number == 26); CHECK(data.second.elevation == 12); CHECK(data.second.azimuth == 41); CHECK(data.second.snr == 0); CHECK(data.third.has_data == true); CHECK(data.third.satellite_prn_number == 29); CHECK(data.third.elevation == 4); CHECK(data.third.azimuth == 345); CHECK(data.third.snr == 0); CHECK(data.fourth.has_data == true); CHECK(data.fourth.satellite_prn_number == 30); CHECK(data.fourth.elevation == 17); CHECK(data.fourth.azimuth == 190); CHECK(data.fourth.snr == 18); CHECK(crc == 0x7B); // GLONASS satellites CHECK(parse("$GLGSV,3,1,09,65,21,293,23,72,05,092,,73,48,073,19,74,36,147,24*6A", &data, &crc) == true); CHECK(parse("$GLGSV,3,2,09,80,13,022,,81,06,354,,87,24,250,26,88,30,305,*65", &data, &crc) == true); // Check last message (3/3) CHECK(parse("$GLGSV,3,3,09,95,13,022,*52", &data, &crc) == true); CHECK(data.talker_id == 'L'); CHECK(data.total_messages == 3); CHECK(data.message_number == 3); CHECK(data.satellites_in_view == 9); CHECK(data.first.has_data == true); CHECK(data.first.satellite_prn_number == 95); CHECK(data.first.elevation == 13); CHECK(data.first.azimuth == 22); CHECK(data.first.snr == 0); CHECK(data.second.has_data == false); CHECK(data.third.has_data == false); CHECK(data.fourth.has_data == false); CHECK(crc == 0x52); // Generic CHECK(parse("$GPGSV,3,1,12,11,52,219,48,12,09,021,40,14,34,057,47,17,25,306,45*72", &data, &crc) == true); CHECK(parse("$GPGSV,3,2,12,20,46,274,48,23,14,223,45,24,67,214,49,31,35,123,48*75", &data, &crc) == true); CHECK(parse("$GPGSV,3,3,12,32,78,266,51,33,11,238,39,37,15,197,37,39,25,195,00*7A", &data, &crc) == true); CHECK(parse("$GLGSV,2,1,07,65,36,079,51,66,77,331,53,74,15,014,42,75,41,067,49*65", &data, &crc) == true); CHECK(parse("$GLGSV,2,2,07,76,24,132,50,82,41,296,48,83,13,346,43*78", &data, &crc) == true); } TEST_CASE("Checksum calculation") { CHECK(calc_checksum("$GNRMC,031649.50,A,4958.42331,N,00909.23445,E,1.039,,250516,,,A*6F") == 0x6F); CHECK(calc_checksum("$GNGGA,031649.50,4958.42331,N,00909.23445,E,1,09,1.08,156.1,M,47.7,M,,*4A") == 0x4A); CHECK(calc_checksum("$GPGSV,3,2,12,07,42,173,22,09,81,053,16,16,15,069,,19,00,233,*78") == 0x78); } <commit_msg>Moved file<commit_after><|endoftext|>
<commit_before> #include <configure/Application.hpp> #include <boost/filesystem.hpp> #include <fstream> namespace fs = boost::filesystem; typedef configure::Application app_t; BOOST_AUTO_TEST_CASE(invalid_args) { BOOST_CHECK_THROW(app_t(0, nullptr), std::exception); BOOST_CHECK_THROW(app_t(-1, nullptr), std::exception); BOOST_CHECK_THROW(app_t(std::vector<std::string>()), std::exception); } struct Env { fs::path _dir; fs::path _old_cwd; Env() : _dir{fs::temp_directory_path() / fs::unique_path()} , _old_cwd{fs::current_path()} { fs::create_directories(_dir); fs::current_path(_dir); } ~Env() { fs::current_path(_old_cwd); fs::remove_all(_dir); } void add_project() { std::ofstream out{(_dir / "configure.lua").string()}; out << "something"; out.close(); } fs::path const& dir() { return _dir; } }; BOOST_AUTO_TEST_CASE(missing_project) { Env env; BOOST_CHECK_THROW(app_t({"pif"}), std::exception); } BOOST_AUTO_TEST_CASE(no_build_dir) { Env env; env.add_project(); app_t app({"pif"}); BOOST_CHECK_EQUAL(app.build_directories().size(), 0); BOOST_CHECK_EQUAL(app.project_directory(), env.dir()); } <commit_msg>Add missing include.<commit_after> #include <configure/Application.hpp> #include <boost/filesystem.hpp> #include <fstream> #include <vector> namespace fs = boost::filesystem; typedef configure::Application app_t; BOOST_AUTO_TEST_CASE(invalid_args) { BOOST_CHECK_THROW(app_t(0, nullptr), std::exception); BOOST_CHECK_THROW(app_t(-1, nullptr), std::exception); BOOST_CHECK_THROW(app_t(std::vector<std::string>()), std::exception); } struct Env { fs::path _dir; fs::path _old_cwd; Env() : _dir{fs::temp_directory_path() / fs::unique_path()} , _old_cwd{fs::current_path()} { fs::create_directories(_dir); fs::current_path(_dir); } ~Env() { fs::current_path(_old_cwd); fs::remove_all(_dir); } void add_project() { std::ofstream out{(_dir / "configure.lua").string()}; out << "something"; out.close(); } fs::path const& dir() { return _dir; } }; BOOST_AUTO_TEST_CASE(missing_project) { Env env; BOOST_CHECK_THROW(app_t({"pif"}), std::exception); } BOOST_AUTO_TEST_CASE(no_build_dir) { Env env; env.add_project(); app_t app({"pif"}); BOOST_CHECK_EQUAL(app.build_directories().size(), 0); BOOST_CHECK_EQUAL(app.project_directory(), env.dir()); } <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include "media/types.h" using namespace std; const int arraySize = 50; /* * Function for inserting a new medium (Medium, Video, Book, ...) * to an array of Medium pointers. */ void addMedia(Medium* medium, Medium* media[], int arraySize) { int i; for (i = 0; i < arraySize; i++) { if (media[i] == NULL) { media[i] = medium; break; } } if (i == arraySize) { cerr << "Error: Exeeded array size of " << arraySize << " elements!" << endl; } } int main() { char command = 'q'; Medium* media[arraySize]; int signature = 0; // Initialize array with NULL values int i; for (i = 0; i < arraySize; i++) { media[i] = NULL; } while (true) { cout << "What do you want to do?" << endl << "m: create new medium" << endl << "b: create new book" << endl << "v: create new video" << endl << "l: list all media" << endl << "e SIGNATURE: borrow media with the given signature" << endl << "r SIGNATURE: return media with the given signature" << endl << "q: quit" << endl << endl << "Command: "; cin >> command; cout << endl; switch (command) { case 'm': addMedia(new Medium(), media, arraySize); break; case 'b': addMedia(new Book(), media, arraySize); break; case 'v': addMedia(new Video(), media, arraySize); break; case 'l': cout << "Media Library" << endl; int i; for (i = 0; i < arraySize; i++) { if (media[i] == NULL) { break; } media[i]->print(); } break; case 'e': cin >> signature; for (i = 0; (i < arraySize) && (media[i] != NULL); i++) { if (media[i]->getSignature() == signature) { media[i]->lendOut(); } } break; case 'r': cin >> signature; for (i = 0; (i < arraySize) && (media[i] != NULL); i++) { if (media[i]->getSignature() == signature) { media[i]->handIn(); } } break; case 'q': // Clean up for (i = 0; (i < arraySize) && (media[i] != NULL); i++) { delete media[i]; } exit(EXIT_SUCCESS); } cout << endl; } } <commit_msg>Adds better NULL initialization of array.<commit_after>#include <iostream> #include <stdlib.h> #include "media/types.h" using namespace std; const int arraySize = 50; /* * Function for inserting a new medium (Medium, Video, Book, ...) * to an array of Medium pointers. */ void addMedia(Medium* medium, Medium* media[], int arraySize) { int i; for (i = 0; i < arraySize; i++) { if (media[i] == NULL) { media[i] = medium; break; } } if (i == arraySize) { cerr << "Error: Exeeded array size of " << arraySize << " elements!" << endl; } } int main() { char command = 'q'; Medium* media[arraySize] = {NULL}; int signature = 0; while (true) { cout << "What do you want to do?" << endl << "m: create new medium" << endl << "b: create new book" << endl << "v: create new video" << endl << "l: list all media" << endl << "e SIGNATURE: borrow media with the given signature" << endl << "r SIGNATURE: return media with the given signature" << endl << "q: quit" << endl << endl << "Command: "; cin >> command; cout << endl; switch (command) { case 'm': addMedia(new Medium(), media, arraySize); break; case 'b': addMedia(new Book(), media, arraySize); break; case 'v': addMedia(new Video(), media, arraySize); break; case 'l': cout << "Media Library" << endl; int i; for (i = 0; i < arraySize; i++) { if (media[i] == NULL) { break; } media[i]->print(); } break; case 'e': cin >> signature; for (i = 0; (i < arraySize) && (media[i] != NULL); i++) { if (media[i]->getSignature() == signature) { media[i]->lendOut(); } } break; case 'r': cin >> signature; for (i = 0; (i < arraySize) && (media[i] != NULL); i++) { if (media[i]->getSignature() == signature) { media[i]->handIn(); } } break; case 'q': // Clean up for (i = 0; (i < arraySize) && (media[i] != NULL); i++) { delete media[i]; } exit(EXIT_SUCCESS); } cout << endl; } } <|endoftext|>
<commit_before>#include <iostream> #include <queue> #include <stdio.h> using namespace std; #include "Binary-tree.hpp" #include "pretty-print.hpp" // Функция создает сбалансированное дерево и возращает корневой узел дерева Node* createBalancedBTree(Node** node, int *&value, int cnt) { if (cnt <= 0) return NULL; if (node == NULL) { Node* tmp = NULL; node = &tmp; } if ((*node) == NULL) { (*node) = new Node(*value); ++value; --cnt; } int cntr = cnt / 2; int cntl = cnt - cntr; if (cntl > 0) createBalancedBTree(&(*node)->left, value, cntl); if (cntr > 0) createBalancedBTree(&(*node)->right, value, cntr); return (*node); } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* insertSearchBTree(Node** node, int value) { if ((*node) == NULL) { (*node) = new Node(value); return *node; } if ((*node)->data > value) { return insertSearchBTree(&(*node)->left, value); } else if ((*node)->data < value) { return insertSearchBTree(&(*node)->right, value); } else { std::cout << "something going wrong! " << value << endl; } } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* createSearchBTree(int *array, int size) { Node* node = NULL; for (int i = 0; i < size; ++i) insertSearchBTree(&node, array[i]); return node; } void findRowsSumm(Node *node, int *rows, int currentDepth) { if (node == NULL) return; rows[currentDepth] += node->data; findRowsSumm(node->left, rows, currentDepth+1); findRowsSumm(node->right, rows, currentDepth+1); } int findRowWithMaxSumm(Node *node, int rowsCount) { if (node == NULL) return -1; int *rowsSumm = new int[rowsCount]; for (int i = 0; i < rowsCount; ++i) rowsSumm[i] = 0; findRowsSumm(node, rowsSumm, 0); int maxRow = -1; int maxValue = 0; for (int i = 0; i < rowsCount; i++) { if ((rowsSumm[i] >= 0) && (rowsSumm[i] > maxValue)) { maxRow = i; maxValue = rowsSumm[i]; } } delete [] rowsSumm; return maxRow; } void destroyTree(Node *node) { if (node != NULL) { destroyTree(node->left); destroyTree(node->right); } delete node; } int main() { int data[] = {35, 55, 15, 50, 40, 0, 10, 45, 5, 30, 25}; int size = sizeof(data) / (sizeof(data[0])); cout << "Exer.1 - Balanced B-Tree" << endl; int *it = (int *)&data; Node* balancedBTreeRoot = createBalancedBTree(NULL, it, size); printPretty(balancedBTreeRoot); destroyTree(balancedBTreeRoot); cout << endl; cout << "Exer.2 - Search B-Tree" << endl; Node* searchBTreeRoot = createSearchBTree(data, size); printPretty(searchBTreeRoot); // destroyTree(searchBTreeRoot); cout << endl; cout << "Exer.6 - Find row with max summ of values from search B-Tree" << endl; printPretty(searchBTreeRoot); int row = findRowWithMaxSumm(searchBTreeRoot, size); destroyTree(searchBTreeRoot); cout << "Count starts from 0, -1 = no values found" << endl; cout << "Answer is " << row << endl; cout << endl; return 0; } <commit_msg>lab5 simplify<commit_after>#include <iostream> #include <queue> #include <stdio.h> using namespace std; #include "Binary-tree.hpp" #include "pretty-print.hpp" // Функция создает сбалансированное дерево и возращает корневой узел дерева Node* createBalancedBTree(Node** node, int *&value, int cnt) { if (cnt <= 0) return NULL; if (node == NULL) { Node* tmp = NULL; node = &tmp; } if ((*node) == NULL) { (*node) = new Node(*value); ++value; --cnt; } int cntr = cnt / 2; int cntl = cnt - cntr; if (cntl > 0) createBalancedBTree(&(*node)->left, value, cntl); if (cntr > 0) createBalancedBTree(&(*node)->right, value, cntr); return (*node); } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* insertSearchBTree(Node** node, int value) { if ((*node) == NULL) { (*node) = new Node(value); return *node; } if ((*node)->data > value) { return insertSearchBTree(&(*node)->left, value); } else if ((*node)->data < value) { return insertSearchBTree(&(*node)->right, value); } else { std::cout << "something going wrong! " << value << endl; } } // Функция создает бинарное дерево поиска и возращает корневой узел дерева Node* createSearchBTree(int *array, int size) { Node* node = NULL; for (int i = 0; i < size; ++i) insertSearchBTree(&node, array[i]); return node; } void findRowsSumm(Node *node, int *rows, int currentDepth) { if (node == NULL) return; rows[currentDepth] += node->data; findRowsSumm(node->left, rows, currentDepth+1); findRowsSumm(node->right, rows, currentDepth+1); } int findRowWithMaxSumm(Node *node, int rowsCount) { if (node == NULL) return -1; int *rowsSumm = new int[rowsCount]; for (int i = 0; i < rowsCount; ++i) rowsSumm[i] = 0; findRowsSumm(node, rowsSumm, 0); int maxRow = -1; int maxValue = 0; for (int i = 0; i < rowsCount; i++) { if ((rowsSumm[i] >= 0) && (rowsSumm[i] > maxValue)) { maxRow = i; maxValue = rowsSumm[i]; } } delete [] rowsSumm; return maxRow; } void free(Node *node) { if (node != NULL) { free(node->left); free(node->right); } delete node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ Node * minValueNode(Node* node) { Node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current; } /* Given a binary search tree and a key, this function deletes the key and returns the new root */ Node* deleteNode(Node **root, int data) { // base case if ((*root) == NULL) return (*root); // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (data < (*root)->data) (*root)->left = deleteNode(&(*root)->left, data); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (data > (*root)->data) (*root)->right = deleteNode(&(*root)->right, data); // if key is same as root's key, then This is the node // to be deleted else { // node with only one child or no child if ((*root)->left == NULL) { Node *temp = (*root)->right; free((*root)); return temp; } else if ((*root)->right == NULL) { Node *temp = (*root)->left; free((*root)); return temp; } // node with two children: Get the inorder successor (smallest // in the right subtree) Node * temp = minValueNode((*root)->right); // Copy the inorder successor's content to this node (*root)->data = temp->data; // Delete the inorder successor (*root)->right = deleteNode(&(*root)->right, temp->data); } return (*root); } void exer1(int *data, int size) { cout << "Exer.1 - Balanced B-Tree" << endl; int *it = (int *)&(*data); Node* balancedBTreeRoot = createBalancedBTree(NULL, it, size); printPretty(balancedBTreeRoot); free(balancedBTreeRoot); cout << endl; } void exer2(int *data, int size) { cout << "Exer.2 - Search B-Tree" << endl; Node* searchBTreeRoot = createSearchBTree(data, size); printPretty(searchBTreeRoot); free(searchBTreeRoot); cout << endl; } void exer3(int *data, int size) { cout << "Exer.3 - Delete nodes from B-Tree" << endl; Node* root = createSearchBTree(data, size); cout << "Delete node with one children" << endl; deleteNode(&root, 5); printPretty(root); cout << endl; cout << "Delete node with two childrens" << endl; deleteNode(&root, 15); printPretty(root); //cout << "Delete terminal node(root)" << endl; //root = deleteNode(&root, 35); //printPretty(root); free(root); cout << endl; } void exer6(int *data, int size) { cout << "Exer.6 - Find row with max summ" << endl; cout << "Rows indexing start from 0, -1 = no values found" << endl; int *it6 = (int *)&(*data); Node * tree6 = createBalancedBTree(NULL, it6, size); printPretty(tree6); int row = findRowWithMaxSumm(tree6, size); free(tree6); cout << "Answer is " << row << endl; cout << endl; } int main() { int data[] = {35, 55, 15, 50, 40, 0, 10, 45, 5, 30, 25}; int size = sizeof(data) / (sizeof(data[0])); exer1(data, size); exer2(data, size); exer3(data, size); // exer4(data, size); // exer5(data, size); exer6(data, size); return 0; } <|endoftext|>
<commit_before>#ifndef GNR_LIGHTPTR_HPP # define GNR_LIGHTPTR_HPP # pragma once #include <cassert> #include <atomic> #include <memory> #include <type_traits> #include <utility> namespace gnr { namespace detail { namespace light_ptr { using counter_type = unsigned; using atomic_type = std::atomic<counter_type>; template <typename T> using deleter_type = void (*)(T*); template <typename U> struct ref_type { using type = U&; }; template <> struct ref_type<void> { using type = void; }; } } template <typename T> class light_ptr { template <typename U, typename V> struct deletion_type { using type = V; }; template <typename U, typename V> struct deletion_type<U[], V> { using type = V[]; }; template <typename U, typename V, std::size_t N> struct deletion_type<U[N], V> { using type = V[]; }; using element_type = std::remove_extent_t<T>; using deleter_type = detail::light_ptr::deleter_type<element_type>; class counter_base { friend class light_ptr; using invoker_type = void (*)(counter_base*, element_type*) noexcept; detail::light_ptr::atomic_type counter_{}; invoker_type const invoker_; protected: explicit counter_base(detail::light_ptr::counter_type const c, invoker_type const invoker) noexcept : counter_(c), invoker_(invoker) { } public: template <typename U> typename std::enable_if<!std::is_void<U>{}>::type dec_ref(U* const ptr) noexcept { if (detail::light_ptr::counter_type(1) == counter_.fetch_sub(detail::light_ptr::counter_type(1), std::memory_order_relaxed)) { using type_must_be_complete = char[sizeof(U) ? 1 : -1]; (void)sizeof(type_must_be_complete); invoker_(this, ptr); } // else do nothing } template <typename U> typename std::enable_if<std::is_void<U>{}>::type dec_ref(U* const ptr) noexcept { if (detail::light_ptr::counter_type(1) == counter_.fetch_sub(detail::light_ptr::counter_type(1), std::memory_order_relaxed)) { invoker_(this, ptr); } // else do nothing } void inc_ref() noexcept { counter_.fetch_add(detail::light_ptr::counter_type(1), std::memory_order_relaxed); } }; template <typename D> class counter : public counter_base { std::decay_t<D> const d_; static void invoked(counter_base* const ptr, element_type* const e) noexcept { auto const c(static_cast<counter<D>*>(ptr)); // invoke deleter on the element c->d_(e); // delete from a static member function delete c; } public: explicit counter(detail::light_ptr::counter_type const c, D&& d) noexcept : counter_base(c, invoked), d_(std::forward<D>(d)) { } }; private: template <typename U> friend struct std::hash; counter_base* counter_{}; element_type* ptr_; public: light_ptr() = default; template <typename U> explicit light_ptr(U* const p) { reset(p); } template <typename U, typename D> explicit light_ptr(U* const p, D&& d) { reset(p, std::forward<D>(d)); } light_ptr(light_ptr const& other) noexcept { *this = other; } light_ptr(light_ptr&& other) noexcept { *this = std::move(other); } ~light_ptr() noexcept { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing } light_ptr& operator=(light_ptr const& rhs) noexcept { if (*this != rhs) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing if ((counter_ = rhs.counter_)) { counter_->inc_ref(); } // else do nothing ptr_ = rhs.ptr_; } // else do nothing return *this; } light_ptr& operator=(light_ptr&& rhs) noexcept { counter_ = rhs.counter_; rhs.counter_ = nullptr; ptr_ = rhs.ptr_; return *this; } light_ptr& operator=(std::nullptr_t const) noexcept { reset(); return *this; } bool operator<(light_ptr const& rhs) const noexcept { return counter_ < rhs.counter_; } bool operator==(light_ptr const& rhs) const noexcept { return counter_ == rhs.counter_; } bool operator!=(light_ptr const& rhs) const noexcept { return !operator==(rhs); } bool operator==(std::nullptr_t const) const noexcept { return !counter_; } bool operator!=(std::nullptr_t const) const noexcept { return counter_; } explicit operator bool() const noexcept { return counter_; } typename detail::light_ptr::ref_type<T>::type operator*() const noexcept { return *reinterpret_cast<T*>(ptr_); } T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); } template <typename U = T, typename = typename std::enable_if<std::is_array<U>{}>::type> typename detail::light_ptr::ref_type<element_type>::type operator[]( std::size_t const i) const noexcept { return ptr_[i]; } element_type* get() const noexcept { return ptr_; } void reset() noexcept { reset(nullptr); } void reset(std::nullptr_t const) noexcept { if (counter_) { counter_->dec_ref(ptr_); counter_ = nullptr; } // else do nothing } template <typename U> void reset(U* const p) { reset(p, [](element_type* const p) noexcept { std::default_delete<typename deletion_type<T, U>::type>()( static_cast<U*>(p) ); } ); } template <typename U, typename D> void reset(U* const p, D&& d) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing counter_ = p ? new counter<D>( detail::light_ptr::counter_type(1), std::forward<D>(d) ) : nullptr; ptr_ = p; } void swap(light_ptr& other) noexcept { std::swap(counter_, other.counter_); std::swap(ptr_, other.ptr_); } bool unique() const noexcept { return detail::light_ptr::counter_type(1) == use_count(); } detail::light_ptr::counter_type use_count() const noexcept { return counter_ ? counter_->counter_.load(std::memory_order_relaxed) : detail::light_ptr::counter_type{}; } }; template<class T, class ...Args> inline light_ptr<T> make_light(Args&& ...args) { return light_ptr<T>(new T(std::forward<Args>(args)...)); } } namespace std { template <typename T> struct hash<gnr::light_ptr<T> > { size_t operator()(gnr::light_ptr<T> const& l) const noexcept { return hash<typename gnr::light_ptr<T>::element_type*>()(l.ptr_); } }; } #endif // GNR_LIGHTPTR_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_LIGHTPTR_HPP # define GNR_LIGHTPTR_HPP # pragma once #include <cassert> #include <atomic> #include <memory> #include <type_traits> #include <utility> namespace gnr { namespace { using counter_type = unsigned; using atomic_counter_type = std::atomic<counter_type>; template <typename T> using deleter_type = void (*)(T*); template <typename U> struct ref_type { using type = U&; }; template <> struct ref_type<void> { using type = void; }; template <typename U> using ref_type_t = typename ref_type<U>::type; } template <typename T> class light_ptr { template <typename U, typename V> struct deletion_type { using type = V; }; template <typename U, typename V> struct deletion_type<U[], V> { using type = V[]; }; template <typename U, typename V, std::size_t N> struct deletion_type<U[N], V> { using type = V[]; }; template <typename ...A> using deletion_type_t = typename deletion_type<A...>::type; using element_type = std::remove_extent_t<T>; class counter_base { friend class light_ptr; using invoker_type = void (*)(counter_base*, element_type*) noexcept; atomic_counter_type counter_{}; invoker_type const invoker_; protected: explicit counter_base(counter_type const c, invoker_type const invoker) noexcept : counter_(c), invoker_(invoker) { } public: template <typename U> std::enable_if_t<!std::is_void<U>{}> dec_ref(U* const ptr) noexcept { if (counter_type(1) == counter_.fetch_sub(counter_type(1), std::memory_order_relaxed)) { using type_must_be_complete = char[sizeof(U) ? 1 : -1]; (void)sizeof(type_must_be_complete); invoker_(this, ptr); } // else do nothing } template <typename U> std::enable_if_t<std::is_void<U>{}> dec_ref(U* const ptr) noexcept { if (counter_type(1) == counter_.fetch_sub(counter_type(1), std::memory_order_relaxed)) { invoker_(this, ptr); } // else do nothing } void inc_ref() noexcept { counter_.fetch_add(counter_type(1), std::memory_order_relaxed); } }; template <typename D> class counter : public counter_base { std::decay_t<D> const d_; static void invoked(counter_base* const ptr, element_type* const e) noexcept { auto const c(static_cast<counter<D>*>(ptr)); // invoke deleter on the element c->d_(e); // delete from a static member function delete c; } public: explicit counter(counter_type const c, D&& d) noexcept : counter_base(c, invoked), d_(std::forward<D>(d)) { } }; private: template <typename U> friend struct std::hash; counter_base* counter_{}; element_type* ptr_; public: light_ptr() = default; template <typename U> explicit light_ptr(U* const p) { reset(p); } template <typename U, typename D> explicit light_ptr(U* const p, D&& d) { reset(p, std::forward<D>(d)); } light_ptr(light_ptr const& other) noexcept { *this = other; } light_ptr(light_ptr&& other) noexcept { *this = std::move(other); } ~light_ptr() noexcept { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing } light_ptr& operator=(light_ptr const& rhs) noexcept { if (*this != rhs) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing if ((counter_ = rhs.counter_)) { counter_->inc_ref(); } // else do nothing ptr_ = rhs.ptr_; } // else do nothing return *this; } light_ptr& operator=(light_ptr&& rhs) noexcept { counter_ = rhs.counter_; rhs.counter_ = nullptr; ptr_ = rhs.ptr_; return *this; } light_ptr& operator=(std::nullptr_t const) noexcept { reset(); return *this; } bool operator<(light_ptr const& rhs) const noexcept { return counter_ < rhs.counter_; } bool operator==(light_ptr const& rhs) const noexcept { return counter_ == rhs.counter_; } bool operator!=(light_ptr const& rhs) const noexcept { return !operator==(rhs); } bool operator==(std::nullptr_t const) const noexcept { return !counter_; } bool operator!=(std::nullptr_t const) const noexcept { return counter_; } explicit operator bool() const noexcept { return counter_; } ref_type_t<T> operator*() const noexcept { return *reinterpret_cast<T*>(ptr_); } auto operator->() const noexcept { return reinterpret_cast<T*>(ptr_); } template <typename U = T, typename = std::enable_if_t<std::is_array<U>{}> > ref_type_t<element_type> operator[](std::size_t const i) const noexcept { return ptr_[i]; } auto get() const noexcept { return ptr_; } void reset() noexcept { reset(nullptr); } void reset(std::nullptr_t const) noexcept { if (counter_) { counter_->dec_ref(ptr_); counter_ = nullptr; } // else do nothing } template <typename U> void reset(U* const p) { reset(p, [](element_type* const p) noexcept { std::default_delete<deletion_type_t<T, U>>()( static_cast<U*>(p) ); } ); } template <typename U, typename D> void reset(U* const p, D&& d) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing counter_ = p ? new counter<D>(counter_type(1), std::forward<D>(d)) : nullptr; ptr_ = p; } void swap(light_ptr& other) noexcept { std::swap(counter_, other.counter_); std::swap(ptr_, other.ptr_); } bool unique() const noexcept { return counter_type(1) == use_count(); } counter_type use_count() const noexcept { return counter_ ? counter_->counter_.load(std::memory_order_relaxed) : counter_type{}; } }; template<class T, typename ...A> inline light_ptr<T> make_light(A&& ...args) { return light_ptr<T>(new T(std::forward<A>(args)...)); } } namespace std { template <typename T> struct hash<gnr::light_ptr<T> > { size_t operator()(gnr::light_ptr<T> const& l) const noexcept { return hash<typename gnr::light_ptr<T>::element_type*>()(l.ptr_); } }; } #endif // GNR_LIGHTPTR_HPP <|endoftext|>
<commit_before>#pragma once #ifndef LIGHTPTR_HPP # define LIGHTPTR_HPP #include <cassert> #include <atomic> #include <memory> #include <utility> #include <type_traits> namespace generic { namespace detail { using counter_type = unsigned; using atomic_type = ::std::atomic<counter_type>; template <typename T> using deleter_type = void (*)(T*); template <typename T> using invoker_type = void (*)(void*, T*); template <typename U> struct ref_type { using type = U&; }; template <> struct ref_type<void> { using type = void; }; } template <typename T> struct light_ptr { template <typename U, typename V> struct deletion_type { using type = V; }; template <typename U, typename V> struct deletion_type<U[], V> { using type = V[]; }; template <typename U, typename V, ::std::size_t N> struct deletion_type<U[N], V> { using type = V[]; }; template <typename U> struct remove_array { using type = U; }; template <typename U> struct remove_array<U[]> { using type = U; }; template <typename U, ::std::size_t N> struct remove_array<U[N]> { using type = U; }; using element_type = typename remove_array<T>::type; using deleter_type = detail::deleter_type<element_type>; using invoker_type = detail::invoker_type<element_type>; struct counter_base { explicit counter_base(detail::counter_type c, void* counter_ptr, invoker_type invoker) noexcept : counter_(c), counter_ptr_(counter_ptr), invoker_(invoker) { } template <typename U> typename ::std::enable_if<!::std::is_void<U>{}>::type dec_ref(U* const ptr) { if (detail::counter_type(1) == counter_.fetch_sub(detail::counter_type(1), ::std::memory_order_relaxed)) { typedef char type_must_be_complete[sizeof(U) ? 1 : -1]; (void)sizeof(type_must_be_complete); invoker_(counter_ptr_, ptr); } // else do nothing } template <typename U> typename ::std::enable_if<::std::is_void<U>{}>::type dec_ref(U* const ptr) { if (detail::counter_type(1) == counter_.fetch_sub(detail::counter_type(1), ::std::memory_order_relaxed)) { invoker_(counter_ptr_, ptr); } // else do nothing } void inc_ref() noexcept { //assert(counter_ptr); counter_.fetch_add(detail::counter_type(1), ::std::memory_order_relaxed); } detail::atomic_type counter_{}; void* counter_ptr_; invoker_type invoker_; }; template <typename U> struct counter : counter_base { explicit counter(detail::counter_type c, U&& d) noexcept : counter_base(c, this, invoker), d_(::std::forward<U>(d)) { } private: static void invoker(void* const ptr, element_type* const e) { U const d(::std::move(static_cast<counter<U>*>(ptr)->d_)); delete static_cast<counter<U>*>(ptr); d(e); } private: U d_; }; light_ptr() = default; template <typename U> explicit light_ptr(U* const p, deleter_type const d = default_deleter<U>) { reset(p, d); } ~light_ptr() { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing } light_ptr(light_ptr const& other) { *this = other; } light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); } light_ptr& operator=(light_ptr const& rhs) { if (*this != rhs) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing counter_ = rhs.counter_; ptr_ = rhs.ptr_; if (counter_) { counter_->inc_ref(); } // else do nothing } // else do nothing return *this; } light_ptr& operator=(light_ptr&& rhs) noexcept { counter_ = rhs.counter_; ptr_ = rhs.ptr_; rhs.counter_ = nullptr; rhs.ptr_ = nullptr; return *this; } light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); } bool operator<(light_ptr const& rhs) const noexcept { return get() < rhs.get(); } bool operator==(light_ptr const& rhs) const noexcept { return counter_ == rhs.counter_; } bool operator!=(light_ptr const& rhs) const noexcept { return !operator==(rhs); } bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; } bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; } explicit operator bool() const noexcept { return ptr_; } typename detail::ref_type<T>::type operator*() const noexcept { return *static_cast<T*>(static_cast<void*>(ptr_)); } T* operator->() const noexcept { return static_cast<T*>(static_cast<void*>(ptr_)); } element_type* get() const noexcept { return ptr_; } void reset() { reset(nullptr); } void reset(::std::nullptr_t const) { if (counter_) { counter_->dec_ref(ptr_); counter_ = {}; } // else do nothing ptr_ = {}; } template <typename U> static void default_deleter(element_type* const p) { ::std::default_delete<typename deletion_type<T, U>::type>()( static_cast<U*>(p)); } template <typename U, typename D> void reset(U* const p, D&& d = default_deleter<U>) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d)); ptr_ = p; } void swap(light_ptr& other) noexcept { ::std::swap(counter_, other.counter_); ::std::swap(ptr_, other.ptr_); } bool unique() const noexcept { return detail::counter_type(1) == use_count(); } detail::counter_type use_count() const noexcept { return counter_ ? counter_->counter_ptr_->load(::std::memory_order_relaxed) : detail::counter_type{}; } private: counter_base* counter_{}; element_type* ptr_{}; }; template<class T, class ...Args> inline light_ptr<T> make_light(Args&& ...args) { return light_ptr<T>(new T(::std::forward<Args>(args)...)); } } namespace std { template <typename T> struct hash<::generic::light_ptr<T> > { size_t operator()(::generic::light_ptr<T> const& l) const noexcept { return hash<typename ::generic::light_ptr<T>::element_type*>()(l.get()); } }; } #endif // LIGHTPTR_HPP <commit_msg>some fixes<commit_after>#pragma once #ifndef LIGHTPTR_HPP # define LIGHTPTR_HPP #include <cassert> #include <atomic> #include <memory> #include <utility> #include <type_traits> namespace generic { namespace detail { using counter_type = unsigned; using atomic_type = ::std::atomic<counter_type>; template <typename T> using deleter_type = void (*)(T*); template <typename T> using invoker_type = void (*)(void*, T*); template <typename U> struct ref_type { using type = U&; }; template <> struct ref_type<void> { using type = void; }; } template <typename T> struct light_ptr { template <typename U, typename V> struct deletion_type { using type = V; }; template <typename U, typename V> struct deletion_type<U[], V> { using type = V[]; }; template <typename U, typename V, ::std::size_t N> struct deletion_type<U[N], V> { using type = V[]; }; template <typename U> struct remove_array { using type = U; }; template <typename U> struct remove_array<U[]> { using type = U; }; template <typename U, ::std::size_t N> struct remove_array<U[N]> { using type = U; }; using element_type = typename remove_array<T>::type; using deleter_type = detail::deleter_type<element_type>; using invoker_type = detail::invoker_type<element_type>; struct counter_base { explicit counter_base(detail::counter_type c, invoker_type invoker) noexcept : counter_(c), invoker_(invoker) { } template <typename U> typename ::std::enable_if<!::std::is_void<U>{}>::type dec_ref(U* const ptr) { if (detail::counter_type(1) == counter_.fetch_sub(detail::counter_type(1), ::std::memory_order_relaxed)) { typedef char type_must_be_complete[sizeof(U) ? 1 : -1]; (void)sizeof(type_must_be_complete); invoker_(this, ptr); } // else do nothing } template <typename U> typename ::std::enable_if<::std::is_void<U>{}>::type dec_ref(U* const ptr) { if (detail::counter_type(1) == counter_.fetch_sub(detail::counter_type(1), ::std::memory_order_relaxed)) { invoker_(this, ptr); } // else do nothing } void inc_ref() noexcept { //assert(counter_ptr); counter_.fetch_add(detail::counter_type(1), ::std::memory_order_relaxed); } detail::atomic_type counter_{}; invoker_type invoker_; }; template <typename U> struct counter : counter_base { explicit counter(detail::counter_type const c, U&& d) noexcept : counter_base(c, invoker), d_(::std::forward<U>(d)) { } private: static void invoker(void* const ptr, element_type* const e) { counter* const c(static_cast<counter<U>*>( static_cast<counter_base*>(ptr))); U const d(::std::move(c->d_)); delete c; d(e); } private: U d_; }; light_ptr() = default; template <typename U> explicit light_ptr(U* const p, deleter_type const d = default_deleter<U>) { reset(p, d); } ~light_ptr() { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing } light_ptr(light_ptr const& other) { *this = other; } light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); } light_ptr& operator=(light_ptr const& rhs) { if (*this != rhs) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing counter_ = rhs.counter_; ptr_ = rhs.ptr_; if (counter_) { counter_->inc_ref(); } // else do nothing } // else do nothing return *this; } light_ptr& operator=(light_ptr&& rhs) noexcept { counter_ = rhs.counter_; ptr_ = rhs.ptr_; rhs.counter_ = nullptr; rhs.ptr_ = nullptr; return *this; } light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); } bool operator<(light_ptr const& rhs) const noexcept { return get() < rhs.get(); } bool operator==(light_ptr const& rhs) const noexcept { return counter_ == rhs.counter_; } bool operator!=(light_ptr const& rhs) const noexcept { return !operator==(rhs); } bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; } bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; } explicit operator bool() const noexcept { return ptr_; } typename detail::ref_type<T>::type operator*() const noexcept { return *static_cast<T*>(static_cast<void*>(ptr_)); } T* operator->() const noexcept { return static_cast<T*>(static_cast<void*>(ptr_)); } element_type* get() const noexcept { return ptr_; } void reset() { reset(nullptr); } void reset(::std::nullptr_t const) { if (counter_) { counter_->dec_ref(ptr_); counter_ = {}; } // else do nothing ptr_ = {}; } template <typename U> static void default_deleter(element_type* const p) { ::std::default_delete<typename deletion_type<T, U>::type>()( static_cast<U*>(p)); } template <typename U, typename D> void reset(U* const p, D&& d = default_deleter<U>) { if (counter_) { counter_->dec_ref(ptr_); } // else do nothing counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d)); ptr_ = p; } void swap(light_ptr& other) noexcept { ::std::swap(counter_, other.counter_); ::std::swap(ptr_, other.ptr_); } bool unique() const noexcept { return detail::counter_type(1) == use_count(); } detail::counter_type use_count() const noexcept { return counter_ ? counter_->counter_ptr_->load(::std::memory_order_relaxed) : detail::counter_type{}; } private: counter_base* counter_{}; element_type* ptr_{}; }; template<class T, class ...Args> inline light_ptr<T> make_light(Args&& ...args) { return light_ptr<T>(new T(::std::forward<Args>(args)...)); } } namespace std { template <typename T> struct hash<::generic::light_ptr<T> > { size_t operator()(::generic::light_ptr<T> const& l) const noexcept { return hash<typename ::generic::light_ptr<T>::element_type*>()(l.get()); } }; } #endif // LIGHTPTR_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 <iostream> #include "mkldnn.hpp" #include "paddle/fluid/operators/softmax_op.h" #include "paddle/fluid/platform/mkldnn_helper.h" namespace paddle { namespace operators { using paddle::framework::Tensor; using paddle::platform::MKLDNNDeviceContext; using paddle::platform::MKLDNNMemDesc; using mkldnn::memory; // Note: paddle has also "memory" namespace using mkldnn::primitive; using mkldnn::softmax_forward; using mkldnn::prop_kind; using mkldnn::stream; template <typename T> class SoftmaxMKLDNNKernel : public paddle::framework::OpKernel<T> { public: void Compute(const paddle::framework::ExecutionContext& ctx) const override { PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()), "It must use CPUPlace."); auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>(); auto mkldnn_engine = dev_ctx.GetEngine(); const Tensor* input = ctx.Input<Tensor>("X"); Tensor* output = ctx.Output<Tensor>("Out"); PADDLE_ENFORCE(input->dims().size() == 2UL, "The input of softmax op must be a 2D matrix."); const T* input_data = input->data<T>(); // allocate memory for output T* output_data = output->mutable_data<T>(ctx.GetPlace()); std::vector<int> src_tz = paddle::framework::vectorize2int(input->dims()); std::vector<int> dst_tz = paddle::framework::vectorize2int(output->dims()); // MKL-DNN does support softmax over selected axis. Having 2D Tensor, // we will make normalization after final eg. axis: 1 PADDLE_ENFORCE(((src_tz[0] == dst_tz[0]) && (src_tz[1] == dst_tz[1])), "Softmax input and output dimensions should match"); // Same memory descriptor to be used for input and output memory::dims softmax_tz = {src_tz[0], src_tz[1]}; // Currently only supports NC data format // TODO(jczaja-intel): support more formats auto softmax_md = MKLDNNMemDesc({softmax_tz}, memory::f32, memory::format::nc); // Normalization is made after innermost dimension eg. C out of NC auto softmax_desc = softmax_forward::desc(prop_kind::forward_scoring, softmax_md, 1 /*dim: C*/); // create memory primitives auto softmax_src_memory = memory({softmax_md, mkldnn_engine}, static_cast<void*>(const_cast<T*>(input_data))); auto softmax_dst_memory = memory({softmax_md, mkldnn_engine}, static_cast<void*>(const_cast<T*>(output_data))); auto softmax_prim_desc = softmax_forward::primitive_desc(softmax_desc, mkldnn_engine); auto softmax = softmax_forward(softmax_prim_desc, softmax_src_memory, softmax_dst_memory); std::vector<primitive> pipeline{softmax}; stream(stream::kind::eager).submit(pipeline).wait(); const bool is_test = ctx.Attr<bool>("is_test"); if (!is_test) { T threshold = exp(-64); for (size_t i = 0; i < dst_tz[0] * dst_tz[1]; ++i) { output_data[i] = output_data[i] < threshold ? threshold : output_data[i]; } } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(softmax, MKLDNN, ::paddle::platform::CPUPlace, ops::SoftmaxMKLDNNKernel<float>); <commit_msg>Fix signed/unsigned comparison warning (#10211)<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 <iostream> #include "mkldnn.hpp" #include "paddle/fluid/operators/softmax_op.h" #include "paddle/fluid/platform/mkldnn_helper.h" namespace paddle { namespace operators { using paddle::framework::Tensor; using paddle::platform::MKLDNNDeviceContext; using paddle::platform::MKLDNNMemDesc; using mkldnn::memory; // Note: paddle has also "memory" namespace using mkldnn::primitive; using mkldnn::softmax_forward; using mkldnn::prop_kind; using mkldnn::stream; template <typename T> class SoftmaxMKLDNNKernel : public paddle::framework::OpKernel<T> { public: void Compute(const paddle::framework::ExecutionContext& ctx) const override { PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()), "It must use CPUPlace."); auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>(); auto mkldnn_engine = dev_ctx.GetEngine(); const Tensor* input = ctx.Input<Tensor>("X"); Tensor* output = ctx.Output<Tensor>("Out"); PADDLE_ENFORCE(input->dims().size() == 2UL, "The input of softmax op must be a 2D matrix."); const T* input_data = input->data<T>(); // allocate memory for output T* output_data = output->mutable_data<T>(ctx.GetPlace()); std::vector<int> src_tz = paddle::framework::vectorize2int(input->dims()); std::vector<int> dst_tz = paddle::framework::vectorize2int(output->dims()); // MKL-DNN does support softmax over selected axis. Having 2D Tensor, // we will make normalization after final eg. axis: 1 PADDLE_ENFORCE(((src_tz[0] == dst_tz[0]) && (src_tz[1] == dst_tz[1])), "Softmax input and output dimensions should match"); // Same memory descriptor to be used for input and output memory::dims softmax_tz = {src_tz[0], src_tz[1]}; // Currently only supports NC data format // TODO(jczaja-intel): support more formats auto softmax_md = MKLDNNMemDesc({softmax_tz}, memory::f32, memory::format::nc); // Normalization is made after innermost dimension eg. C out of NC auto softmax_desc = softmax_forward::desc(prop_kind::forward_scoring, softmax_md, 1 /*dim: C*/); // create memory primitives auto softmax_src_memory = memory({softmax_md, mkldnn_engine}, static_cast<void*>(const_cast<T*>(input_data))); auto softmax_dst_memory = memory({softmax_md, mkldnn_engine}, static_cast<void*>(const_cast<T*>(output_data))); auto softmax_prim_desc = softmax_forward::primitive_desc(softmax_desc, mkldnn_engine); auto softmax = softmax_forward(softmax_prim_desc, softmax_src_memory, softmax_dst_memory); std::vector<primitive> pipeline{softmax}; stream(stream::kind::eager).submit(pipeline).wait(); const bool is_test = ctx.Attr<bool>("is_test"); if (!is_test) { T threshold = exp(-64); for (int i = 0; i < dst_tz[0] * dst_tz[1]; ++i) { output_data[i] = output_data[i] < threshold ? threshold : output_data[i]; } } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(softmax, MKLDNN, ::paddle::platform::CPUPlace, ops::SoftmaxMKLDNNKernel<float>); <|endoftext|>
<commit_before>/** FlexArray [PawLIB] * Version: 1.0 * * A dynamic array with a low dynamic allocation demand. * Designed to take the place of 'std::vector'. * * Author(s): Michael Parkman, Jonathan Theodore, Jason C. McDonald */ /* LICENSE * Copyright (c) 2016 MousePaw Media. * 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 of the copyright holder 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. * * CONTRIBUTING * See http://www.mousepawgames.com/participate/opensource for information * on how to contribute to our projects. */ #ifndef FLEX_ARRAY_HPP_INCLUDED #define FLEX_ARRAY_HPP_INCLUDED #include <stdio.h> #include <stdexcept> #include "pawlib/base_flex_array.hpp" #include "pawlib/constants.hpp" #include "pawlib/iochannel.hpp" using pawlib::iochannel; using namespace pawlib::ioformat; namespace pawlib { template <typename type> class FlexArray : public Base_FlexArr<type> { public: /** Create a new FlexArray with the default capacity. */ FlexArray() :Base_FlexArr<type>() {} /** Create a new FlexArray with the specified minimum capacity. * \param the minimum number of elements that the FlexArray can contain. */ // cppcheck-suppress noExplicitConstructor FlexArray(uint32_t numElements) :Base_FlexArr<type>(numElements) {} /** Insert an element into the FlexArray at the given index. * Unsigned to prevent negative indices. * \param the element to insert * \param the index to insert the element at. * \return true if insert successful, else false. */ bool insert(type newElement, uint32_t index) { /* If the index is greater than the number of elements * in the array currently. */ if(index > 0 && index > this-> currElements - 1) { // Throw a non-fatal error. Numbers are 0-based. ioc << cat_error << vrb_quiet << "Index " << index << " out of bounds [0 - " << this->currElements - 1 << "]." << io_end; // Report failure. return false; } // Otherwise, the index is in bounds... else { // If the number of elements is equal to the capacity. if(this->currElements == this->capacity) { // Attempt to double the capacity. If it fails... if(!this->double_size()) { // Report failure. return false; } } // If there are elements in the FlexArray... if(this->currElements > 0) { /* Every element to the right of the index should * be shifted right one position. */ this->mem_shift(index + 1, 1); // Place the new element at the specified index. this->theArray[index] = newElement; } // Incrememnt the number of elements. ++(this->currElements); // Report success. return true; } } /** Remove and return the element at the given index. * \param the index to act on. * \return the element from the given index. */ type yank(uint32_t index) { // If there are no elements in the array... if(this->currElements == 0) { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot yank from empty FlexArray."); } // Else if the given index is out of bounds. else if(index > this->capacity) { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot yank from out of range index."); } else { // Store the element at index, to be returned shortly. type temp = this->theArray[index]; /* All of the elements to the right of the index should be * shifted left one position. This effectively deletes the * element from the array.*/ this->mem_shift(index + 1, -1); // Decrement the number of elements. --(this->currElements); // Return the deleted element. return temp; } } /** Insert an element at the beginning of the FlexArray. * Just an alias for shift() * \param the element to insert. * \return true if successful, else false. */ bool push_front(type newElement) { push(newElement); } /** Insert an element at the beginning of the FlexArray. * \param the element to insert. * \return true if successful, else false. */ bool shift(type newElement) { // If there are elements currently within the array. if(this->currElements > 0) { // If the array is full... if(this->currElements == this->capacity) { // Attempt to double the array's capacity. If it fails... if(!this->double_size()) { // Report failure. return false; } } // Shift all the elements to the right one position. this->mem_shift(0, 1); } // Store the new element in the first position. this->theArray[0] = newElement; // Increment the number of elements. ++(this->currElements); // Report success. return true; } /** Returns the first element in the FlexArray without modifying * the data structure. * \return the first element in the FlexArray. */ type peek() { // If there is at least one element in the array... if(this->currElements > 0) { // Return that element. return this->at(0); } // Otherwise... else { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot peek from empty FlexArray."); } } /** Returns and removes the first element in the FlexArray. * \return the first element, now removed. */ type unshift() { // If there is at least one element in the array... if(this->currElements > 0) { // Store the first element, to be returned later. type temp = this->theArray[0]; /* Move all elements to the left one index. This * effectively deletes the first element from the array. * We perform a raw memory move for efficiency. */ this->mem_shift(1, -1); // Decrement the number of elements. --(this->currElements); // Return the element we just deleted. return temp; } // Else if there are no elements in the array... else { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot unshift from empty FlexArray."); } } /** Return and remove the last element in the FlexArray. * Just an alias for pop() * \return the last element, now removed. */ type pop_back() { return pop(); } /** Return and remove the last element in the FlexArray. * \return the last element, now removed. */ type pop() { // If there are no elements... if(this->currElements == 0) { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot pop from empty FlexArray."); } // Else if there is at least one element... else { /* Return the last element and decrement the * number of elements. */ return this->theArray[--(this->currElements)]; } } /** Add the specified element to the end of the FlexArray. * Just an alias for push() * \param the element to add. * \return true if successful, else false. */ bool push_back(type newElement) { return push(newElement); } /** Add the specified element to the end of the FlexArray. * \param the element to add. * \return true if successful, else false. */ bool push(type newElement) { // If the array is full... if(this->currElements == this->capacity) { // Attempt to double the array's capacity. If it fails... if(!this->double_size()) { // Report failure. return false; } } /* Store the new element in the last position and * increment the number of elements. */ this->theArray[(this->currElements)++] = newElement; // Report success. return true; } }; } #endif // FLEX_ARRAY_HPP_INCLUDED <commit_msg>Comment typo.<commit_after>/** FlexArray [PawLIB] * Version: 1.0 * * A dynamic array with a low dynamic allocation demand. * Designed to take the place of 'std::vector'. * * Author(s): Michael Parkman, Jonathan Theodore, Jason C. McDonald */ /* LICENSE * Copyright (c) 2016 MousePaw Media. * 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 of the copyright holder 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. * * CONTRIBUTING * See http://www.mousepawgames.com/participate/opensource for information * on how to contribute to our projects. */ #ifndef FLEX_ARRAY_HPP_INCLUDED #define FLEX_ARRAY_HPP_INCLUDED #include <stdio.h> #include <stdexcept> #include "pawlib/base_flex_array.hpp" #include "pawlib/constants.hpp" #include "pawlib/iochannel.hpp" using pawlib::iochannel; using namespace pawlib::ioformat; namespace pawlib { template <typename type> class FlexArray : public Base_FlexArr<type> { public: /** Create a new FlexArray with the default capacity. */ FlexArray() :Base_FlexArr<type>() {} /** Create a new FlexArray with the specified minimum capacity. * \param the minimum number of elements that the FlexArray can contain. */ // cppcheck-suppress noExplicitConstructor FlexArray(uint32_t numElements) :Base_FlexArr<type>(numElements) {} /** Insert an element into the FlexArray at the given index. * Unsigned to prevent negative indices. * \param the element to insert * \param the index to insert the element at. * \return true if insert successful, else false. */ bool insert(type newElement, uint32_t index) { /* If the index is greater than the number of elements * in the array currently. */ if(index > 0 && index > this-> currElements - 1) { // Throw a non-fatal error. Numbers are 0-based. ioc << cat_error << vrb_quiet << "Index " << index << " out of bounds [0 - " << this->currElements - 1 << "]." << io_end; // Report failure. return false; } // Otherwise, the index is in bounds... else { // If the number of elements is equal to the capacity. if(this->currElements == this->capacity) { // Attempt to double the capacity. If it fails... if(!this->double_size()) { // Report failure. return false; } } // If there are elements in the FlexArray... if(this->currElements > 0) { /* Every element to the right of the index should * be shifted right one position. */ this->mem_shift(index + 1, 1); // Place the new element at the specified index. this->theArray[index] = newElement; } // Incrememnt the number of elements. ++(this->currElements); // Report success. return true; } } /** Remove and return the element at the given index. * \param the index to act on. * \return the element from the given index. */ type yank(uint32_t index) { // If there are no elements in the array... if(this->currElements == 0) { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot yank from empty FlexArray."); } // Else if the given index is out of bounds. else if(index > this->capacity) { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot yank from out of range index."); } else { // Store the element at index, to be returned shortly. type temp = this->theArray[index]; /* All of the elements to the right of the index should be * shifted left one position. This effectively deletes the * element from the array.*/ this->mem_shift(index + 1, -1); // Decrement the number of elements. --(this->currElements); // Return the deleted element. return temp; } } /** Insert an element at the end of the FlexArray. * Just an alias for push() * \param the element to insert. * \return true if successful, else false. */ bool push_front(type newElement) { push(newElement); } /** Insert an element at the beginning of the FlexArray. * \param the element to insert. * \return true if successful, else false. */ bool shift(type newElement) { // If there are elements currently within the array. if(this->currElements > 0) { // If the array is full... if(this->currElements == this->capacity) { // Attempt to double the array's capacity. If it fails... if(!this->double_size()) { // Report failure. return false; } } // Shift all the elements to the right one position. this->mem_shift(0, 1); } // Store the new element in the first position. this->theArray[0] = newElement; // Increment the number of elements. ++(this->currElements); // Report success. return true; } /** Returns the first element in the FlexArray without modifying * the data structure. * \return the first element in the FlexArray. */ type peek() { // If there is at least one element in the array... if(this->currElements > 0) { // Return that element. return this->at(0); } // Otherwise... else { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot peek from empty FlexArray."); } } /** Returns and removes the first element in the FlexArray. * \return the first element, now removed. */ type unshift() { // If there is at least one element in the array... if(this->currElements > 0) { // Store the first element, to be returned later. type temp = this->theArray[0]; /* Move all elements to the left one index. This * effectively deletes the first element from the array. * We perform a raw memory move for efficiency. */ this->mem_shift(1, -1); // Decrement the number of elements. --(this->currElements); // Return the element we just deleted. return temp; } // Else if there are no elements in the array... else { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot unshift from empty FlexArray."); } } /** Return and remove the last element in the FlexArray. * Just an alias for pop() * \return the last element, now removed. */ type pop_back() { return pop(); } /** Return and remove the last element in the FlexArray. * \return the last element, now removed. */ type pop() { // If there are no elements... if(this->currElements == 0) { // Throw a fatal error. throw std::out_of_range("FlexArray: Cannot pop from empty FlexArray."); } // Else if there is at least one element... else { /* Return the last element and decrement the * number of elements. */ return this->theArray[--(this->currElements)]; } } /** Add the specified element to the end of the FlexArray. * Just an alias for push() * \param the element to add. * \return true if successful, else false. */ bool push_back(type newElement) { return push(newElement); } /** Add the specified element to the end of the FlexArray. * \param the element to add. * \return true if successful, else false. */ bool push(type newElement) { // If the array is full... if(this->currElements == this->capacity) { // Attempt to double the array's capacity. If it fails... if(!this->double_size()) { // Report failure. return false; } } /* Store the new element in the last position and * increment the number of elements. */ this->theArray[(this->currElements)++] = newElement; // Report success. return true; } }; } #endif // FLEX_ARRAY_HPP_INCLUDED <|endoftext|>
<commit_before>#include "unlimited.h" #include "test/test_bitcoin.h" #include "../consensus/consensus.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> using namespace std; // Defined in rpc_tests.cpp not bitcoin-cli.cpp extern UniValue CallRPC(string strMethod); BOOST_FIXTURE_TEST_SUITE(excessiveblock_test, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_excessive) { BOOST_CHECK_NO_THROW(CallRPC("getexcessiveblock")); BOOST_CHECK_NO_THROW(CallRPC("getminingmaxblock")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock not_uint"), runtime_error); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock -1 0"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 1"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 1000")); BOOST_CHECK_NO_THROW(CallRPC("setexcessiveblock 1000 1")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 0 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 100000")); BOOST_CHECK_THROW(CallRPC("setminingmaxblock not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0 0"), runtime_error); } BOOST_AUTO_TEST_CASE(buip005) { string exceptedEB; string exceptedAD; excessiveBlockSize = 1000000; excessiveAcceptDepth = 9999999; exceptedEB = "EB1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 100000; excessiveAcceptDepth = 9999999 + 1; exceptedEB = "EB0.1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 10000; exceptedEB = "EB0"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); // set back to defaults excessiveBlockSize = 1000000; excessiveAcceptDepth = 4; } BOOST_AUTO_TEST_CASE(excessiveChecks) { CBlock block; excessiveBlockSize = 16000000; // Ignore excessive block size when checking sigops and block effort // Check sigops values // Maintain compatibility with the old sigops calculator for blocks <= 1MB BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); // Check sigops > 1MB. BOOST_CHECK_MESSAGE(false == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2),100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,(2*1000000),(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,(2*1000000)+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); // Check tx size values maxTxSize.value = DEFAULT_LARGEST_TRANSACTION; // Within a 1 MB block, a 1MB transaction is not excessive BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,1,1,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE), "improper max tx"); // With a > 1 MB block, use the maxTxSize to determine BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value), "improper max tx"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value+1), "improper max tx"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>fix unit test for new constraint on setminingmaxblock<commit_after>#include "unlimited.h" #include "test/test_bitcoin.h" #include "../consensus/consensus.h" #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> using namespace std; // Defined in rpc_tests.cpp not bitcoin-cli.cpp extern UniValue CallRPC(string strMethod); BOOST_FIXTURE_TEST_SUITE(excessiveblock_test, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_excessive) { BOOST_CHECK_NO_THROW(CallRPC("getexcessiveblock")); BOOST_CHECK_NO_THROW(CallRPC("getminingmaxblock")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock not_uint"), runtime_error); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000000 -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock -1 0"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 1"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 1000")); BOOST_CHECK_NO_THROW(CallRPC("setexcessiveblock 1000 1")); BOOST_CHECK_THROW(CallRPC("setexcessiveblock 1000 0 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 100000"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock not_uint"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock -1"), boost::bad_lexical_cast); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0"), runtime_error); BOOST_CHECK_THROW(CallRPC("setminingmaxblock 0 0"), runtime_error); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 1000")); BOOST_CHECK_NO_THROW(CallRPC("setminingmaxblock 101")); } BOOST_AUTO_TEST_CASE(buip005) { string exceptedEB; string exceptedAD; excessiveBlockSize = 1000000; excessiveAcceptDepth = 9999999; exceptedEB = "EB1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 100000; excessiveAcceptDepth = 9999999 + 1; exceptedEB = "EB0.1"; exceptedAD = "AD9999999"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); BOOST_CHECK_MESSAGE(BUComments.back() == exceptedAD, "AD ought to have been " << exceptedAD << " when excessiveBlockSize = " << excessiveAcceptDepth); excessiveBlockSize = 10000; exceptedEB = "EB0"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); excessiveBlockSize = 150000; exceptedEB = "EB0.1"; settingsToUserAgentString(); BOOST_CHECK_MESSAGE(BUComments.front() == exceptedEB, "EB ought to have been rounded to " << exceptedEB << " when excessiveBlockSize = " << excessiveBlockSize << " but was " << BUComments.front()); // set back to defaults excessiveBlockSize = 1000000; excessiveAcceptDepth = 4; } BOOST_AUTO_TEST_CASE(excessiveChecks) { CBlock block; excessiveBlockSize = 16000000; // Ignore excessive block size when checking sigops and block effort // Check sigops values // Maintain compatibility with the old sigops calculator for blocks <= 1MB BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE-1,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS+1,100,100), "improper sigops"); // Check sigops > 1MB. BOOST_CHECK_MESSAGE(false == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2),100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,1000000+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,(2*1000000),(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); BOOST_CHECK_MESSAGE(false == CheckExcessive(block,(2*1000000)+1,(blockSigopsPerMb.value*2)+1,100,100), "improper sigops"); // Check tx size values maxTxSize.value = DEFAULT_LARGEST_TRANSACTION; // Within a 1 MB block, a 1MB transaction is not excessive BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE,1,1,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE), "improper max tx"); // With a > 1 MB block, use the maxTxSize to determine BOOST_CHECK_MESSAGE(false == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value), "improper max tx"); BOOST_CHECK_MESSAGE(true == CheckExcessive(block,BLOCKSTREAM_CORE_MAX_BLOCK_SIZE+1,1,1,maxTxSize.value+1), "improper max tx"); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: srchitem.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2007-05-10 17:07:42 $ * * 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 * ************************************************************************/ #ifndef _SFX_SRCHITEM_HXX #define _SFX_SRCHITEM_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef INCLUDED_SFX2_DLLAPI_H #include "sfx2/dllapi.h" #endif #ifndef _COM_SUN_STAR_UTIL_XSEARCHDESCRIPTOR_HPP_ #include <com/sun/star/util/XSearchDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_ #include <com/sun/star/util/SearchOptions.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_ #include <com/sun/star/util/SearchFlags.hpp> #endif #ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_ #include <com/sun/star/i18n/TransliterationModules.hpp> #endif #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> #endif #ifndef _RSCSFX_HXX //autogen #include <rsc/rscsfx.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFXMSG_HXX //autogen #include <sfx2/msg.hxx> #endif #ifndef _SFX_SRCHDEFS_HXX_ #include <sfx2/srchdefs.hxx> #endif // defines --------------------------------------------------------------- // Kommandos #define SVX_SEARCHCMD_FIND ((sal_uInt16)0) #define SVX_SEARCHCMD_FIND_ALL ((sal_uInt16)1) #define SVX_SEARCHCMD_REPLACE ((sal_uInt16)2) #define SVX_SEARCHCMD_REPLACE_ALL ((sal_uInt16)3) // Suche in (fuer Calc) #define SVX_SEARCHIN_FORMULA ((sal_uInt16)0) #define SVX_SEARCHIN_VALUE ((sal_uInt16)1) #define SVX_SEARCHIN_NOTE ((sal_uInt16)2) // Applicationsflag #define SVX_SEARCHAPP_WRITER ((sal_uInt16)0) #define SVX_SEARCHAPP_CALC ((sal_uInt16)1) #define SVX_SEARCHAPP_DRAW ((sal_uInt16)2) #define SVX_SEARCHAPP_BASE ((sal_uInt16)3) // class SvxSearchItem --------------------------------------------------- //#ifdef ITEMID_SEARCH /* [Beschreibung] In diesem Item werden alle Such-Attribute gespeichert. */ class SFX2_DLLPUBLIC SvxSearchItem : public SfxPoolItem, public utl::ConfigItem { com::sun::star::util::SearchOptions aSearchOpt; SfxStyleFamily eFamily; // Vorlagen-Familie sal_uInt16 nCommand; // Kommando (Suchen, Alle Suchen, Ersetzen, Alle Ersetzen) // Calc-Spezifische Daten sal_uInt16 nCellType; // Suche in Formeln/Werten/Notizen sal_uInt16 nAppFlag; // Fuer welche Applikation ist der Dialog ueberhaupt sal_Bool bRowDirection; // Suchrichtung Zeilenweise/Spaltenweise sal_Bool bAllTables; // in alle Tabellen suchen sal_Bool bBackward; // Suche Rueckwaerts sal_Bool bPattern; // Suche nach Vorlagen sal_Bool bContent; // Suche im Inhalt sal_Bool bAsianOptions; // use asian options? public: TYPEINFO(); SvxSearchItem( const sal_uInt16 nId /*= ITEMID_SEARCH*/ ); SvxSearchItem( const SvxSearchItem& rItem ); virtual ~SvxSearchItem(); virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const; virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ); virtual int operator == ( const SfxPoolItem& ) const; virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper * = 0 ) const; // ConfigItem virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames ); sal_uInt16 GetCommand() const { return nCommand; } void SetCommand(sal_uInt16 nNewCommand) { nCommand = nNewCommand; } inline const String GetSearchString() const; inline void SetSearchString(const String& rNewString); inline const String GetReplaceString() const; inline void SetReplaceString(const String& rNewString); inline sal_Bool GetWordOnly() const; void SetWordOnly(sal_Bool bNewWordOnly); inline sal_Bool GetExact() const; void SetExact(sal_Bool bNewExact); sal_Bool GetBackward() const { return bBackward; } void SetBackward(sal_Bool bNewBackward) { bBackward = bNewBackward; } inline sal_Bool GetSelection() const; void SetSelection(sal_Bool bNewSelection); inline sal_Bool GetRegExp() const; void SetRegExp( sal_Bool bVal ); sal_Bool GetPattern() const { return bPattern; } void SetPattern(sal_Bool bNewPattern) { bPattern = bNewPattern; } sal_Bool IsContent() const { return bContent; } void SetContent( sal_Bool bNew ) { bContent = bNew; } SfxStyleFamily GetFamily() const { return eFamily; } void SetFamily( SfxStyleFamily eNewFamily ) { eFamily = eNewFamily; } sal_Bool GetRowDirection() const { return bRowDirection; } void SetRowDirection(sal_Bool bNewRowDirection) { bRowDirection = bNewRowDirection; } sal_Bool IsAllTables() const { return bAllTables; } void SetAllTables(sal_Bool bNew) { bAllTables = bNew; } sal_uInt16 GetCellType() const { return nCellType; } void SetCellType(sal_uInt16 nNewCellType) { nCellType = nNewCellType; } sal_uInt16 GetAppFlag() const { return nAppFlag; } void SetAppFlag(sal_uInt16 nNewAppFlag) { nAppFlag = nNewAppFlag; } inline sal_Bool IsLevenshtein() const; void SetLevenshtein( sal_Bool bVal ); inline sal_Bool IsLEVRelaxed() const; void SetLEVRelaxed(sal_Bool bSet); inline sal_uInt16 GetLEVOther() const; inline void SetLEVOther(sal_uInt16 nSet); inline sal_uInt16 GetLEVShorter() const; inline void SetLEVShorter(sal_uInt16 nSet); inline sal_uInt16 GetLEVLonger() const; inline void SetLEVLonger(sal_uInt16 nSet); void GetFromDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XSearchDescriptor > & rDescr ); void SetToDescriptor( ::com::sun::star::uno::Reference< ::com::sun::star::util::XSearchDescriptor > & rDescr ); inline const com::sun::star::util::SearchOptions & GetSearchOptions() const; inline void SetSearchOptions( const com::sun::star::util::SearchOptions &rOpt ); inline sal_Int32 GetTransliterationFlags() const; void SetTransliterationFlags( sal_Int32 nFlags ); inline sal_Bool IsMatchFullHalfWidthForms() const; void SetMatchFullHalfWidthForms( sal_Bool bVal ); inline sal_Bool IsUseAsianOptions() const { return bAsianOptions; } inline void SetUseAsianOptions( sal_Bool bVal ) { bAsianOptions = bVal; } }; const String SvxSearchItem::GetSearchString() const { return aSearchOpt.searchString; } void SvxSearchItem::SetSearchString(const String& rNewString) { aSearchOpt.searchString = rNewString; } const String SvxSearchItem::GetReplaceString() const { return aSearchOpt.replaceString; } void SvxSearchItem::SetReplaceString(const String& rNewString) { aSearchOpt.replaceString = rNewString; } sal_Bool SvxSearchItem::GetWordOnly() const { return 0 != (aSearchOpt.searchFlag & com::sun::star::util::SearchFlags::NORM_WORD_ONLY); } sal_Bool SvxSearchItem::GetExact() const { return 0 == (aSearchOpt.transliterateFlags & com::sun::star::i18n::TransliterationModules_IGNORE_CASE); } sal_Bool SvxSearchItem::GetSelection() const { return 0 != (aSearchOpt.searchFlag & com::sun::star::util::SearchFlags::REG_NOT_BEGINOFLINE); } sal_Bool SvxSearchItem::GetRegExp() const { return aSearchOpt.algorithmType == com::sun::star::util::SearchAlgorithms_REGEXP ; } sal_Bool SvxSearchItem::IsLEVRelaxed() const { return 0 != (aSearchOpt.searchFlag & com::sun::star::util::SearchFlags::LEV_RELAXED); } sal_uInt16 SvxSearchItem::GetLEVOther() const { return (INT16) aSearchOpt.changedChars; } void SvxSearchItem::SetLEVOther( sal_uInt16 nVal ) { aSearchOpt.changedChars = nVal; } sal_uInt16 SvxSearchItem::GetLEVShorter() const { return (INT16) aSearchOpt.insertedChars; } void SvxSearchItem::SetLEVShorter( sal_uInt16 nVal ) { aSearchOpt.insertedChars = nVal; } sal_uInt16 SvxSearchItem::GetLEVLonger() const { return (INT16) aSearchOpt.deletedChars; } void SvxSearchItem::SetLEVLonger( sal_uInt16 nVal ) { aSearchOpt.deletedChars = nVal; } sal_Bool SvxSearchItem::IsLevenshtein() const { return aSearchOpt.algorithmType == com::sun::star::util::SearchAlgorithms_APPROXIMATE; } const com::sun::star::util::SearchOptions & SvxSearchItem::GetSearchOptions() const { return aSearchOpt; } void SvxSearchItem::SetSearchOptions( const com::sun::star::util::SearchOptions &rOpt ) { aSearchOpt = rOpt; } sal_Int32 SvxSearchItem::GetTransliterationFlags() const { return aSearchOpt.transliterateFlags; } sal_Bool SvxSearchItem::IsMatchFullHalfWidthForms() const { return 0 != (aSearchOpt.transliterateFlags & com::sun::star::i18n::TransliterationModules_IGNORE_WIDTH); } #endif //#endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.258); FILE MERGED 2008/04/01 15:38:33 thb 1.3.258.3: #i85898# Stripping all external header guards 2008/04/01 12:40:38 thb 1.3.258.2: #i85898# Stripping all external header guards 2008/03/31 13:37:57 rt 1.3.258.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: srchitem.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFX_SRCHITEM_HXX #define _SFX_SRCHITEM_HXX #include "sal/config.h" #include "sfx2/dllapi.h" #include <com/sun/star/util/XSearchDescriptor.hpp> #include <com/sun/star/util/SearchOptions.hpp> #include <com/sun/star/util/SearchFlags.hpp> #include <com/sun/star/i18n/TransliterationModules.hpp> #include <unotools/configitem.hxx> #include <rsc/rscsfx.hxx> #include <tools/string.hxx> #include <svtools/poolitem.hxx> #include <sfx2/msg.hxx> #include <sfx2/srchdefs.hxx> // defines --------------------------------------------------------------- // Kommandos #define SVX_SEARCHCMD_FIND ((sal_uInt16)0) #define SVX_SEARCHCMD_FIND_ALL ((sal_uInt16)1) #define SVX_SEARCHCMD_REPLACE ((sal_uInt16)2) #define SVX_SEARCHCMD_REPLACE_ALL ((sal_uInt16)3) // Suche in (fuer Calc) #define SVX_SEARCHIN_FORMULA ((sal_uInt16)0) #define SVX_SEARCHIN_VALUE ((sal_uInt16)1) #define SVX_SEARCHIN_NOTE ((sal_uInt16)2) // Applicationsflag #define SVX_SEARCHAPP_WRITER ((sal_uInt16)0) #define SVX_SEARCHAPP_CALC ((sal_uInt16)1) #define SVX_SEARCHAPP_DRAW ((sal_uInt16)2) #define SVX_SEARCHAPP_BASE ((sal_uInt16)3) // class SvxSearchItem --------------------------------------------------- //#ifdef ITEMID_SEARCH /* [Beschreibung] In diesem Item werden alle Such-Attribute gespeichert. */ class SFX2_DLLPUBLIC SvxSearchItem : public SfxPoolItem, public utl::ConfigItem { com::sun::star::util::SearchOptions aSearchOpt; SfxStyleFamily eFamily; // Vorlagen-Familie sal_uInt16 nCommand; // Kommando (Suchen, Alle Suchen, Ersetzen, Alle Ersetzen) // Calc-Spezifische Daten sal_uInt16 nCellType; // Suche in Formeln/Werten/Notizen sal_uInt16 nAppFlag; // Fuer welche Applikation ist der Dialog ueberhaupt sal_Bool bRowDirection; // Suchrichtung Zeilenweise/Spaltenweise sal_Bool bAllTables; // in alle Tabellen suchen sal_Bool bBackward; // Suche Rueckwaerts sal_Bool bPattern; // Suche nach Vorlagen sal_Bool bContent; // Suche im Inhalt sal_Bool bAsianOptions; // use asian options? public: TYPEINFO(); SvxSearchItem( const sal_uInt16 nId /*= ITEMID_SEARCH*/ ); SvxSearchItem( const SvxSearchItem& rItem ); virtual ~SvxSearchItem(); virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const; virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ); virtual int operator == ( const SfxPoolItem& ) const; virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper * = 0 ) const; // ConfigItem virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames ); sal_uInt16 GetCommand() const { return nCommand; } void SetCommand(sal_uInt16 nNewCommand) { nCommand = nNewCommand; } inline const String GetSearchString() const; inline void SetSearchString(const String& rNewString); inline const String GetReplaceString() const; inline void SetReplaceString(const String& rNewString); inline sal_Bool GetWordOnly() const; void SetWordOnly(sal_Bool bNewWordOnly); inline sal_Bool GetExact() const; void SetExact(sal_Bool bNewExact); sal_Bool GetBackward() const { return bBackward; } void SetBackward(sal_Bool bNewBackward) { bBackward = bNewBackward; } inline sal_Bool GetSelection() const; void SetSelection(sal_Bool bNewSelection); inline sal_Bool GetRegExp() const; void SetRegExp( sal_Bool bVal ); sal_Bool GetPattern() const { return bPattern; } void SetPattern(sal_Bool bNewPattern) { bPattern = bNewPattern; } sal_Bool IsContent() const { return bContent; } void SetContent( sal_Bool bNew ) { bContent = bNew; } SfxStyleFamily GetFamily() const { return eFamily; } void SetFamily( SfxStyleFamily eNewFamily ) { eFamily = eNewFamily; } sal_Bool GetRowDirection() const { return bRowDirection; } void SetRowDirection(sal_Bool bNewRowDirection) { bRowDirection = bNewRowDirection; } sal_Bool IsAllTables() const { return bAllTables; } void SetAllTables(sal_Bool bNew) { bAllTables = bNew; } sal_uInt16 GetCellType() const { return nCellType; } void SetCellType(sal_uInt16 nNewCellType) { nCellType = nNewCellType; } sal_uInt16 GetAppFlag() const { return nAppFlag; } void SetAppFlag(sal_uInt16 nNewAppFlag) { nAppFlag = nNewAppFlag; } inline sal_Bool IsLevenshtein() const; void SetLevenshtein( sal_Bool bVal ); inline sal_Bool IsLEVRelaxed() const; void SetLEVRelaxed(sal_Bool bSet); inline sal_uInt16 GetLEVOther() const; inline void SetLEVOther(sal_uInt16 nSet); inline sal_uInt16 GetLEVShorter() const; inline void SetLEVShorter(sal_uInt16 nSet); inline sal_uInt16 GetLEVLonger() const; inline void SetLEVLonger(sal_uInt16 nSet); void GetFromDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XSearchDescriptor > & rDescr ); void SetToDescriptor( ::com::sun::star::uno::Reference< ::com::sun::star::util::XSearchDescriptor > & rDescr ); inline const com::sun::star::util::SearchOptions & GetSearchOptions() const; inline void SetSearchOptions( const com::sun::star::util::SearchOptions &rOpt ); inline sal_Int32 GetTransliterationFlags() const; void SetTransliterationFlags( sal_Int32 nFlags ); inline sal_Bool IsMatchFullHalfWidthForms() const; void SetMatchFullHalfWidthForms( sal_Bool bVal ); inline sal_Bool IsUseAsianOptions() const { return bAsianOptions; } inline void SetUseAsianOptions( sal_Bool bVal ) { bAsianOptions = bVal; } }; const String SvxSearchItem::GetSearchString() const { return aSearchOpt.searchString; } void SvxSearchItem::SetSearchString(const String& rNewString) { aSearchOpt.searchString = rNewString; } const String SvxSearchItem::GetReplaceString() const { return aSearchOpt.replaceString; } void SvxSearchItem::SetReplaceString(const String& rNewString) { aSearchOpt.replaceString = rNewString; } sal_Bool SvxSearchItem::GetWordOnly() const { return 0 != (aSearchOpt.searchFlag & com::sun::star::util::SearchFlags::NORM_WORD_ONLY); } sal_Bool SvxSearchItem::GetExact() const { return 0 == (aSearchOpt.transliterateFlags & com::sun::star::i18n::TransliterationModules_IGNORE_CASE); } sal_Bool SvxSearchItem::GetSelection() const { return 0 != (aSearchOpt.searchFlag & com::sun::star::util::SearchFlags::REG_NOT_BEGINOFLINE); } sal_Bool SvxSearchItem::GetRegExp() const { return aSearchOpt.algorithmType == com::sun::star::util::SearchAlgorithms_REGEXP ; } sal_Bool SvxSearchItem::IsLEVRelaxed() const { return 0 != (aSearchOpt.searchFlag & com::sun::star::util::SearchFlags::LEV_RELAXED); } sal_uInt16 SvxSearchItem::GetLEVOther() const { return (INT16) aSearchOpt.changedChars; } void SvxSearchItem::SetLEVOther( sal_uInt16 nVal ) { aSearchOpt.changedChars = nVal; } sal_uInt16 SvxSearchItem::GetLEVShorter() const { return (INT16) aSearchOpt.insertedChars; } void SvxSearchItem::SetLEVShorter( sal_uInt16 nVal ) { aSearchOpt.insertedChars = nVal; } sal_uInt16 SvxSearchItem::GetLEVLonger() const { return (INT16) aSearchOpt.deletedChars; } void SvxSearchItem::SetLEVLonger( sal_uInt16 nVal ) { aSearchOpt.deletedChars = nVal; } sal_Bool SvxSearchItem::IsLevenshtein() const { return aSearchOpt.algorithmType == com::sun::star::util::SearchAlgorithms_APPROXIMATE; } const com::sun::star::util::SearchOptions & SvxSearchItem::GetSearchOptions() const { return aSearchOpt; } void SvxSearchItem::SetSearchOptions( const com::sun::star::util::SearchOptions &rOpt ) { aSearchOpt = rOpt; } sal_Int32 SvxSearchItem::GetTransliterationFlags() const { return aSearchOpt.transliterateFlags; } sal_Bool SvxSearchItem::IsMatchFullHalfWidthForms() const { return 0 != (aSearchOpt.transliterateFlags & com::sun::star::i18n::TransliterationModules_IGNORE_WIDTH); } #endif //#endif <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "chrome/browser/ui/webui/options/chromeos/system_settings_provider.h" #include <string> #include "base/i18n/rtl.h" #include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/synchronization/lock.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros_settings.h" #include "chrome/browser/chromeos/cros_settings_names.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "unicode/calendar.h" #include "unicode/timezone.h" #include "unicode/ures.h" namespace { // TODO(jungshik): Using Enumerate method in ICU gives 600+ timezones. // Even after filtering out duplicate entries with a strict identity check, // we still have 400+ zones. Relaxing the criteria for the timezone // identity is likely to cut down the number to < 100. Until we // come up with a better list, we hard-code the following list as used by // Android. static const char* kTimeZones[] = { "Pacific/Majuro", "Pacific/Midway", "Pacific/Honolulu", "America/Anchorage", "America/Los_Angeles", "America/Tijuana", "America/Denver", "America/Phoenix", "America/Chihuahua", "America/Chicago", "America/Mexico_City", "America/Costa_Rica", "America/Regina", "America/New_York", "America/Bogota", "America/Caracas", "America/Barbados", "America/Manaus", "America/Santiago", "America/St_Johns", "America/Sao_Paulo", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Godthab", "America/Montevideo", "Atlantic/South_Georgia", "Atlantic/Azores", "Atlantic/Cape_Verde", "Africa/Casablanca", "Europe/London", "Europe/Amsterdam", "Europe/Belgrade", "Europe/Brussels", "Europe/Sarajevo", "Africa/Windhoek", "Africa/Brazzaville", "Asia/Amman", "Europe/Athens", "Asia/Beirut", "Africa/Cairo", "Europe/Helsinki", "Asia/Jerusalem", "Europe/Minsk", "Africa/Harare", "Asia/Baghdad", "Europe/Moscow", "Asia/Kuwait", "Africa/Nairobi", "Asia/Tehran", "Asia/Baku", "Asia/Tbilisi", "Asia/Yerevan", "Asia/Dubai", "Asia/Kabul", "Asia/Karachi", "Asia/Oral", "Asia/Yekaterinburg", "Asia/Calcutta", "Asia/Colombo", "Asia/Katmandu", "Asia/Almaty", "Asia/Rangoon", "Asia/Krasnoyarsk", "Asia/Bangkok", "Asia/Shanghai", "Asia/Hong_Kong", "Asia/Irkutsk", "Asia/Kuala_Lumpur", "Australia/Perth", "Asia/Taipei", "Asia/Seoul", "Asia/Tokyo", "Asia/Yakutsk", "Australia/Adelaide", "Australia/Darwin", "Australia/Brisbane", "Australia/Hobart", "Australia/Sydney", "Asia/Vladivostok", "Pacific/Guam", "Asia/Magadan", "Pacific/Auckland", "Pacific/Fiji", "Pacific/Tongatapu", }; static base::Lock timezone_bundle_lock; struct UResClose { inline void operator() (UResourceBundle* b) const { ures_close(b); } }; string16 GetExemplarCity(const icu::TimeZone& zone) { // TODO(jungshik): After upgrading to ICU 4.6, use U_ICUDATA_ZONE static const char* zone_bundle_name = NULL; // These will be leaked at the end. static UResourceBundle *zone_bundle = NULL; static UResourceBundle *zone_strings = NULL; UErrorCode status = U_ZERO_ERROR; { base::AutoLock lock(timezone_bundle_lock); if (zone_bundle == NULL) zone_bundle = ures_open(zone_bundle_name, uloc_getDefault(), &status); if (zone_strings == NULL) zone_strings = ures_getByKey(zone_bundle, "zone_strings", NULL, &status); } icu::UnicodeString zone_id; zone.getID(zone_id); std::string zone_id_str; zone_id.toUTF8String(zone_id_str); // resource keys for timezones use ':' in place of '/'. ReplaceSubstringsAfterOffset(&zone_id_str, 0, "/", ":"); scoped_ptr_malloc<UResourceBundle, UResClose> zone_item( ures_getByKey(zone_strings, zone_id_str.c_str(), NULL, &status)); icu::UnicodeString city; if (U_FAILURE(status)) goto fallback; city = icu::ures_getUnicodeStringByKey(zone_item.get(), "ec", &status); if (U_SUCCESS(status)) return string16(city.getBuffer(), city.length()); fallback: ReplaceSubstringsAfterOffset(&zone_id_str, 0, ":", "/"); // Take the last component of a timezone id (e.g. 'Baz' in 'Foo/Bar/Baz'). // Depending on timezones, keeping all but the 1st component // (e.g. Bar/Baz) may be better, but our current list does not have // any timezone for which that's the case. std::string::size_type slash_pos = zone_id_str.rfind('/'); if (slash_pos != std::string::npos && slash_pos < zone_id_str.size()) zone_id_str.erase(0, slash_pos + 1); // zone id has '_' in place of ' '. ReplaceSubstringsAfterOffset(&zone_id_str, 0, "_", " "); return ASCIIToUTF16(zone_id_str); } } // namespace anonymous namespace chromeos { SystemSettingsProvider::SystemSettingsProvider() { for (size_t i = 0; i < arraysize(kTimeZones); i++) { timezones_.push_back(icu::TimeZone::createTimeZone( icu::UnicodeString(kTimeZones[i], -1, US_INV))); } system::TimezoneSettings::GetInstance()->AddObserver(this); } SystemSettingsProvider::~SystemSettingsProvider() { system::TimezoneSettings::GetInstance()->RemoveObserver(this); STLDeleteElements(&timezones_); } void SystemSettingsProvider::DoSet(const std::string& path, Value* in_value) { // Non-guest users can change the time zone. if (UserManager::Get()->IsLoggedInAsGuest()) return; if (path == kSystemTimezone) { string16 value; if (!in_value || !in_value->IsType(Value::TYPE_STRING) || !in_value->GetAsString(&value)) return; const icu::TimeZone* timezone = GetTimezone(value); if (!timezone) return; system::TimezoneSettings::GetInstance()->SetTimezone(*timezone); } } bool SystemSettingsProvider::Get(const std::string& path, Value** out_value) const { if (path == kSystemTimezone) { *out_value = Value::CreateStringValue(GetKnownTimezoneID( system::TimezoneSettings::GetInstance()->GetTimezone())); return true; } return false; } bool SystemSettingsProvider::HandlesSetting(const std::string& path) const { return path == kSystemTimezone; } void SystemSettingsProvider::TimezoneChanged(const icu::TimeZone& timezone) { // Fires system setting change notification. CrosSettings::Get()->FireObservers(kSystemTimezone); } ListValue* SystemSettingsProvider::GetTimezoneList() { ListValue* timezoneList = new ListValue(); for (std::vector<icu::TimeZone*>::iterator iter = timezones_.begin(); iter != timezones_.end(); ++iter) { const icu::TimeZone* timezone = *iter; ListValue* option = new ListValue(); option->Append(Value::CreateStringValue(GetTimezoneID(*timezone))); option->Append(Value::CreateStringValue(GetTimezoneName(*timezone))); timezoneList->Append(option); } return timezoneList; } string16 SystemSettingsProvider::GetTimezoneName( const icu::TimeZone& timezone) { // Instead of using the raw_offset, use the offset in effect now. // For instance, US Pacific Time, the offset shown will be -7 in summer // while it'll be -8 in winter. int raw_offset, dst_offset; UDate now = icu::Calendar::getNow(); UErrorCode status = U_ZERO_ERROR; timezone.getOffset(now, false, raw_offset, dst_offset, status); DCHECK(U_SUCCESS(status)); int offset = raw_offset + dst_offset; // offset is in msec. int minute_offset = std::abs(offset) / 60000; int hour_offset = minute_offset / 60; int min_remainder = minute_offset % 60; // Some timezones have a non-integral hour offset. So, we need to // use hh:mm form. std::string offset_str = base::StringPrintf(offset >= 0 ? "UTC+%d:%02d" : "UTC-%d:%02d", hour_offset, min_remainder); // TODO(jungshik): When coming up with a better list of timezones, we also // have to come up with better 'display' names. One possibility is to list // multiple cities (e.g. "Los Angeles, Vancouver .." in the order of // the population of a country the city belongs to.). // We can also think of using LONG_GENERIC or LOCATION once we upgrade // to ICU 4.6. // In the meantime, we use "LONG" name with "Exemplar City" to distinguish // multiple timezones with the same "LONG" name but with different // rules (e.g. US Mountain Time in Denver vs Phoenix). icu::UnicodeString name; timezone.getDisplayName(dst_offset != 0, icu::TimeZone::LONG, name); string16 result(l10n_util::GetStringFUTF16( IDS_OPTIONS_SETTINGS_TIMEZONE_DISPLAY_TEMPLATE, ASCIIToUTF16(offset_str), string16(name.getBuffer(), name.length()), GetExemplarCity(timezone))); base::i18n::AdjustStringForLocaleDirection(&result); return result; } string16 SystemSettingsProvider::GetTimezoneID( const icu::TimeZone& timezone) { icu::UnicodeString id; timezone.getID(id); return string16(id.getBuffer(), id.length()); } const icu::TimeZone* SystemSettingsProvider::GetTimezone( const string16& timezone_id) { for (std::vector<icu::TimeZone*>::iterator iter = timezones_.begin(); iter != timezones_.end(); ++iter) { const icu::TimeZone* timezone = *iter; if (GetTimezoneID(*timezone) == timezone_id) { return timezone; } } return NULL; } string16 SystemSettingsProvider::GetKnownTimezoneID( const icu::TimeZone& timezone) const { for (std::vector<icu::TimeZone*>::const_iterator iter = timezones_.begin(); iter != timezones_.end(); ++iter) { const icu::TimeZone* known_timezone = *iter; if (known_timezone->hasSameRules(timezone)) return GetTimezoneID(*known_timezone); } // Not able to find a matching timezone in our list. return string16(); } } // namespace chromeos <commit_msg>Remove a goto jump from the code in favor of an if-construct.<commit_after>// Copyright (c) 2011 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 "chrome/browser/ui/webui/options/chromeos/system_settings_provider.h" #include <string> #include "base/i18n/rtl.h" #include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/synchronization/lock.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros_settings.h" #include "chrome/browser/chromeos/cros_settings_names.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "unicode/calendar.h" #include "unicode/timezone.h" #include "unicode/ures.h" namespace { // TODO(jungshik): Using Enumerate method in ICU gives 600+ timezones. // Even after filtering out duplicate entries with a strict identity check, // we still have 400+ zones. Relaxing the criteria for the timezone // identity is likely to cut down the number to < 100. Until we // come up with a better list, we hard-code the following list as used by // Android. static const char* kTimeZones[] = { "Pacific/Majuro", "Pacific/Midway", "Pacific/Honolulu", "America/Anchorage", "America/Los_Angeles", "America/Tijuana", "America/Denver", "America/Phoenix", "America/Chihuahua", "America/Chicago", "America/Mexico_City", "America/Costa_Rica", "America/Regina", "America/New_York", "America/Bogota", "America/Caracas", "America/Barbados", "America/Manaus", "America/Santiago", "America/St_Johns", "America/Sao_Paulo", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Godthab", "America/Montevideo", "Atlantic/South_Georgia", "Atlantic/Azores", "Atlantic/Cape_Verde", "Africa/Casablanca", "Europe/London", "Europe/Amsterdam", "Europe/Belgrade", "Europe/Brussels", "Europe/Sarajevo", "Africa/Windhoek", "Africa/Brazzaville", "Asia/Amman", "Europe/Athens", "Asia/Beirut", "Africa/Cairo", "Europe/Helsinki", "Asia/Jerusalem", "Europe/Minsk", "Africa/Harare", "Asia/Baghdad", "Europe/Moscow", "Asia/Kuwait", "Africa/Nairobi", "Asia/Tehran", "Asia/Baku", "Asia/Tbilisi", "Asia/Yerevan", "Asia/Dubai", "Asia/Kabul", "Asia/Karachi", "Asia/Oral", "Asia/Yekaterinburg", "Asia/Calcutta", "Asia/Colombo", "Asia/Katmandu", "Asia/Almaty", "Asia/Rangoon", "Asia/Krasnoyarsk", "Asia/Bangkok", "Asia/Shanghai", "Asia/Hong_Kong", "Asia/Irkutsk", "Asia/Kuala_Lumpur", "Australia/Perth", "Asia/Taipei", "Asia/Seoul", "Asia/Tokyo", "Asia/Yakutsk", "Australia/Adelaide", "Australia/Darwin", "Australia/Brisbane", "Australia/Hobart", "Australia/Sydney", "Asia/Vladivostok", "Pacific/Guam", "Asia/Magadan", "Pacific/Auckland", "Pacific/Fiji", "Pacific/Tongatapu", }; static base::Lock timezone_bundle_lock; struct UResClose { inline void operator() (UResourceBundle* b) const { ures_close(b); } }; string16 GetExemplarCity(const icu::TimeZone& zone) { // TODO(jungshik): After upgrading to ICU 4.6, use U_ICUDATA_ZONE static const char* zone_bundle_name = NULL; // These will be leaked at the end. static UResourceBundle *zone_bundle = NULL; static UResourceBundle *zone_strings = NULL; UErrorCode status = U_ZERO_ERROR; { base::AutoLock lock(timezone_bundle_lock); if (zone_bundle == NULL) zone_bundle = ures_open(zone_bundle_name, uloc_getDefault(), &status); if (zone_strings == NULL) zone_strings = ures_getByKey(zone_bundle, "zone_strings", NULL, &status); } icu::UnicodeString zone_id; zone.getID(zone_id); std::string zone_id_str; zone_id.toUTF8String(zone_id_str); // resource keys for timezones use ':' in place of '/'. ReplaceSubstringsAfterOffset(&zone_id_str, 0, "/", ":"); scoped_ptr_malloc<UResourceBundle, UResClose> zone_item( ures_getByKey(zone_strings, zone_id_str.c_str(), NULL, &status)); icu::UnicodeString city; if (!U_FAILURE(status)) { city = icu::ures_getUnicodeStringByKey(zone_item.get(), "ec", &status); if (U_SUCCESS(status)) return string16(city.getBuffer(), city.length()); } // Fallback case in case of failure. ReplaceSubstringsAfterOffset(&zone_id_str, 0, ":", "/"); // Take the last component of a timezone id (e.g. 'Baz' in 'Foo/Bar/Baz'). // Depending on timezones, keeping all but the 1st component // (e.g. Bar/Baz) may be better, but our current list does not have // any timezone for which that's the case. std::string::size_type slash_pos = zone_id_str.rfind('/'); if (slash_pos != std::string::npos && slash_pos < zone_id_str.size()) zone_id_str.erase(0, slash_pos + 1); // zone id has '_' in place of ' '. ReplaceSubstringsAfterOffset(&zone_id_str, 0, "_", " "); return ASCIIToUTF16(zone_id_str); } } // namespace anonymous namespace chromeos { SystemSettingsProvider::SystemSettingsProvider() { for (size_t i = 0; i < arraysize(kTimeZones); i++) { timezones_.push_back(icu::TimeZone::createTimeZone( icu::UnicodeString(kTimeZones[i], -1, US_INV))); } system::TimezoneSettings::GetInstance()->AddObserver(this); } SystemSettingsProvider::~SystemSettingsProvider() { system::TimezoneSettings::GetInstance()->RemoveObserver(this); STLDeleteElements(&timezones_); } void SystemSettingsProvider::DoSet(const std::string& path, Value* in_value) { // Non-guest users can change the time zone. if (UserManager::Get()->IsLoggedInAsGuest()) return; if (path == kSystemTimezone) { string16 value; if (!in_value || !in_value->IsType(Value::TYPE_STRING) || !in_value->GetAsString(&value)) return; const icu::TimeZone* timezone = GetTimezone(value); if (!timezone) return; system::TimezoneSettings::GetInstance()->SetTimezone(*timezone); } } bool SystemSettingsProvider::Get(const std::string& path, Value** out_value) const { if (path == kSystemTimezone) { *out_value = Value::CreateStringValue(GetKnownTimezoneID( system::TimezoneSettings::GetInstance()->GetTimezone())); return true; } return false; } bool SystemSettingsProvider::HandlesSetting(const std::string& path) const { return path == kSystemTimezone; } void SystemSettingsProvider::TimezoneChanged(const icu::TimeZone& timezone) { // Fires system setting change notification. CrosSettings::Get()->FireObservers(kSystemTimezone); } ListValue* SystemSettingsProvider::GetTimezoneList() { ListValue* timezoneList = new ListValue(); for (std::vector<icu::TimeZone*>::iterator iter = timezones_.begin(); iter != timezones_.end(); ++iter) { const icu::TimeZone* timezone = *iter; ListValue* option = new ListValue(); option->Append(Value::CreateStringValue(GetTimezoneID(*timezone))); option->Append(Value::CreateStringValue(GetTimezoneName(*timezone))); timezoneList->Append(option); } return timezoneList; } string16 SystemSettingsProvider::GetTimezoneName( const icu::TimeZone& timezone) { // Instead of using the raw_offset, use the offset in effect now. // For instance, US Pacific Time, the offset shown will be -7 in summer // while it'll be -8 in winter. int raw_offset, dst_offset; UDate now = icu::Calendar::getNow(); UErrorCode status = U_ZERO_ERROR; timezone.getOffset(now, false, raw_offset, dst_offset, status); DCHECK(U_SUCCESS(status)); int offset = raw_offset + dst_offset; // offset is in msec. int minute_offset = std::abs(offset) / 60000; int hour_offset = minute_offset / 60; int min_remainder = minute_offset % 60; // Some timezones have a non-integral hour offset. So, we need to // use hh:mm form. std::string offset_str = base::StringPrintf(offset >= 0 ? "UTC+%d:%02d" : "UTC-%d:%02d", hour_offset, min_remainder); // TODO(jungshik): When coming up with a better list of timezones, we also // have to come up with better 'display' names. One possibility is to list // multiple cities (e.g. "Los Angeles, Vancouver .." in the order of // the population of a country the city belongs to.). // We can also think of using LONG_GENERIC or LOCATION once we upgrade // to ICU 4.6. // In the meantime, we use "LONG" name with "Exemplar City" to distinguish // multiple timezones with the same "LONG" name but with different // rules (e.g. US Mountain Time in Denver vs Phoenix). icu::UnicodeString name; timezone.getDisplayName(dst_offset != 0, icu::TimeZone::LONG, name); string16 result(l10n_util::GetStringFUTF16( IDS_OPTIONS_SETTINGS_TIMEZONE_DISPLAY_TEMPLATE, ASCIIToUTF16(offset_str), string16(name.getBuffer(), name.length()), GetExemplarCity(timezone))); base::i18n::AdjustStringForLocaleDirection(&result); return result; } string16 SystemSettingsProvider::GetTimezoneID( const icu::TimeZone& timezone) { icu::UnicodeString id; timezone.getID(id); return string16(id.getBuffer(), id.length()); } const icu::TimeZone* SystemSettingsProvider::GetTimezone( const string16& timezone_id) { for (std::vector<icu::TimeZone*>::iterator iter = timezones_.begin(); iter != timezones_.end(); ++iter) { const icu::TimeZone* timezone = *iter; if (GetTimezoneID(*timezone) == timezone_id) { return timezone; } } return NULL; } string16 SystemSettingsProvider::GetKnownTimezoneID( const icu::TimeZone& timezone) const { for (std::vector<icu::TimeZone*>::const_iterator iter = timezones_.begin(); iter != timezones_.end(); ++iter) { const icu::TimeZone* known_timezone = *iter; if (known_timezone->hasSameRules(timezone)) return GetTimezoneID(*known_timezone); } // Not able to find a matching timezone in our list. return string16(); } } // namespace chromeos <|endoftext|>
<commit_before>#include "ReplicatedLog.h" #include "Framework/Replication/ReplicationConfig.h" #include "System/Events/EventLoop.h" static Buffer enableMultiPaxos; static Buffer dummy; void ReplicatedLog::Init(QuorumContext* context_) { Log_Trace(); context = context_; paxosID = 0; proposer.Init(context); acceptor.Init(context); lastRequestChosenTime = 0; lastRequestChosenPaxosID = 0; commitChaining = false; enableMultiPaxos.Write("EnableMultiPaxos"); dummy.Write("dummy"); } void ReplicatedLog::Shutdown() { proposer.Shutdown(); } void ReplicatedLog::SetCommitChaining(bool commitChaining_) { commitChaining = commitChaining_; } bool ReplicatedLog::GetCommitChaining() { return commitChaining; } void ReplicatedLog::SetAsyncCommit(bool asyncCommit) { acceptor.SetAsyncCommit(asyncCommit); } bool ReplicatedLog::GetAsyncCommit() { return acceptor.GetAsyncCommit(); } void ReplicatedLog::Stop() { proposer.Stop(); } void ReplicatedLog::Continue() { // nothing } bool ReplicatedLog::IsMultiPaxosEnabled() { return proposer.state.multi; } bool ReplicatedLog::IsAppending() { return context->IsLeaseOwner() && proposer.state.numProposals > 0; } void ReplicatedLog::TryAppendDummy() { Log_Trace(); if (!context->IsLeaseOwner() || proposer.IsActive() || !proposer.state.multi) return; Append(dummy); } void ReplicatedLog::TryAppendNextValue() { Log_Trace(); if (!context->IsLeaseOwner() || proposer.IsActive() || !proposer.state.multi) return; Buffer& value = context->GetNextValue(); if (value.GetLength() == 0) return; Append(value); } void ReplicatedLog::TryCatchup() { if (context->IsLeaseKnown()) RequestChosen(context->GetLeaseOwner()); } void ReplicatedLog::SetPaxosID(uint64_t paxosID_) { paxosID = paxosID_; } uint64_t ReplicatedLog::GetPaxosID() { return paxosID; } void ReplicatedLog::RegisterPaxosID(uint64_t paxosID, uint64_t nodeID) { Log_Trace(); if (paxosID > GetPaxosID()) { // I am lagging and need to catch-up RequestChosen(nodeID); } } void ReplicatedLog::OnMessage(PaxosMessage& imsg) { Log_Trace(); if (context->IsPaxosBlocked()) { Log_Trace("paxos is blocked"); return; } if (imsg.type == PAXOS_PREPARE_REQUEST) OnPrepareRequest(imsg); else if (imsg.IsPrepareResponse()) OnPrepareResponse(imsg); else if (imsg.type == PAXOS_PROPOSE_REQUEST) OnProposeRequest(imsg); else if (imsg.IsProposeResponse()) OnProposeResponse(imsg); else if (imsg.IsLearn()) OnLearnChosen(imsg); else if (imsg.type == PAXOS_REQUEST_CHOSEN) OnRequestChosen(imsg); else if (imsg.type == PAXOS_START_CATCHUP) OnStartCatchup(imsg); else ASSERT_FAIL(); } void ReplicatedLog::OnCatchupComplete(uint64_t paxosID_) { paxosID = paxosID_; acceptor.OnCatchupComplete(); // commits NewPaxosRound(); } void ReplicatedLog::OnLearnLease() { Log_Trace("context->IsLeaseOwner() = %s", (context->IsLeaseOwner() ? "true" : "false")); Log_Trace("!proposer.IsActive() = %s", (!proposer.IsActive() ? "true" : "false")); Log_Trace("!proposer.state.multi = %s", (!proposer.state.multi ? "true" : "false")); if (context->IsLeaseOwner() && !proposer.IsActive() && !proposer.state.multi) { Log_Trace("Appending EnableMultiPaxos"); Append(enableMultiPaxos); } } void ReplicatedLog::OnLeaseTimeout() { proposer.state.multi = false; } void ReplicatedLog::OnAppendComplete() { // TODO: this is not a complete solution if (paxosID < context->GetHighestPaxosID()) context->GetDatabase()->Commit(); if (!commitChaining) { acceptor.WriteState(); context->GetDatabase()->Commit(); } TryAppendNextValue(); } void ReplicatedLog::Append(Buffer& value) { Log_Trace(); if (proposer.IsActive()) return; proposer.Propose(value); } void ReplicatedLog::OnPrepareRequest(PaxosMessage& imsg) { Log_Trace(); // Log_Debug("OnPrepareRequest begin"); if (imsg.paxosID == paxosID) { // Log_Debug("OnPrepareRequest end"); return acceptor.OnPrepareRequest(imsg); } OnRequest(imsg); // Log_Debug("OnPrepareRequest end"); } void ReplicatedLog::OnPrepareResponse(PaxosMessage& imsg) { Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnPrepareResponse(imsg); } void ReplicatedLog::OnProposeRequest(PaxosMessage& imsg) { Log_Trace(); // Log_Debug("OnProposeRequest begin"); if (imsg.paxosID == paxosID) { // Log_Debug("OnProposeRequest end"); return acceptor.OnProposeRequest(imsg); } OnRequest(imsg); // Log_Debug("OnProposeRequest end"); } void ReplicatedLog::OnProposeResponse(PaxosMessage& imsg) { Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnProposeResponse(imsg); } void ReplicatedLog::OnLearnChosen(PaxosMessage& imsg) { uint64_t runID; ReadBuffer value; // Log_Debug("OnLearnChosen begin"); Log_Trace(); if (imsg.paxosID > paxosID) { RequestChosen(imsg.nodeID); // I am lagging and need to catch-up return; } else if (imsg.paxosID < paxosID) return; if (imsg.type == PAXOS_LEARN_VALUE) { runID = imsg.runID; value = imsg.value; context->GetDatabase()->SetAcceptedValue(paxosID, value); } else if (imsg.type == PAXOS_LEARN_PROPOSAL && acceptor.state.accepted && acceptor.state.acceptedProposalID == imsg.proposalID) { runID = acceptor.state.acceptedRunID; value.Wrap(acceptor.state.acceptedValue); } else { RequestChosen(imsg.nodeID); return; } ProcessLearnChosen(imsg.nodeID, runID, value); // Log_Debug("OnLearnChosen end"); } void ReplicatedLog::OnRequestChosen(PaxosMessage& imsg) { Buffer value; PaxosMessage omsg; Log_Trace(); if (imsg.paxosID >= GetPaxosID()) return; // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() > 0) { Log_Trace("Sending paxosID %d to node %d", imsg.paxosID, imsg.nodeID); omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); } else { Log_Trace("Node requested a paxosID I no longer have"); omsg.StartCatchup(paxosID, MY_NODEID); } context->GetTransport()->SendMessage(imsg.nodeID, omsg); } void ReplicatedLog::OnStartCatchup(PaxosMessage& imsg) { if (imsg.nodeID == context->GetLeaseOwner()) context->OnStartCatchup(); } void ReplicatedLog::ProcessLearnChosen(uint64_t nodeID, uint64_t runID, ReadBuffer value) { bool ownAppend; if (context->GetHighestPaxosID() > 0 && paxosID < (context->GetHighestPaxosID() - 1)) { Log_Debug("Commiting because paxosID < (context->GetHighestPaxosID() - 1)"); Log_Debug("paxosID = %U | context->GetHighestPaxosID() = %U", paxosID, context->GetHighestPaxosID()); Log_Trace("+++ Value for paxosID = %U: %R +++", paxosID, &value); context->GetDatabase()->Commit(); } NewPaxosRound(); // increments paxosID, clears proposer, acceptor if (paxosID <= context->GetHighestPaxosID()) RequestChosen(nodeID); ownAppend = proposer.state.multi; if (nodeID == MY_NODEID && runID == REPLICATION_CONFIG->GetRunID() && context->IsLeaseOwner()) { if (!proposer.state.multi) { proposer.state.multi = true; context->OnIsLeader(); } proposer.state.multi = true; Log_Trace("Multi paxos enabled"); } else { proposer.state.multi = false; Log_Trace("Multi paxos disabled"); } if (!BUFCMP(&value, &enableMultiPaxos) && !BUFCMP(&value, &dummy)) context->OnAppend(paxosID - 1, value, ownAppend); // new convention: QuorumContext::OnAppend() must call // ReplicatedLog::OnAppendComplete() // when it's done! } void ReplicatedLog::OnRequest(PaxosMessage& imsg) { Log_Trace(); Buffer value; PaxosMessage omsg; if (imsg.paxosID < GetPaxosID()) { // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() == 0) return; omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); context->GetTransport()->SendMessage(imsg.nodeID, omsg); } else // paxosID < msg.paxosID { // I am lagging and need to catch-up RequestChosen(imsg.nodeID); } } void ReplicatedLog::NewPaxosRound() { EventLoop::Remove(&(proposer.prepareTimeout)); EventLoop::Remove(&(proposer.proposeTimeout)); paxosID++; proposer.state.OnNewPaxosRound(); acceptor.state.OnNewPaxosRound(); } void ReplicatedLog::RequestChosen(uint64_t nodeID) { PaxosMessage omsg; Log_Trace(); if (lastRequestChosenPaxosID == GetPaxosID() && EventLoop::Now() - lastRequestChosenTime < REQUEST_CHOSEN_TIMEOUT) return; lastRequestChosenPaxosID = GetPaxosID(); lastRequestChosenTime = EventLoop::Now(); omsg.RequestChosen(GetPaxosID(), MY_NODEID); context->GetTransport()->SendMessage(nodeID, omsg); } <commit_msg>Fixed replication bug.<commit_after>#include "ReplicatedLog.h" #include "Framework/Replication/ReplicationConfig.h" #include "System/Events/EventLoop.h" static Buffer enableMultiPaxos; static Buffer dummy; void ReplicatedLog::Init(QuorumContext* context_) { Log_Trace(); context = context_; paxosID = 0; proposer.Init(context); acceptor.Init(context); lastRequestChosenTime = 0; lastRequestChosenPaxosID = 0; commitChaining = false; enableMultiPaxos.Write("EnableMultiPaxos"); dummy.Write("dummy"); } void ReplicatedLog::Shutdown() { proposer.Shutdown(); } void ReplicatedLog::SetCommitChaining(bool commitChaining_) { commitChaining = commitChaining_; } bool ReplicatedLog::GetCommitChaining() { return commitChaining; } void ReplicatedLog::SetAsyncCommit(bool asyncCommit) { acceptor.SetAsyncCommit(asyncCommit); } bool ReplicatedLog::GetAsyncCommit() { return acceptor.GetAsyncCommit(); } void ReplicatedLog::Stop() { proposer.Stop(); } void ReplicatedLog::Continue() { // nothing } bool ReplicatedLog::IsMultiPaxosEnabled() { return proposer.state.multi; } bool ReplicatedLog::IsAppending() { return context->IsLeaseOwner() && proposer.state.numProposals > 0; } void ReplicatedLog::TryAppendDummy() { Log_Trace(); if (!context->IsLeaseOwner() || proposer.IsActive() || !proposer.state.multi) return; Append(dummy); } void ReplicatedLog::TryAppendNextValue() { Log_Trace(); if (!context->IsLeaseOwner() || proposer.IsActive() || !proposer.state.multi) return; Buffer& value = context->GetNextValue(); if (value.GetLength() == 0) return; Append(value); } void ReplicatedLog::TryCatchup() { if (context->IsLeaseKnown()) RequestChosen(context->GetLeaseOwner()); } void ReplicatedLog::SetPaxosID(uint64_t paxosID_) { paxosID = paxosID_; } uint64_t ReplicatedLog::GetPaxosID() { return paxosID; } void ReplicatedLog::RegisterPaxosID(uint64_t paxosID, uint64_t nodeID) { Log_Trace(); if (paxosID > GetPaxosID()) { // I am lagging and need to catch-up RequestChosen(nodeID); } } void ReplicatedLog::OnMessage(PaxosMessage& imsg) { Log_Trace(); if (context->IsPaxosBlocked()) { Log_Trace("paxos is blocked"); return; } if (imsg.type == PAXOS_PREPARE_REQUEST) OnPrepareRequest(imsg); else if (imsg.IsPrepareResponse()) OnPrepareResponse(imsg); else if (imsg.type == PAXOS_PROPOSE_REQUEST) OnProposeRequest(imsg); else if (imsg.IsProposeResponse()) OnProposeResponse(imsg); else if (imsg.IsLearn()) OnLearnChosen(imsg); else if (imsg.type == PAXOS_REQUEST_CHOSEN) OnRequestChosen(imsg); else if (imsg.type == PAXOS_START_CATCHUP) OnStartCatchup(imsg); else ASSERT_FAIL(); } void ReplicatedLog::OnCatchupComplete(uint64_t paxosID_) { paxosID = paxosID_; acceptor.OnCatchupComplete(); // commits NewPaxosRound(); } void ReplicatedLog::OnLearnLease() { Log_Trace("context->IsLeaseOwner() = %s", (context->IsLeaseOwner() ? "true" : "false")); Log_Trace("!proposer.IsActive() = %s", (!proposer.IsActive() ? "true" : "false")); Log_Trace("!proposer.state.multi = %s", (!proposer.state.multi ? "true" : "false")); if (context->IsLeaseOwner() && !proposer.IsActive() && !proposer.state.multi) { Log_Trace("Appending EnableMultiPaxos"); Append(enableMultiPaxos); } } void ReplicatedLog::OnLeaseTimeout() { proposer.state.multi = false; } void ReplicatedLog::OnAppendComplete() { // TODO: this is not a complete solution if (paxosID < context->GetHighestPaxosID()) context->GetDatabase()->Commit(); if (!commitChaining) { acceptor.WriteState(); context->GetDatabase()->Commit(); } TryAppendNextValue(); } void ReplicatedLog::Append(Buffer& value) { Log_Trace(); if (proposer.IsActive()) return; proposer.Propose(value); } void ReplicatedLog::OnPrepareRequest(PaxosMessage& imsg) { Log_Trace(); // Log_Debug("OnPrepareRequest begin"); if (imsg.paxosID == paxosID) { // Log_Debug("OnPrepareRequest end"); return acceptor.OnPrepareRequest(imsg); } OnRequest(imsg); // Log_Debug("OnPrepareRequest end"); } void ReplicatedLog::OnPrepareResponse(PaxosMessage& imsg) { Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnPrepareResponse(imsg); } void ReplicatedLog::OnProposeRequest(PaxosMessage& imsg) { Log_Trace(); // Log_Debug("OnProposeRequest begin"); if (imsg.paxosID == paxosID) { // Log_Debug("OnProposeRequest end"); return acceptor.OnProposeRequest(imsg); } OnRequest(imsg); // Log_Debug("OnProposeRequest end"); } void ReplicatedLog::OnProposeResponse(PaxosMessage& imsg) { Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnProposeResponse(imsg); } void ReplicatedLog::OnLearnChosen(PaxosMessage& imsg) { uint64_t runID; ReadBuffer value; // Log_Debug("OnLearnChosen begin"); Log_Trace(); if (imsg.paxosID > paxosID) { RequestChosen(imsg.nodeID); // I am lagging and need to catch-up return; } else if (imsg.paxosID < paxosID) return; if (imsg.type == PAXOS_LEARN_VALUE) { runID = imsg.runID; value = imsg.value; context->GetDatabase()->SetAcceptedValue(paxosID, value); } else if (imsg.type == PAXOS_LEARN_PROPOSAL && acceptor.state.accepted && acceptor.state.acceptedProposalID == imsg.proposalID) { runID = acceptor.state.acceptedRunID; value.Wrap(acceptor.state.acceptedValue); } else { RequestChosen(imsg.nodeID); return; } ProcessLearnChosen(imsg.nodeID, runID, value); // Log_Debug("OnLearnChosen end"); } void ReplicatedLog::OnRequestChosen(PaxosMessage& imsg) { Buffer value; PaxosMessage omsg; Log_Trace(); if (imsg.paxosID >= GetPaxosID()) return; // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() > 0) { Log_Trace("Sending paxosID %d to node %d", imsg.paxosID, imsg.nodeID); omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); } else { Log_Trace("Node requested a paxosID I no longer have"); omsg.StartCatchup(paxosID, MY_NODEID); } context->GetTransport()->SendMessage(imsg.nodeID, omsg); } void ReplicatedLog::OnStartCatchup(PaxosMessage& imsg) { if (imsg.nodeID == context->GetLeaseOwner()) context->OnStartCatchup(); } void ReplicatedLog::ProcessLearnChosen(uint64_t nodeID, uint64_t runID, ReadBuffer value) { bool ownAppend; if (context->GetHighestPaxosID() > 0 && paxosID < (context->GetHighestPaxosID() - 1)) { Log_Debug("Commiting because paxosID < (context->GetHighestPaxosID() - 1)"); Log_Debug("paxosID = %U | context->GetHighestPaxosID() = %U", paxosID, context->GetHighestPaxosID()); Log_Trace("+++ Value for paxosID = %U: %R +++", paxosID, &value); context->GetDatabase()->Commit(); } NewPaxosRound(); // increments paxosID, clears proposer, acceptor if (paxosID <= context->GetHighestPaxosID()) RequestChosen(nodeID); ownAppend = proposer.state.multi; if (nodeID == MY_NODEID && runID == REPLICATION_CONFIG->GetRunID() && context->IsLeaseOwner()) { if (!proposer.state.multi) { proposer.state.multi = true; context->OnIsLeader(); } proposer.state.multi = true; Log_Trace("Multi paxos enabled"); } else { proposer.state.multi = false; Log_Trace("Multi paxos disabled"); } if (!BUFCMP(&value, &enableMultiPaxos) && !BUFCMP(&value, &dummy)) context->OnAppend(paxosID - 1, value, ownAppend); else OnAppendComplete(); // new convention: QuorumContext::OnAppend() must call // ReplicatedLog::OnAppendComplete() // when it's done! } void ReplicatedLog::OnRequest(PaxosMessage& imsg) { Log_Trace(); Buffer value; PaxosMessage omsg; if (imsg.paxosID < GetPaxosID()) { // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() == 0) return; omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); context->GetTransport()->SendMessage(imsg.nodeID, omsg); } else // paxosID < msg.paxosID { // I am lagging and need to catch-up RequestChosen(imsg.nodeID); } } void ReplicatedLog::NewPaxosRound() { EventLoop::Remove(&(proposer.prepareTimeout)); EventLoop::Remove(&(proposer.proposeTimeout)); paxosID++; proposer.state.OnNewPaxosRound(); acceptor.state.OnNewPaxosRound(); } void ReplicatedLog::RequestChosen(uint64_t nodeID) { PaxosMessage omsg; Log_Trace(); if (lastRequestChosenPaxosID == GetPaxosID() && EventLoop::Now() - lastRequestChosenTime < REQUEST_CHOSEN_TIMEOUT) return; lastRequestChosenPaxosID = GetPaxosID(); lastRequestChosenTime = EventLoop::Now(); omsg.RequestChosen(GetPaxosID(), MY_NODEID); context->GetTransport()->SendMessage(nodeID, omsg); } <|endoftext|>
<commit_before>#include "ReplicatedLog.h" #include "Framework/Replication/ReplicationConfig.h" #include "System/Events/EventLoop.h" //#define RLOG_DEBUG_MESSAGES 1 static Buffer dummy; void ReplicatedLog::Init(QuorumContext* context_) { Log_Trace(); context = context_; paxosID = 0; proposer.Init(context); acceptor.Init(context); lastRequestChosenTime = 0; commitChaining = false; dummy.Write("dummy"); } void ReplicatedLog::Shutdown() { proposer.Shutdown(); } void ReplicatedLog::SetUseProposeTimeouts(bool useProposeTimeouts_) { useProposeTimeouts = useProposeTimeouts_; } void ReplicatedLog::SetCommitChaining(bool commitChaining_) { commitChaining = commitChaining_; } bool ReplicatedLog::GetCommitChaining() { return commitChaining; } void ReplicatedLog::SetAsyncCommit(bool asyncCommit) { acceptor.SetAsyncCommit(asyncCommit); } bool ReplicatedLog::GetAsyncCommit() { return acceptor.GetAsyncCommit(); } void ReplicatedLog::Stop() { proposer.Stop(); } void ReplicatedLog::Continue() { RequestChosen(paxosID); } bool ReplicatedLog::IsMultiPaxosEnabled() { return proposer.state.multi; } bool ReplicatedLog::IsAppending() { return context->IsLeaseOwner() && proposer.state.numProposals > 0; } void ReplicatedLog::TryAppendDummy() { Log_Trace(); if (proposer.IsActive()) return; proposer.SetUseTimeouts(true); Append(dummy); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Appending DUMMY!"); #endif } void ReplicatedLog::TryAppendNextValue() { Log_Trace(); if (!context->IsLeaseOwner() || proposer.IsActive() || !proposer.state.multi) return; Buffer& value = context->GetNextValue(); if (value.GetLength() == 0) return; proposer.SetUseTimeouts(useProposeTimeouts); Append(value); } void ReplicatedLog::TryCatchup() { if (context->IsLeaseKnown() && context->GetHighestPaxosID() > GetPaxosID()) RequestChosen(context->GetLeaseOwner()); } void ReplicatedLog::Restart() { context->OnStartProposing(); if (proposer.IsActive()) proposer.Restart(); } void ReplicatedLog::SetPaxosID(uint64_t paxosID_) { paxosID = paxosID_; } uint64_t ReplicatedLog::GetPaxosID() { return paxosID; } void ReplicatedLog::NewPaxosRound() { EventLoop::Remove(&(proposer.prepareTimeout)); EventLoop::Remove(&(proposer.proposeTimeout)); paxosID++; proposer.state.OnNewPaxosRound(); acceptor.state.OnNewPaxosRound(); lastRequestChosenTime = 0; } void ReplicatedLog::ResetPaxosState() { acceptor.ResetState(); } void ReplicatedLog::RegisterPaxosID(uint64_t paxosID, uint64_t nodeID) { Log_Trace(); if (paxosID > GetPaxosID()) { // I am lagging and need to catch-up RequestChosen(nodeID); } } void ReplicatedLog::OnMessage(PaxosMessage& imsg) { Log_Trace(); if (imsg.type == PAXOS_PREPARE_REQUEST) OnPrepareRequest(imsg); else if (imsg.IsPrepareResponse()) OnPrepareResponse(imsg); else if (imsg.type == PAXOS_PROPOSE_REQUEST) OnProposeRequest(imsg); else if (imsg.IsProposeResponse()) OnProposeResponse(imsg); else if (imsg.IsLearn()) OnLearnChosen(imsg); else if (imsg.type == PAXOS_REQUEST_CHOSEN) OnRequestChosen(imsg); else if (imsg.type == PAXOS_START_CATCHUP) OnStartCatchup(imsg); else ASSERT_FAIL(); } void ReplicatedLog::OnCatchupComplete(uint64_t paxosID_) { paxosID = paxosID_; acceptor.OnCatchupComplete(); // commits NewPaxosRound(); } void ReplicatedLog::OnLearnLease() { Log_Trace("context->IsLeaseOwner() = %s", (context->IsLeaseOwner() ? "true" : "false")); Log_Trace("!proposer.IsActive() = %s", (!proposer.IsActive() ? "true" : "false")); Log_Trace("!proposer.state.multi = %s", (!proposer.state.multi ? "true" : "false")); if (context->IsLeaseOwner() && !proposer.IsActive() && !proposer.state.multi) { Log_Trace("Appending dummy to enable MultiPaxos"); TryAppendDummy(); } } void ReplicatedLog::OnLeaseTimeout() { proposer.state.multi = false; } void ReplicatedLog::OnAppendComplete() { // TODO: this is not a complete solution if (paxosID < context->GetHighestPaxosID()) context->GetDatabase()->Commit(); if (!commitChaining) { acceptor.WriteState(); context->GetDatabase()->Commit(); } TryAppendNextValue(); } void ReplicatedLog::WriteState() { acceptor.WriteState(); } void ReplicatedLog::Append(Buffer& value) { Log_Trace(); if (proposer.IsActive()) return; context->OnStartProposing(); proposer.Propose(value); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Proposing for paxosID = %U", GetPaxosID()); #endif } void ReplicatedLog::OnPrepareRequest(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnPrepareRequest"); #endif acceptor.OnPrepareRequest(imsg); OnRequest(imsg); } void ReplicatedLog::OnPrepareResponse(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnPrepareResponse"); #endif Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnPrepareResponse(imsg); } void ReplicatedLog::OnProposeRequest(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnProposeRequest"); #endif Log_Trace(); acceptor.OnProposeRequest(imsg); OnRequest(imsg); } void ReplicatedLog::OnProposeResponse(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnProposeResponse"); #endif Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnProposeResponse(imsg); } void ReplicatedLog::OnLearnChosen(PaxosMessage& imsg) { uint64_t runID; Buffer learnedValue; #ifdef RLOG_DEBUG_MESSAGES Log_Debug("OnLearnChosen begin"); #endif if (context->GetDatabase()->IsCommiting()) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Database is commiting, dropping Paxos message"); #endif return; } Log_Trace(); if (imsg.paxosID > paxosID) { RequestChosen(imsg.nodeID); // I am lagging and need to catch-up return; } else if (imsg.paxosID < paxosID) return; if (imsg.type == PAXOS_LEARN_VALUE) { runID = imsg.runID; learnedValue.Write(imsg.value); context->GetDatabase()->SetAcceptedValue(paxosID, learnedValue); } else if (imsg.type == PAXOS_LEARN_PROPOSAL && acceptor.state.accepted && acceptor.state.acceptedProposalID == imsg.proposalID) { runID = acceptor.state.acceptedRunID; learnedValue.Write(acceptor.state.acceptedValue); } else { RequestChosen(imsg.nodeID); return; } ProcessLearnChosen(imsg.nodeID, runID, learnedValue); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("OnLearnChosen end"); #endif } void ReplicatedLog::OnRequestChosen(PaxosMessage& imsg) { Buffer value; PaxosMessage omsg; #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnRequestChosen, imsg.paxosID = %U, mine = %U", imsg.paxosID, GetPaxosID()); #endif if (imsg.paxosID >= GetPaxosID()) return; // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() > 0) { Log_Trace("Sending paxosID %d to node %d", imsg.paxosID, imsg.nodeID); omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); } else { Log_Trace("Node requested a paxosID I no longer have"); omsg.StartCatchup(paxosID, MY_NODEID); } context->GetTransport()->SendMessage(imsg.nodeID, omsg); } void ReplicatedLog::OnStartCatchup(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnStartCatchup"); #endif if (imsg.nodeID == context->GetLeaseOwner()) context->OnStartCatchup(); } void ReplicatedLog::ProcessLearnChosen(uint64_t nodeID, uint64_t runID, Buffer& learnedValue) { bool ownAppend; #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Round completed for paxosID = %U", paxosID); Log_Trace("+++ Value for paxosID = %U: %B +++", paxosID, &learnedValue); if (context->GetHighestPaxosID() > 0 && paxosID < context->GetHighestPaxosID() && !IsLeaseOwner()) { Log_Debug("Paxos-based catchup, highest seen paxosID is %U, currently at %U", context->GetHighestPaxosID(), paxosID); if (paxosID == (context->GetHighestPaxosID() - 1)) Log_Debug("Paxos-based catchup complete..."); } #endif if (context->GetHighestPaxosID() > 0 && paxosID < (context->GetHighestPaxosID() - 1)) context->GetDatabase()->Commit(); NewPaxosRound(); // increments paxosID, clears proposer, acceptor if (paxosID <= context->GetHighestPaxosID()) RequestChosen(nodeID); ownAppend = proposer.state.multi; if (nodeID == MY_NODEID && runID == REPLICATION_CONFIG->GetRunID() && context->IsLeaseOwner()) { if (!proposer.state.multi) { proposer.state.multi = true; context->OnIsLeader(); } proposer.state.multi = true; Log_Trace("Multi paxos enabled"); } else { proposer.state.multi = false; Log_Trace("Multi paxos disabled"); } if (BUFCMP(&learnedValue, &dummy)) OnAppendComplete(); else context->OnAppend(paxosID - 1, learnedValue, ownAppend); // new convention: QuorumContext::OnAppend() must call // ReplicatedLog::OnAppendComplete() // when it's done! } void ReplicatedLog::OnRequest(PaxosMessage& imsg) { Log_Trace(); Buffer value; PaxosMessage omsg; if (imsg.paxosID < GetPaxosID()) { // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() == 0) return; omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); context->GetTransport()->SendMessage(imsg.nodeID, omsg); } else if (GetPaxosID() < imsg.paxosID) { // I am lagging and need to catch-up RequestChosen(imsg.nodeID); } } void ReplicatedLog::RequestChosen(uint64_t nodeID) { PaxosMessage omsg; if (EventLoop::Now() - lastRequestChosenTime < REQUEST_CHOSEN_TIMEOUT) return; lastRequestChosenTime = EventLoop::Now(); omsg.RequestChosen(GetPaxosID(), MY_NODEID); context->GetTransport()->SendMessage(nodeID, omsg); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::RequestChosen, paxosID = %U, to = %U", GetPaxosID(), nodeID); #endif } <commit_msg>Don't catchup if I'm the lease owner.<commit_after>#include "ReplicatedLog.h" #include "Framework/Replication/ReplicationConfig.h" #include "System/Events/EventLoop.h" //#define RLOG_DEBUG_MESSAGES 1 static Buffer dummy; void ReplicatedLog::Init(QuorumContext* context_) { Log_Trace(); context = context_; paxosID = 0; proposer.Init(context); acceptor.Init(context); lastRequestChosenTime = 0; commitChaining = false; dummy.Write("dummy"); } void ReplicatedLog::Shutdown() { proposer.Shutdown(); } void ReplicatedLog::SetUseProposeTimeouts(bool useProposeTimeouts_) { useProposeTimeouts = useProposeTimeouts_; } void ReplicatedLog::SetCommitChaining(bool commitChaining_) { commitChaining = commitChaining_; } bool ReplicatedLog::GetCommitChaining() { return commitChaining; } void ReplicatedLog::SetAsyncCommit(bool asyncCommit) { acceptor.SetAsyncCommit(asyncCommit); } bool ReplicatedLog::GetAsyncCommit() { return acceptor.GetAsyncCommit(); } void ReplicatedLog::Stop() { proposer.Stop(); } void ReplicatedLog::Continue() { RequestChosen(paxosID); } bool ReplicatedLog::IsMultiPaxosEnabled() { return proposer.state.multi; } bool ReplicatedLog::IsAppending() { return context->IsLeaseOwner() && proposer.state.numProposals > 0; } void ReplicatedLog::TryAppendDummy() { Log_Trace(); if (proposer.IsActive()) return; proposer.SetUseTimeouts(true); Append(dummy); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Appending DUMMY!"); #endif } void ReplicatedLog::TryAppendNextValue() { Log_Trace(); if (!context->IsLeaseOwner() || proposer.IsActive() || !proposer.state.multi) return; Buffer& value = context->GetNextValue(); if (value.GetLength() == 0) return; proposer.SetUseTimeouts(useProposeTimeouts); Append(value); } void ReplicatedLog::TryCatchup() { if (context->IsLeaseKnown() && context->GetHighestPaxosID() > GetPaxosID()) RequestChosen(context->GetLeaseOwner()); } void ReplicatedLog::Restart() { context->OnStartProposing(); if (proposer.IsActive()) proposer.Restart(); } void ReplicatedLog::SetPaxosID(uint64_t paxosID_) { paxosID = paxosID_; } uint64_t ReplicatedLog::GetPaxosID() { return paxosID; } void ReplicatedLog::NewPaxosRound() { EventLoop::Remove(&(proposer.prepareTimeout)); EventLoop::Remove(&(proposer.proposeTimeout)); paxosID++; proposer.state.OnNewPaxosRound(); acceptor.state.OnNewPaxosRound(); lastRequestChosenTime = 0; } void ReplicatedLog::ResetPaxosState() { acceptor.ResetState(); } void ReplicatedLog::RegisterPaxosID(uint64_t paxosID, uint64_t nodeID) { Log_Trace(); if (paxosID > GetPaxosID()) { // I am lagging and need to catch-up RequestChosen(nodeID); } } void ReplicatedLog::OnMessage(PaxosMessage& imsg) { Log_Trace(); if (imsg.type == PAXOS_PREPARE_REQUEST) OnPrepareRequest(imsg); else if (imsg.IsPrepareResponse()) OnPrepareResponse(imsg); else if (imsg.type == PAXOS_PROPOSE_REQUEST) OnProposeRequest(imsg); else if (imsg.IsProposeResponse()) OnProposeResponse(imsg); else if (imsg.IsLearn()) OnLearnChosen(imsg); else if (imsg.type == PAXOS_REQUEST_CHOSEN) OnRequestChosen(imsg); else if (imsg.type == PAXOS_START_CATCHUP) OnStartCatchup(imsg); else ASSERT_FAIL(); } void ReplicatedLog::OnCatchupComplete(uint64_t paxosID_) { paxosID = paxosID_; acceptor.OnCatchupComplete(); // commits NewPaxosRound(); } void ReplicatedLog::OnLearnLease() { Log_Trace("context->IsLeaseOwner() = %s", (context->IsLeaseOwner() ? "true" : "false")); Log_Trace("!proposer.IsActive() = %s", (!proposer.IsActive() ? "true" : "false")); Log_Trace("!proposer.state.multi = %s", (!proposer.state.multi ? "true" : "false")); if (context->IsLeaseOwner() && !proposer.IsActive() && !proposer.state.multi) { Log_Trace("Appending dummy to enable MultiPaxos"); TryAppendDummy(); } } void ReplicatedLog::OnLeaseTimeout() { proposer.state.multi = false; } void ReplicatedLog::OnAppendComplete() { // TODO: this is not a complete solution if (paxosID < context->GetHighestPaxosID()) context->GetDatabase()->Commit(); if (!commitChaining) { acceptor.WriteState(); context->GetDatabase()->Commit(); } TryAppendNextValue(); } void ReplicatedLog::WriteState() { acceptor.WriteState(); } void ReplicatedLog::Append(Buffer& value) { Log_Trace(); if (proposer.IsActive()) return; context->OnStartProposing(); proposer.Propose(value); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Proposing for paxosID = %U", GetPaxosID()); #endif } void ReplicatedLog::OnPrepareRequest(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnPrepareRequest"); #endif acceptor.OnPrepareRequest(imsg); OnRequest(imsg); } void ReplicatedLog::OnPrepareResponse(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnPrepareResponse"); #endif Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnPrepareResponse(imsg); } void ReplicatedLog::OnProposeRequest(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnProposeRequest"); #endif Log_Trace(); acceptor.OnProposeRequest(imsg); OnRequest(imsg); } void ReplicatedLog::OnProposeResponse(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnProposeResponse"); #endif Log_Trace(); if (imsg.paxosID == paxosID) proposer.OnProposeResponse(imsg); } void ReplicatedLog::OnLearnChosen(PaxosMessage& imsg) { uint64_t runID; Buffer learnedValue; #ifdef RLOG_DEBUG_MESSAGES Log_Debug("OnLearnChosen begin"); #endif if (context->GetDatabase()->IsCommiting()) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Database is commiting, dropping Paxos message"); #endif return; } Log_Trace(); if (imsg.paxosID > paxosID) { RequestChosen(imsg.nodeID); // I am lagging and need to catch-up return; } else if (imsg.paxosID < paxosID) return; if (imsg.type == PAXOS_LEARN_VALUE) { runID = imsg.runID; learnedValue.Write(imsg.value); context->GetDatabase()->SetAcceptedValue(paxosID, learnedValue); } else if (imsg.type == PAXOS_LEARN_PROPOSAL && acceptor.state.accepted && acceptor.state.acceptedProposalID == imsg.proposalID) { runID = acceptor.state.acceptedRunID; learnedValue.Write(acceptor.state.acceptedValue); } else { RequestChosen(imsg.nodeID); return; } ProcessLearnChosen(imsg.nodeID, runID, learnedValue); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("OnLearnChosen end"); #endif } void ReplicatedLog::OnRequestChosen(PaxosMessage& imsg) { Buffer value; PaxosMessage omsg; #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnRequestChosen, imsg.paxosID = %U, mine = %U", imsg.paxosID, GetPaxosID()); #endif if (imsg.paxosID >= GetPaxosID()) return; // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() > 0) { Log_Trace("Sending paxosID %d to node %d", imsg.paxosID, imsg.nodeID); omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); } else { Log_Trace("Node requested a paxosID I no longer have"); omsg.StartCatchup(paxosID, MY_NODEID); } context->GetTransport()->SendMessage(imsg.nodeID, omsg); } void ReplicatedLog::OnStartCatchup(PaxosMessage& imsg) { #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::OnStartCatchup"); #endif if (imsg.nodeID == context->GetLeaseOwner()) context->OnStartCatchup(); } void ReplicatedLog::ProcessLearnChosen(uint64_t nodeID, uint64_t runID, Buffer& learnedValue) { bool ownAppend; #ifdef RLOG_DEBUG_MESSAGES Log_Debug("Round completed for paxosID = %U", paxosID); Log_Trace("+++ Value for paxosID = %U: %B +++", paxosID, &learnedValue); if (context->GetHighestPaxosID() > 0 && paxosID < context->GetHighestPaxosID() && !IsLeaseOwner()) { Log_Debug("Paxos-based catchup, highest seen paxosID is %U, currently at %U", context->GetHighestPaxosID(), paxosID); if (paxosID == (context->GetHighestPaxosID() - 1)) Log_Debug("Paxos-based catchup complete..."); } #endif if (context->GetHighestPaxosID() > 0 && paxosID < (context->GetHighestPaxosID() - 1)) context->GetDatabase()->Commit(); NewPaxosRound(); // increments paxosID, clears proposer, acceptor if (paxosID <= context->GetHighestPaxosID()) RequestChosen(nodeID); ownAppend = proposer.state.multi; if (nodeID == MY_NODEID && runID == REPLICATION_CONFIG->GetRunID() && context->IsLeaseOwner()) { if (!proposer.state.multi) { proposer.state.multi = true; context->OnIsLeader(); } proposer.state.multi = true; Log_Trace("Multi paxos enabled"); } else { proposer.state.multi = false; Log_Trace("Multi paxos disabled"); } if (BUFCMP(&learnedValue, &dummy)) OnAppendComplete(); else context->OnAppend(paxosID - 1, learnedValue, ownAppend); // new convention: QuorumContext::OnAppend() must call // ReplicatedLog::OnAppendComplete() // when it's done! } void ReplicatedLog::OnRequest(PaxosMessage& imsg) { Log_Trace(); Buffer value; PaxosMessage omsg; if (imsg.paxosID < GetPaxosID()) { // the node is lagging and needs to catch-up context->GetDatabase()->GetAcceptedValue(imsg.paxosID, value); if (value.GetLength() == 0) return; omsg.LearnValue(imsg.paxosID, MY_NODEID, 0, value); context->GetTransport()->SendMessage(imsg.nodeID, omsg); } else if (GetPaxosID() < imsg.paxosID) { // I am lagging and need to catch-up RequestChosen(imsg.nodeID); } } void ReplicatedLog::RequestChosen(uint64_t nodeID) { PaxosMessage omsg; if (context->IsLeaseOwner() || EventLoop::Now() - lastRequestChosenTime < REQUEST_CHOSEN_TIMEOUT) return; lastRequestChosenTime = EventLoop::Now(); omsg.RequestChosen(GetPaxosID(), MY_NODEID); context->GetTransport()->SendMessage(nodeID, omsg); #ifdef RLOG_DEBUG_MESSAGES Log_Debug("ReplicatedLog::RequestChosen, paxosID = %U, to = %U", GetPaxosID(), nodeID); #endif } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Daniel H. Larkin //////////////////////////////////////////////////////////////////////////////// #include "RocksDBEngine/RocksDBKeyBounds.h" #include "Basics/Exceptions.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBTypes.h" using namespace arangodb; using namespace arangodb::rocksutils; using namespace arangodb::velocypack; const char RocksDBKeyBounds::_stringSeparator = '\0'; RocksDBKeyBounds RocksDBKeyBounds::Empty() { return RocksDBKeyBounds(); } RocksDBKeyBounds RocksDBKeyBounds::Databases() { return RocksDBKeyBounds(RocksDBEntryType::Database); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseCollections( TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::Collection, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CollectionDocuments( uint64_t collectionObjectId) { return RocksDBKeyBounds(RocksDBEntryType::Document, collectionObjectId); } RocksDBKeyBounds RocksDBKeyBounds::PrimaryIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::PrimaryIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndexVertex( uint64_t indexId, arangodb::StringRef const& vertexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId, vertexId); } RocksDBKeyBounds RocksDBKeyBounds::IndexEntries(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::GeoIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::GeoIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::GeoIndex(uint64_t indexId, bool isSlot) { RocksDBKeyBounds b; size_t length = sizeof(char) + sizeof(uint64_t) * 2; b._startBuffer.reserve(length); b._startBuffer.push_back(static_cast<char>(RocksDBEntryType::GeoIndexValue)); uint64ToPersistent(b._startBuffer, indexId); b._endBuffer.clear(); b._endBuffer.append(b._startBuffer); // append common prefix uint64_t norm = isSlot ? 0xFFU : 0; // encode slot|pot in lowest bit uint64ToPersistent(b._startBuffer, norm); // lower endian norm = norm | (0xFFFFFFFFULL << 32); uint64ToPersistent(b._endBuffer, norm); return b; } RocksDBKeyBounds RocksDBKeyBounds::IndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseViews(TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::View, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CounterValues() { return RocksDBKeyBounds(RocksDBEntryType::CounterValue); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexPrefix( uint64_t indexId, arangodb::StringRef const& word) { // I did not want to pass a bool to the constructor for this RocksDBKeyBounds bounds; size_t length = sizeof(char) + sizeof(uint64_t) + word.size(); bounds._startBuffer.reserve(length); bounds._startBuffer.push_back( static_cast<char>(RocksDBEntryType::FulltextIndexValue)); uint64ToPersistent(bounds._startBuffer, indexId); bounds._startBuffer.append(word.data(), word.length()); bounds._endBuffer.clear(); bounds._endBuffer.append(bounds._startBuffer); bounds._endBuffer.push_back( 0xFFU); // invalid UTF-8 character, higher than with memcmp bounds._start = rocksdb::Slice(bounds._startBuffer); bounds._end = rocksdb::Slice(bounds._endBuffer); return bounds; } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexComplete( uint64_t indexId, arangodb::StringRef const& word) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId, word); } // ============================ Member Methods ============================== RocksDBKeyBounds& RocksDBKeyBounds::operator=(RocksDBKeyBounds const& other) { _type = other._type; _startBuffer = other._startBuffer; _endBuffer = other._endBuffer; _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); return *this; } rocksdb::Slice const& RocksDBKeyBounds::start() const { TRI_ASSERT(_start.size() > 0); return _start; } rocksdb::Slice const& RocksDBKeyBounds::end() const { TRI_ASSERT(_end.size() > 0); return _end; } uint64_t RocksDBKeyBounds::objectId() const { RocksDBEntryType type = static_cast<RocksDBEntryType>(_startBuffer[0]); switch (type) { case RocksDBEntryType::Document: case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { TRI_ASSERT(_startBuffer.size() >= (sizeof(char) + sizeof(uint64_t))); return uint64FromPersistent(_startBuffer.data() + sizeof(char)); } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_TYPE_ERROR); } } // constructor for an empty bound. do not use for anything but to // default-construct a key bound! RocksDBKeyBounds::RocksDBKeyBounds() : _type(RocksDBEntryType::Database), _startBuffer(), _endBuffer() {} RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::Database: { size_t length = sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } case RocksDBEntryType::CounterValue: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, 0); _endBuffer.reserve(length); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { // Unique VPack index values are stored as follows: // 7 + 8-byte object ID of index + VPack array with index value(s) .... // prefix is the same for non-unique indexes // static slices with an array with one entry VPackSlice min("\x02\x03\x1e"); // [minSlice] VPackSlice max("\x02\x03\x1f"); // [maxSlice] size_t length = sizeof(char) + sizeof(uint64_t) + min.byteSize(); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max _startBuffer.append((char*)(min.begin()), min.byteSize()); _endBuffer.append((char*)(max.begin()), max.byteSize()); break; } case RocksDBEntryType::Collection: case RocksDBEntryType::Document: case RocksDBEntryType::GeoIndexValue: { // Collections are stored as follows: // Key: 1 + 8-byte ArangoDB database ID + 8-byte ArangoDB collection ID // // Documents are stored as follows: // Key: 3 + 8-byte object ID of collection + 8-byte document revision ID size_t length = sizeof(char) + sizeof(uint64_t) * 2; _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max uint64ToPersistent(_startBuffer, 0); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::FulltextIndexValue: case RocksDBEntryType::View: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, arangodb::StringRef const& second) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::FulltextIndexValue: case RocksDBEntryType::EdgeIndexValue: { size_t length = sizeof(char) + sizeof(uint64_t) + second.size() + sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(second.data(), second.length()); _startBuffer.push_back(_stringSeparator); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, VPackSlice const& second, VPackSlice const& third) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { size_t startLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(second.byteSize()) + sizeof(char); _startBuffer.reserve(startLength); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(reinterpret_cast<char const*>(second.begin()), static_cast<size_t>(second.byteSize())); _startBuffer.push_back(_stringSeparator); TRI_ASSERT(_startBuffer.length() == startLength); size_t endLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(third.byteSize()) + sizeof(char); _endBuffer.reserve(endLength); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, first); _endBuffer.append(reinterpret_cast<char const*>(third.begin()), static_cast<size_t>(third.byteSize())); _endBuffer.push_back(_stringSeparator); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } void RocksDBKeyBounds::nextPrefix(std::string& s) { TRI_ASSERT(s.size() >= 1); size_t i = s.size() - 1; for (; (i > 0) && (s[i] == '\xff'); --i) { } if ((i == 0) && (s[i] == '\xff')) { s.push_back('\x00'); return; } s[i] = static_cast<char>(static_cast<unsigned char>(s[i]) + 1); for (i = i + 1; i < s.size(); i++) { s[i] = '\x00'; } } <commit_msg>fix updating of slice<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Daniel H. Larkin //////////////////////////////////////////////////////////////////////////////// #include "RocksDBEngine/RocksDBKeyBounds.h" #include "Basics/Exceptions.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBTypes.h" using namespace arangodb; using namespace arangodb::rocksutils; using namespace arangodb::velocypack; const char RocksDBKeyBounds::_stringSeparator = '\0'; RocksDBKeyBounds RocksDBKeyBounds::Empty() { return RocksDBKeyBounds(); } RocksDBKeyBounds RocksDBKeyBounds::Databases() { return RocksDBKeyBounds(RocksDBEntryType::Database); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseCollections( TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::Collection, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CollectionDocuments( uint64_t collectionObjectId) { return RocksDBKeyBounds(RocksDBEntryType::Document, collectionObjectId); } RocksDBKeyBounds RocksDBKeyBounds::PrimaryIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::PrimaryIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndexVertex( uint64_t indexId, arangodb::StringRef const& vertexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId, vertexId); } RocksDBKeyBounds RocksDBKeyBounds::IndexEntries(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::GeoIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::GeoIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::GeoIndex(uint64_t indexId, bool isSlot) { RocksDBKeyBounds b; size_t length = sizeof(char) + sizeof(uint64_t) * 2; b._startBuffer.reserve(length); b._startBuffer.push_back(static_cast<char>(RocksDBEntryType::GeoIndexValue)); uint64ToPersistent(b._startBuffer, indexId); b._endBuffer.clear(); b._endBuffer.append(b._startBuffer); // append common prefix uint64_t norm = isSlot ? 0xFFU : 0; // encode slot|pot in lowest bit uint64ToPersistent(b._startBuffer, norm); // lower endian norm = norm | (0xFFFFFFFFULL << 32); uint64ToPersistent(b._endBuffer, norm); b._start = rocksdb::Slice(b._startBuffer); b._end = rocksdb::Slice(b._endBuffer); return b; } RocksDBKeyBounds RocksDBKeyBounds::IndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseViews(TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::View, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CounterValues() { return RocksDBKeyBounds(RocksDBEntryType::CounterValue); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexPrefix( uint64_t indexId, arangodb::StringRef const& word) { // I did not want to pass a bool to the constructor for this RocksDBKeyBounds bounds; size_t length = sizeof(char) + sizeof(uint64_t) + word.size(); bounds._startBuffer.reserve(length); bounds._startBuffer.push_back( static_cast<char>(RocksDBEntryType::FulltextIndexValue)); uint64ToPersistent(bounds._startBuffer, indexId); bounds._startBuffer.append(word.data(), word.length()); bounds._endBuffer.clear(); bounds._endBuffer.append(bounds._startBuffer); bounds._endBuffer.push_back( 0xFFU); // invalid UTF-8 character, higher than with memcmp bounds._start = rocksdb::Slice(bounds._startBuffer); bounds._end = rocksdb::Slice(bounds._endBuffer); return bounds; } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexComplete( uint64_t indexId, arangodb::StringRef const& word) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId, word); } // ============================ Member Methods ============================== RocksDBKeyBounds& RocksDBKeyBounds::operator=(RocksDBKeyBounds const& other) { _type = other._type; _startBuffer = other._startBuffer; _endBuffer = other._endBuffer; _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); return *this; } rocksdb::Slice const& RocksDBKeyBounds::start() const { TRI_ASSERT(_start.size() > 0); return _start; } rocksdb::Slice const& RocksDBKeyBounds::end() const { TRI_ASSERT(_end.size() > 0); return _end; } uint64_t RocksDBKeyBounds::objectId() const { RocksDBEntryType type = static_cast<RocksDBEntryType>(_startBuffer[0]); switch (type) { case RocksDBEntryType::Document: case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { TRI_ASSERT(_startBuffer.size() >= (sizeof(char) + sizeof(uint64_t))); return uint64FromPersistent(_startBuffer.data() + sizeof(char)); } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_TYPE_ERROR); } } // constructor for an empty bound. do not use for anything but to // default-construct a key bound! RocksDBKeyBounds::RocksDBKeyBounds() : _type(RocksDBEntryType::Database), _startBuffer(), _endBuffer() {} RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::Database: { size_t length = sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } case RocksDBEntryType::CounterValue: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, 0); _endBuffer.reserve(length); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { // Unique VPack index values are stored as follows: // 7 + 8-byte object ID of index + VPack array with index value(s) .... // prefix is the same for non-unique indexes // static slices with an array with one entry VPackSlice min("\x02\x03\x1e"); // [minSlice] VPackSlice max("\x02\x03\x1f"); // [maxSlice] size_t length = sizeof(char) + sizeof(uint64_t) + min.byteSize(); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max _startBuffer.append((char*)(min.begin()), min.byteSize()); _endBuffer.append((char*)(max.begin()), max.byteSize()); break; } case RocksDBEntryType::Collection: case RocksDBEntryType::Document: case RocksDBEntryType::GeoIndexValue: { // Collections are stored as follows: // Key: 1 + 8-byte ArangoDB database ID + 8-byte ArangoDB collection ID // // Documents are stored as follows: // Key: 3 + 8-byte object ID of collection + 8-byte document revision ID size_t length = sizeof(char) + sizeof(uint64_t) * 2; _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max uint64ToPersistent(_startBuffer, 0); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::FulltextIndexValue: case RocksDBEntryType::View: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, arangodb::StringRef const& second) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::FulltextIndexValue: case RocksDBEntryType::EdgeIndexValue: { size_t length = sizeof(char) + sizeof(uint64_t) + second.size() + sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(second.data(), second.length()); _startBuffer.push_back(_stringSeparator); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, VPackSlice const& second, VPackSlice const& third) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { size_t startLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(second.byteSize()) + sizeof(char); _startBuffer.reserve(startLength); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(reinterpret_cast<char const*>(second.begin()), static_cast<size_t>(second.byteSize())); _startBuffer.push_back(_stringSeparator); TRI_ASSERT(_startBuffer.length() == startLength); size_t endLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(third.byteSize()) + sizeof(char); _endBuffer.reserve(endLength); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, first); _endBuffer.append(reinterpret_cast<char const*>(third.begin()), static_cast<size_t>(third.byteSize())); _endBuffer.push_back(_stringSeparator); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } _start = rocksdb::Slice(_startBuffer); _end = rocksdb::Slice(_endBuffer); } void RocksDBKeyBounds::nextPrefix(std::string& s) { TRI_ASSERT(s.size() >= 1); size_t i = s.size() - 1; for (; (i > 0) && (s[i] == '\xff'); --i) { } if ((i == 0) && (s[i] == '\xff')) { s.push_back('\x00'); return; } s[i] = static_cast<char>(static_cast<unsigned char>(s[i]) + 1); for (i = i + 1; i < s.size(); i++) { s[i] = '\x00'; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2013 Stanford University * * 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 <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/param.h> #include <sys/types.h> #include <string> #include <iostream> using namespace std; #include <ori/version.h> #include <oriutil/debug.h> #include <ori/repo.h> #include <ori/localrepo.h> #include <ori/server.h> #include "fuse_cmd.h" LocalRepo repository; /******************************************************************** * * * Command Infrastructure * * ********************************************************************/ #define CMD_NEED_FUSE 1 #define CMD_DEBUG 2 typedef struct Cmd { const char *name; const char *desc; int (*cmd)(int argc, char * const argv[]); void (*usage)(void); int flags; } Cmd; // General Operations int cmd_addkey(int argc, char * const argv[]); int cmd_branches(int argc, char * const argv[]); int cmd_branch(int argc, char * const argv[]); int cmd_checkout(int argc, char * const argv[]); int cmd_diff(int argc, char * const argv[]); int cmd_filelog(int argc, char * const argv[]); int cmd_findheads(int argc, char * const argv[]); int cmd_gc(int argc, char * const argv[]); void usage_graft(void); int cmd_graft(int argc, char * const argv[]); void usage_list(); int cmd_list(int argc, char * const argv[]); int cmd_listkeys(int argc, char * const argv[]); int cmd_log(int argc, char * const argv[]); int cmd_merge(int argc, char * const argv[]); void usage_newfs(); int cmd_newfs(int argc, char * const argv[]); int cmd_pull(int argc, char * const argv[]); int cmd_rebuildindex(int argc, char * const argv[]); int cmd_rebuildrefs(int argc, char * const argv[]); int cmd_remote(int argc, char * const argv[]); void usage_removefs(); int cmd_removefs(int argc, char * const argv[]); int cmd_removekey(int argc, char * const argv[]); void usage_replicate(void); int cmd_replicate(int argc, char * const argv[]); int cmd_setkey(int argc, char * const argv[]); int cmd_show(int argc, char * const argv[]); void usage_snapshot(void); int cmd_snapshot(int argc, char * const argv[]); int cmd_snapshots(int argc, char * const argv[]); int cmd_status(int argc, char * const argv[]); int cmd_tip(int argc, char * const argv[]); // Debug Operations int cmd_fsck(int argc, char * const argv[]); int cmd_purgesnapshot(int argc, char * const argv[]); int cmd_sshserver(int argc, char * const argv[]); // Internal static int cmd_help(int argc, char * const argv[]); static int cmd_version(int argc, char * const argv[]); static Cmd commands[] = { { "addkey", "Add a trusted public key to the repository", cmd_addkey, NULL, 0, }, { "branch", "Set or print current branch (EXPERIMENTAL)", cmd_branch, NULL, CMD_DEBUG, }, { "branches", "List all available branches (EXPERIMENTAL)", cmd_branches, NULL, CMD_DEBUG, }, { "checkout", "Checkout a revision of the repository (DEBUG)", cmd_checkout, NULL, CMD_DEBUG, }, { "diff", "Display a diff of the pending changes", cmd_diff, NULL, 0, }, { "filelog", "Display a log of change to the specified file", cmd_filelog, NULL, 0, }, { "findheads", "Find lost heads", cmd_findheads, NULL, 0, }, { "gc", "Reclaim unused space", cmd_gc, NULL, 0, }, { "graft", "Graft a subtree from a repository into the local repository", cmd_graft, usage_graft, 0, /* Avoid 0 to allow aliasing of 'cp' */ }, { "help", "Show help for a given topic", cmd_help, NULL, 0, }, { "list", "List local file systems", cmd_list, usage_list, 0, }, { "listkeys", "Display a list of trusted public keys", cmd_listkeys, NULL, 0, }, { "log", "Display a log of commits to the repository", cmd_log, NULL, CMD_NEED_FUSE, }, { "merge", "Merge two heads", cmd_merge, NULL, 0, }, { "newfs", "Create a new file system", cmd_newfs, usage_newfs, 0, }, { "pull", "Pull changes from a repository", cmd_pull, NULL, 0, }, { "purgesnapshot", "Purge snapshot", cmd_purgesnapshot, NULL, 0, }, { "remote", "Remote connection management", cmd_remote, NULL, 0, }, { "removefs", "Remove a local replica", cmd_removefs, usage_removefs, 0, }, { "removekey", "Remove a public key from the repository", cmd_removekey, NULL, 0, }, { "replicate", "Create a local replica", cmd_replicate, usage_replicate, 0, }, { "setkey", "Set the repository private key for signing commits", cmd_setkey, NULL, 0, }, { "show", "Show repository information", cmd_show, NULL, CMD_NEED_FUSE, }, { "snapshot", "Create a repository snapshot", cmd_snapshot, usage_snapshot, CMD_NEED_FUSE, }, { "snapshots", "List all snapshots available in the repository", cmd_snapshots, NULL, CMD_NEED_FUSE, }, { "status", "Scan for changes since last commit", cmd_status, NULL, CMD_NEED_FUSE, }, { "tip", "Print the latest commit on this branch", cmd_tip, NULL, CMD_NEED_FUSE, }, /* Internal (always hidden) */ { "sshserver", NULL, // "Run a simple stdin/out server, intended for SSH access", cmd_sshserver, NULL, 0, }, /* Debugging */ { "fsck", "Check internal state of FUSE file system (DEBUG).", cmd_fsck, NULL, CMD_NEED_FUSE | CMD_DEBUG, }, { "version", "Show version information", cmd_version, NULL, CMD_DEBUG, }, { NULL, NULL, NULL, NULL } }; static int lookupcmd(const char *cmd) { int i; for (i = 0; commands[i].name != NULL; i++) { if (strcmp(commands[i].name, cmd) == 0) return i; } return -1; } static int cmd_help(int argc, char * const argv[]) { int i = 0; if (argc >= 2) { i = lookupcmd(argv[1]); if (i != -1 && commands[i].usage != NULL) { commands[i].usage(); return 0; } if (i == -1) { printf("Unknown command '%s'\n", argv[1]); } else { printf("No help for command '%s'\n", argv[1]); } return 0; } printf("Ori Distributed Personal File System (%s) - Command Line Interface\n\n", ORI_VERSION_STR); printf("Available commands:\n"); for (i = 0; commands[i].name != NULL; i++) { #ifndef DEBUG if (commands[i].flags & CMD_DEBUG) continue; #endif /* DEBUG */ if (commands[i].desc != NULL) printf("%-15s %s\n", commands[i].name, commands[i].desc); } printf("\nPlease report bugs to [email protected]\n"); printf("Website: http://ori.scs.stanford.edu/\n"); return 0; } static int cmd_version(int argc, char * const argv[]) { printf("Ori Distributed Personal File System (%s) - Command Line Interface\n", ORI_VERSION_STR); #ifdef GIT_VERSION printf("Git Commit Id: " GIT_VERSION "\n"); #endif #if defined(DEBUG) || defined(ORI_DEBUG) printf("Build: DEBUG\n"); #elif defined(ORI_PERF) printf("Build: PERF\n"); #else printf("Build: RELEASE\n"); #endif return 0; } int main(int argc, char *argv[]) { bool has_repo = false; int idx; if (argc == 1) { return cmd_help(0, NULL); } idx = lookupcmd(argv[1]); if (idx == -1) { printf("Unknown command '%s'\n", argv[1]); cmd_help(0, NULL); return 1; } // Open the repository for all command except the following if (commands[idx].flags & 0) { try { repository.open(); if (ori_open_log(repository.getLogPath()) < 0) { printf("Couldn't open log!\n"); exit(1); } has_repo = true; } catch (std::exception &e) { // Fall through } } if (commands[idx].flags & CMD_NEED_FUSE) { if (!OF_HasFuse()) { printf("This command must be run on a mounted file system!\n"); exit(1); } } DLOG("Executing '%s'", argv[1]); return commands[idx].cmd(argc-1, (char * const*)argv+1); } <commit_msg>Marking commands as not supported right now<commit_after>/* * Copyright (c) 2012-2013 Stanford University * * 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 <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/param.h> #include <sys/types.h> #include <string> #include <iostream> using namespace std; #include <ori/version.h> #include <oriutil/debug.h> #include <ori/repo.h> #include <ori/localrepo.h> #include <ori/server.h> #include "fuse_cmd.h" LocalRepo repository; /******************************************************************** * * * Command Infrastructure * * ********************************************************************/ #define CMD_NEED_FUSE 1 #define CMD_DEBUG 2 typedef struct Cmd { const char *name; const char *desc; int (*cmd)(int argc, char * const argv[]); void (*usage)(void); int flags; } Cmd; // General Operations int cmd_addkey(int argc, char * const argv[]); int cmd_branches(int argc, char * const argv[]); int cmd_branch(int argc, char * const argv[]); int cmd_checkout(int argc, char * const argv[]); int cmd_diff(int argc, char * const argv[]); int cmd_filelog(int argc, char * const argv[]); int cmd_findheads(int argc, char * const argv[]); int cmd_gc(int argc, char * const argv[]); void usage_graft(void); int cmd_graft(int argc, char * const argv[]); void usage_list(); int cmd_list(int argc, char * const argv[]); int cmd_listkeys(int argc, char * const argv[]); int cmd_log(int argc, char * const argv[]); int cmd_merge(int argc, char * const argv[]); void usage_newfs(); int cmd_newfs(int argc, char * const argv[]); int cmd_pull(int argc, char * const argv[]); int cmd_rebuildindex(int argc, char * const argv[]); int cmd_rebuildrefs(int argc, char * const argv[]); int cmd_remote(int argc, char * const argv[]); void usage_removefs(); int cmd_removefs(int argc, char * const argv[]); int cmd_removekey(int argc, char * const argv[]); void usage_replicate(void); int cmd_replicate(int argc, char * const argv[]); int cmd_setkey(int argc, char * const argv[]); int cmd_show(int argc, char * const argv[]); void usage_snapshot(void); int cmd_snapshot(int argc, char * const argv[]); int cmd_snapshots(int argc, char * const argv[]); int cmd_status(int argc, char * const argv[]); int cmd_tip(int argc, char * const argv[]); // Debug Operations int cmd_fsck(int argc, char * const argv[]); int cmd_purgesnapshot(int argc, char * const argv[]); int cmd_sshserver(int argc, char * const argv[]); // Internal static int cmd_help(int argc, char * const argv[]); static int cmd_version(int argc, char * const argv[]); static Cmd commands[] = { { "addkey", "Add a trusted public key to the repository (NS)", cmd_addkey, NULL, 0, }, { "branch", "Set or print current branch (EXPERIMENTAL) (NS)", cmd_branch, NULL, CMD_DEBUG, }, { "branches", "List all available branches (EXPERIMENTAL) (NS)", cmd_branches, NULL, CMD_DEBUG, }, { "checkout", "Checkout a revision of the repository (DEBUG) (NS)", cmd_checkout, NULL, CMD_DEBUG, }, { "diff", "Display a diff of the pending changes (NS)", cmd_diff, NULL, 0, }, { "filelog", "Display a log of change to the specified file (NS)", cmd_filelog, NULL, 0, }, { "findheads", "Find lost heads (NS)", cmd_findheads, NULL, 0, }, { "gc", "Reclaim unused space (NS)", cmd_gc, NULL, 0, }, { "graft", "Graft a subtree from a repository into the local repository (NS)", cmd_graft, usage_graft, 0, /* 0 to allow aliasing of 'cp' */ }, { "help", "Show help for a given topic", cmd_help, NULL, 0, }, { "list", "List local file systems (NS)", cmd_list, usage_list, 0, }, { "listkeys", "Display a list of trusted public keys (NS)", cmd_listkeys, NULL, 0, }, { "log", "Display a log of commits to the repository", cmd_log, NULL, CMD_NEED_FUSE, }, { "merge", "Merge two heads (NS)", cmd_merge, NULL, 0, }, { "newfs", "Create a new file system", cmd_newfs, usage_newfs, 0, }, { "pull", "Pull changes from a repository (NS)", cmd_pull, NULL, 0, }, { "purgesnapshot", "Purge snapshot (NS)", cmd_purgesnapshot, NULL, 0, }, { "remote", "Remote connection management (NS)", cmd_remote, NULL, 0, }, { "removefs", "Remove a local replica", cmd_removefs, usage_removefs, 0, }, { "removekey", "Remove a public key from the repository (NS)", cmd_removekey, NULL, 0, }, { "replicate", "Create a local replica", cmd_replicate, usage_replicate, 0, }, { "setkey", "Set the repository private key for signing commits (NS)", cmd_setkey, NULL, 0, }, { "show", "Show repository information", cmd_show, NULL, CMD_NEED_FUSE, }, { "snapshot", "Create a repository snapshot", cmd_snapshot, usage_snapshot, CMD_NEED_FUSE, }, { "snapshots", "List all snapshots available in the repository", cmd_snapshots, NULL, CMD_NEED_FUSE, }, { "status", "Scan for changes since last commit", cmd_status, NULL, CMD_NEED_FUSE, }, { "tip", "Print the latest commit on this branch", cmd_tip, NULL, CMD_NEED_FUSE, }, /* Internal (always hidden) */ { "sshserver", NULL, // "Run a simple stdin/out server, intended for SSH access", cmd_sshserver, NULL, 0, }, /* Debugging */ { "fsck", "Check internal state of FUSE file system (DEBUG)", cmd_fsck, NULL, CMD_NEED_FUSE | CMD_DEBUG, }, { "version", "Show version information", cmd_version, NULL, CMD_DEBUG, }, { NULL, NULL, NULL, NULL } }; static int lookupcmd(const char *cmd) { int i; for (i = 0; commands[i].name != NULL; i++) { if (strcmp(commands[i].name, cmd) == 0) return i; } return -1; } static int cmd_help(int argc, char * const argv[]) { int i = 0; if (argc >= 2) { i = lookupcmd(argv[1]); if (i != -1 && commands[i].usage != NULL) { commands[i].usage(); return 0; } if (i == -1) { printf("Unknown command '%s'\n", argv[1]); } else { printf("No help for command '%s'\n", argv[1]); } return 0; } printf("Ori Distributed Personal File System (%s) - Command Line Interface\n\n", ORI_VERSION_STR); printf("Available commands:\n"); for (i = 0; commands[i].name != NULL; i++) { #ifndef DEBUG if (commands[i].flags & CMD_DEBUG) continue; #endif /* DEBUG */ if (commands[i].desc != NULL) printf("%-15s %s\n", commands[i].name, commands[i].desc); } printf("\nPlease report bugs to [email protected]\n"); printf("Website: http://ori.scs.stanford.edu/\n"); return 0; } static int cmd_version(int argc, char * const argv[]) { printf("Ori Distributed Personal File System (%s) - Command Line Interface\n", ORI_VERSION_STR); #ifdef GIT_VERSION printf("Git Commit Id: " GIT_VERSION "\n"); #endif #if defined(DEBUG) || defined(ORI_DEBUG) printf("Build: DEBUG\n"); #elif defined(ORI_PERF) printf("Build: PERF\n"); #else printf("Build: RELEASE\n"); #endif return 0; } int main(int argc, char *argv[]) { bool has_repo = false; int idx; if (argc == 1) { return cmd_help(0, NULL); } idx = lookupcmd(argv[1]); if (idx == -1) { printf("Unknown command '%s'\n", argv[1]); cmd_help(0, NULL); return 1; } // Open the repository for all command except the following if (commands[idx].flags & 0) { try { repository.open(); if (ori_open_log(repository.getLogPath()) < 0) { printf("Couldn't open log!\n"); exit(1); } has_repo = true; } catch (std::exception &e) { // Fall through } } if (commands[idx].flags & CMD_NEED_FUSE) { if (!OF_HasFuse()) { printf("This command must be run on a mounted file system!\n"); exit(1); } } DLOG("Executing '%s'", argv[1]); return commands[idx].cmd(argc-1, (char * const*)argv+1); } <|endoftext|>
<commit_before>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #pragma once #include"ork/orientation.hpp" #if ORK_USE_GLM #include"glm/vec3.hpp" #include"glm/geometric.hpp" namespace ork { namespace GLM {//Kind of deceiving, but whatever struct dunit3 { private: glm::dvec3 _vec; public: ORK_INLINE explicit dunit3(const glm::dvec3&vector) :_vec(glm::normalize(vector)) {} ORK_INLINE dunit3(const double x, const double y, const double z) :_vec(glm::normalize(glm::dvec3(x, y, z))) {} public: ORK_INLINE const glm::dvec3&get()const { return _vec; } ORK_INLINE double&operator[](const size_t index) { return _vec[static_cast<unsigned>(index)]; } ORK_INLINE const double&operator[](const size_t index)const { return _vec[static_cast<unsigned>(index)]; } ORK_INLINE double x()const { return _vec.x; } ORK_INLINE double y()const { return _vec.y; } ORK_INLINE double z()const { return _vec.z; } ORK_INLINE const double&operator[](const unsigned index) const {//unsigned because glm uses int indices return _vec[index]; } ORK_INLINE dunit3 operator-()const { return dunit3(-_vec); } ORK_INLINE unsigned size()const {//unsigned for consistency with glm return 3; } ORK_INLINE unsigned length()const {//For consistency with glm return 3; } }; ORK_INLINE glm::dvec3 operator*(const double lhs, const dunit3&rhs) { return lhs*rhs.get(); } ORK_ORK_EXT(o_stream&) operator<<(o_stream&stream, const dunit3&vec); //Simply tired of defining these ORK_ORK_EXTERN const dunit3 pos_x; ORK_ORK_EXTERN const dunit3 neg_x; ORK_ORK_EXTERN const dunit3 pos_y; ORK_ORK_EXTERN const dunit3 neg_y; ORK_ORK_EXTERN const dunit3 pos_z; ORK_ORK_EXTERN const dunit3 neg_z; //GLM version of loops, needed because GLM uses length() and unsigned as the type #define LOOPVG(SERIES,INDEX)for(unsigned INDEX=0, limit##INDEX=SERIES.length(); INDEX!=limit##INDEX; ++INDEX) #define LOOPVIG(SERIES)LOOPVG(SERIES,i) #define LOOPVJG(SERIES)LOOPVG(SERIES,j) #define LOOPVKG(SERIES)LOOPVG(SERIES,k) #define LOOPVLG(SERIES)LOOPVG(SERIES,l) /* This function basically tests that two floats could have resulted from a single, mathematically equivalent operation float f1=0.2;//Cannot be exactly represented! (One bit either way) float f2=0.1;//ditto Float f2+=0.1;//Maybe 2 bits different now(both bits) assert(f1==f2);//have fun crashing assert(might_be_equal(f1,f2));//We are safe, assuming IEEE 754 (Ok,I am not authoritatively positive) There are false positives with small numbers! */ template<typename T>struct epsilon_type; template<>struct epsilon_type<float> { using type = uint32_t; }; template<>struct epsilon_type<double> { using type = uint64_t; }; template<typename T>struct default_epsilon_factor; template<>struct default_epsilon_factor<float> { static const epsilon_type<float>::type value = static_cast<epsilon_type<float>::type>(0x1) << 4;//A guesstimate }; template<>struct default_epsilon_factor<double> { #if ORK_USE_ACIS static const epsilon_type<double>::type value = static_cast<epsilon_type<double>::type>(0x1) << 4;//This is only verified over time as the minimum upper bound across ACIS when T is double #else //OCC static const epsilon_type<double>::type value = static_cast<epsilon_type<double>::type>(0x1) << 24;//This is only verified over time as the minimum upper bound across OCC when T is double #endif }; template<typename T, typename epsilon_type<T>::type eps_factor = default_epsilon_factor<T>::value> ORK_INLINE ORK_CONSTEXPR T tolerance() { return eps_factor * std::numeric_limits<T>::epsilon(); } namespace detail { template<typename T, typename epsilon_type<T>::type eps_factor = default_epsilon_factor<T>::value, typename epsilon_type<T>::type rel_factor = static_cast<epsilon_type<T>::type>(1)> ORK_INLINE bool equal_simple(const T&lhs, const T&rhs) { static const T abs_eps = tolerance<T, eps_factor>();//We need an absolute epsilon static const T rel_eps = rel_factor * abs_eps;//Factor of 2 to allow for the case of second LSB bump return std::abs(lhs - rhs) <= std::max(abs_eps, rel_eps*std::max(lhs, rhs)); } template<class T> ORK_INLINE bool equal_vector(const T&lhs, const T&rhs) { LOOPVIG(lhs) { if(!equal_simple(lhs[i], rhs[i]))return false; } return true; } template<class T> ORK_INLINE bool equal_matrix(const T&lhs, const T&rhs) { LOOPVIG(lhs) { if(!equal_vector(lhs[i], rhs[i]))return false; } return true; } template<typename T> ORK_INLINE bool less_simple(const T&lhs, const T&rhs) { return lhs < rhs && !equal_simple<T>(lhs, rhs); } template<typename T> ORK_INLINE bool greater_simple(const T&lhs, const T&rhs) { return lhs > rhs && !equal_simple<T>(lhs, rhs); } template<typename T> ORK_INLINE bool less_equal_simple(const T&lhs, const T&rhs) { return lhs < rhs || equal_simple<T>(lhs, rhs); } template<typename T> ORK_INLINE bool greater_equal_simple(const T&lhs, const T&rhs) { return lhs > rhs || equal_simple<T>(lhs, rhs); } }//namespace detail //Use matrix as the default because there are more of them template<typename T> ORK_INLINE bool equal(const T&lhs, const T&rhs) { return detail::equal_matrix<T>(lhs, rhs); } //And we have not bothered to add other overloads template<typename V, glm::precision P> ORK_INLINE bool equal(const glm::tvec3<V, P>&lhs, const glm::tvec3<V, P>&rhs) { return detail::equal_vector<glm::tvec3<V, P>>(lhs, rhs); } template<typename V, glm::precision P> ORK_INLINE bool equal(const glm::tvec4<V, P>&lhs, const glm::tvec4<V, P>&rhs) { return detail::equal_vector<glm::tvec4<V, P>>(lhs, rhs); } ORK_INLINE bool equal(const GLM::dunit3&lhs, const GLM::dunit3&rhs) { return detail::equal_vector<GLM::dunit3>(lhs, rhs); } template<> ORK_INLINE bool equal<float>(const float&lhs, const float&rhs) { return detail::equal_simple<float>(lhs, rhs); } template<> ORK_INLINE bool equal<double>(const double&lhs, const double&rhs) { return detail::equal_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool parallel(const V&v1, const V&v2) { const double norms = glm::length(v1) * glm::length(v2); const double dot = glm::dot(v1, v2); return equal(norms, dot); } template<> ORK_INLINE bool parallel<dunit3>(const dunit3&v1, const dunit3&v2) { const double norms = glm::length(v1.get()) * glm::length(v2.get()); const double dot = glm::dot(v1.get(), v2.get()); return equal(norms, dot); } template<class V> ORK_INLINE bool antiparallel(const V&v1, const V&v2) { return parallel<V>(v1, -v2); } template<class V> ORK_INLINE bool axial(const V&v1, const V&v2) { return parallel<V>(v1, v2) || parallel<V>(v1, -v2); } template<class V> ORK_INLINE bool collinear(const V&v1, const V&v2) {//Just an alias return parallel<V>(v1, v2) || parallel<V>(v1, -v2); } template<class V> ORK_INLINE bool orthogonal(const V&v1, const V&v2) { const double norms = glm::length(v1) * glm::length(v2); const double dot = glm::dot(v1, v2); const bool test = equal(norms, norms + dot); return test; } template<> ORK_INLINE bool orthogonal<dunit3>(const dunit3&v1, const dunit3&v2) { return orthogonal(v1.get(), v2.get()); } /* Some vector functions */ template<class V> ORK_INLINE bool less(const V&v1, const V&v2) { LOOPVIG(v1) { if(equal(v1[i], v2[i]) || v1[i] > v2[i])return false; } return true; } template<> ORK_INLINE bool less<float>(const float&lhs, const float&rhs) { return detail::less_simple<float>(lhs, rhs); } template<> ORK_INLINE bool less<double>(const double&lhs, const double&rhs) { return detail::less_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool greater(const V&v1, const V&v2) { LOOPVIG(v1) { if(equal(v1[i], v2[i]) || v1[i] < v2[i])return false; } return true; } template<> ORK_INLINE bool greater<float>(const float&lhs, const float&rhs) { return detail::greater_simple<float>(lhs, rhs); } template<> ORK_INLINE bool greater<double>(const double&lhs, const double&rhs) { return detail::greater_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool less_equal(const V&v1, const V&v2) { LOOPVIG(v1) { if(greater(v1[i], v2[i]))return false; } return true; } template<> ORK_INLINE bool less_equal<float>(const float&lhs, const float&rhs) { return detail::less_equal_simple<float>(lhs, rhs); } template<> ORK_INLINE bool less_equal<double>(const double&lhs, const double&rhs) { return detail::less_equal_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool greater_equal(const V&v1, const V&v2) { LOOPVIG(v1) { if(less(v1[i], v2[i]))return false; } return true; } template<> ORK_INLINE bool greater_equal<float>(const float&lhs, const float&rhs) { return detail::greater_equal_simple<float>(lhs, rhs); } template<> ORK_INLINE bool greater_equal<double>(const double&lhs, const double&rhs) { return detail::greater_equal_simple<double>(lhs, rhs); } //Rotates a vector about the origin, such that normal would become new_normal if subject to the same rotation ORK_ORK_EXT(glm::dvec3) rotate(const glm::dvec3&vec, const dunit3&normal, const dunit3&new_normal); ORK_ORK_EXT(glm::dvec3) proj_on_plane(const glm::dvec3&vec, const GLM::dunit3&normal); /* Orientation stuff */ ORK_ORK_EXT(const dunit3&) orientation2direction(orientation axis); }//namespace GLM ORK_ORK_EXT(string) to_string(const glm::dvec3&vec); ORK_ORK_EXT(string) to_string(const GLM::dunit3&vec); }//namespace ork namespace glm { ORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec2&vec); ORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec3&vec); } #endif//ORK_USE_GLM<commit_msg>Added 3 bits to OCC tolerance<commit_after>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #pragma once #include"ork/orientation.hpp" #if ORK_USE_GLM #include"glm/vec3.hpp" #include"glm/geometric.hpp" namespace ork { namespace GLM {//Kind of deceiving, but whatever struct dunit3 { private: glm::dvec3 _vec; public: ORK_INLINE explicit dunit3(const glm::dvec3&vector) :_vec(glm::normalize(vector)) {} ORK_INLINE dunit3(const double x, const double y, const double z) :_vec(glm::normalize(glm::dvec3(x, y, z))) {} public: ORK_INLINE const glm::dvec3&get()const { return _vec; } ORK_INLINE double&operator[](const size_t index) { return _vec[static_cast<unsigned>(index)]; } ORK_INLINE const double&operator[](const size_t index)const { return _vec[static_cast<unsigned>(index)]; } ORK_INLINE double x()const { return _vec.x; } ORK_INLINE double y()const { return _vec.y; } ORK_INLINE double z()const { return _vec.z; } ORK_INLINE const double&operator[](const unsigned index) const {//unsigned because glm uses int indices return _vec[index]; } ORK_INLINE dunit3 operator-()const { return dunit3(-_vec); } ORK_INLINE unsigned size()const {//unsigned for consistency with glm return 3; } ORK_INLINE unsigned length()const {//For consistency with glm return 3; } }; ORK_INLINE glm::dvec3 operator*(const double lhs, const dunit3&rhs) { return lhs*rhs.get(); } ORK_ORK_EXT(o_stream&) operator<<(o_stream&stream, const dunit3&vec); //Simply tired of defining these ORK_ORK_EXTERN const dunit3 pos_x; ORK_ORK_EXTERN const dunit3 neg_x; ORK_ORK_EXTERN const dunit3 pos_y; ORK_ORK_EXTERN const dunit3 neg_y; ORK_ORK_EXTERN const dunit3 pos_z; ORK_ORK_EXTERN const dunit3 neg_z; //GLM version of loops, needed because GLM uses length() and unsigned as the type #define LOOPVG(SERIES,INDEX)for(unsigned INDEX=0, limit##INDEX=SERIES.length(); INDEX!=limit##INDEX; ++INDEX) #define LOOPVIG(SERIES)LOOPVG(SERIES,i) #define LOOPVJG(SERIES)LOOPVG(SERIES,j) #define LOOPVKG(SERIES)LOOPVG(SERIES,k) #define LOOPVLG(SERIES)LOOPVG(SERIES,l) /* This function basically tests that two floats could have resulted from a single, mathematically equivalent operation float f1=0.2;//Cannot be exactly represented! (One bit either way) float f2=0.1;//ditto Float f2+=0.1;//Maybe 2 bits different now(both bits) assert(f1==f2);//have fun crashing assert(might_be_equal(f1,f2));//We are safe, assuming IEEE 754 (Ok,I am not authoritatively positive) There are false positives with small numbers! */ template<typename T>struct epsilon_type; template<>struct epsilon_type<float> { using type = uint32_t; }; template<>struct epsilon_type<double> { using type = uint64_t; }; template<typename T>struct default_epsilon_factor; template<>struct default_epsilon_factor<float> { static const epsilon_type<float>::type value = static_cast<epsilon_type<float>::type>(0x1) << 4;//A guesstimate }; template<>struct default_epsilon_factor<double> { #if ORK_USE_ACIS static const epsilon_type<double>::type value = static_cast<epsilon_type<double>::type>(0x1) << 4;//This is only verified over time as the minimum upper bound across ACIS when T is double #else //OCC static const epsilon_type<double>::type value = static_cast<epsilon_type<double>::type>(0x1) << 28;//This is only verified over time as the minimum upper bound across OCC when T is double #endif }; template<typename T, typename epsilon_type<T>::type eps_factor = default_epsilon_factor<T>::value> ORK_INLINE ORK_CONSTEXPR T tolerance() { return eps_factor * std::numeric_limits<T>::epsilon(); } namespace detail { template<typename T, typename epsilon_type<T>::type eps_factor = default_epsilon_factor<T>::value, typename epsilon_type<T>::type rel_factor = static_cast<epsilon_type<T>::type>(1)> ORK_INLINE bool equal_simple(const T&lhs, const T&rhs) { static const T abs_eps = tolerance<T, eps_factor>();//We need an absolute epsilon static const T rel_eps = rel_factor * abs_eps;//Factor of 2 to allow for the case of second LSB bump return std::abs(lhs - rhs) <= std::max(abs_eps, rel_eps*std::max(lhs, rhs)); } template<class T> ORK_INLINE bool equal_vector(const T&lhs, const T&rhs) { LOOPVIG(lhs) { if(!equal_simple(lhs[i], rhs[i]))return false; } return true; } template<class T> ORK_INLINE bool equal_matrix(const T&lhs, const T&rhs) { LOOPVIG(lhs) { if(!equal_vector(lhs[i], rhs[i]))return false; } return true; } template<typename T> ORK_INLINE bool less_simple(const T&lhs, const T&rhs) { return lhs < rhs && !equal_simple<T>(lhs, rhs); } template<typename T> ORK_INLINE bool greater_simple(const T&lhs, const T&rhs) { return lhs > rhs && !equal_simple<T>(lhs, rhs); } template<typename T> ORK_INLINE bool less_equal_simple(const T&lhs, const T&rhs) { return lhs < rhs || equal_simple<T>(lhs, rhs); } template<typename T> ORK_INLINE bool greater_equal_simple(const T&lhs, const T&rhs) { return lhs > rhs || equal_simple<T>(lhs, rhs); } }//namespace detail //Use matrix as the default because there are more of them template<typename T> ORK_INLINE bool equal(const T&lhs, const T&rhs) { return detail::equal_matrix<T>(lhs, rhs); } //And we have not bothered to add other overloads template<typename V, glm::precision P> ORK_INLINE bool equal(const glm::tvec3<V, P>&lhs, const glm::tvec3<V, P>&rhs) { return detail::equal_vector<glm::tvec3<V, P>>(lhs, rhs); } template<typename V, glm::precision P> ORK_INLINE bool equal(const glm::tvec4<V, P>&lhs, const glm::tvec4<V, P>&rhs) { return detail::equal_vector<glm::tvec4<V, P>>(lhs, rhs); } ORK_INLINE bool equal(const GLM::dunit3&lhs, const GLM::dunit3&rhs) { return detail::equal_vector<GLM::dunit3>(lhs, rhs); } template<> ORK_INLINE bool equal<float>(const float&lhs, const float&rhs) { return detail::equal_simple<float>(lhs, rhs); } template<> ORK_INLINE bool equal<double>(const double&lhs, const double&rhs) { return detail::equal_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool parallel(const V&v1, const V&v2) { const double norms = glm::length(v1) * glm::length(v2); const double dot = glm::dot(v1, v2); return equal(norms, dot); } template<> ORK_INLINE bool parallel<dunit3>(const dunit3&v1, const dunit3&v2) { const double norms = glm::length(v1.get()) * glm::length(v2.get()); const double dot = glm::dot(v1.get(), v2.get()); return equal(norms, dot); } template<class V> ORK_INLINE bool antiparallel(const V&v1, const V&v2) { return parallel<V>(v1, -v2); } template<class V> ORK_INLINE bool axial(const V&v1, const V&v2) { return parallel<V>(v1, v2) || parallel<V>(v1, -v2); } template<class V> ORK_INLINE bool collinear(const V&v1, const V&v2) {//Just an alias return parallel<V>(v1, v2) || parallel<V>(v1, -v2); } template<class V> ORK_INLINE bool orthogonal(const V&v1, const V&v2) { const double norms = glm::length(v1) * glm::length(v2); const double dot = glm::dot(v1, v2); const bool test = equal(norms, norms + dot); return test; } template<> ORK_INLINE bool orthogonal<dunit3>(const dunit3&v1, const dunit3&v2) { return orthogonal(v1.get(), v2.get()); } /* Some vector functions */ template<class V> ORK_INLINE bool less(const V&v1, const V&v2) { LOOPVIG(v1) { if(equal(v1[i], v2[i]) || v1[i] > v2[i])return false; } return true; } template<> ORK_INLINE bool less<float>(const float&lhs, const float&rhs) { return detail::less_simple<float>(lhs, rhs); } template<> ORK_INLINE bool less<double>(const double&lhs, const double&rhs) { return detail::less_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool greater(const V&v1, const V&v2) { LOOPVIG(v1) { if(equal(v1[i], v2[i]) || v1[i] < v2[i])return false; } return true; } template<> ORK_INLINE bool greater<float>(const float&lhs, const float&rhs) { return detail::greater_simple<float>(lhs, rhs); } template<> ORK_INLINE bool greater<double>(const double&lhs, const double&rhs) { return detail::greater_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool less_equal(const V&v1, const V&v2) { LOOPVIG(v1) { if(greater(v1[i], v2[i]))return false; } return true; } template<> ORK_INLINE bool less_equal<float>(const float&lhs, const float&rhs) { return detail::less_equal_simple<float>(lhs, rhs); } template<> ORK_INLINE bool less_equal<double>(const double&lhs, const double&rhs) { return detail::less_equal_simple<double>(lhs, rhs); } template<class V> ORK_INLINE bool greater_equal(const V&v1, const V&v2) { LOOPVIG(v1) { if(less(v1[i], v2[i]))return false; } return true; } template<> ORK_INLINE bool greater_equal<float>(const float&lhs, const float&rhs) { return detail::greater_equal_simple<float>(lhs, rhs); } template<> ORK_INLINE bool greater_equal<double>(const double&lhs, const double&rhs) { return detail::greater_equal_simple<double>(lhs, rhs); } //Rotates a vector about the origin, such that normal would become new_normal if subject to the same rotation ORK_ORK_EXT(glm::dvec3) rotate(const glm::dvec3&vec, const dunit3&normal, const dunit3&new_normal); ORK_ORK_EXT(glm::dvec3) proj_on_plane(const glm::dvec3&vec, const GLM::dunit3&normal); /* Orientation stuff */ ORK_ORK_EXT(const dunit3&) orientation2direction(orientation axis); }//namespace GLM ORK_ORK_EXT(string) to_string(const glm::dvec3&vec); ORK_ORK_EXT(string) to_string(const GLM::dunit3&vec); }//namespace ork namespace glm { ORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec2&vec); ORK_ORK_EXT(ork::o_stream&) operator<<(ork::o_stream&stream, const glm::dvec3&vec); } #endif//ORK_USE_GLM<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cclass_unicode.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:04:48 $ * * 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 * ************************************************************************/ #include <cclass_unicode.hxx> #include <com/sun/star/i18n/UnicodeScript.hpp> #include <com/sun/star/i18n/UnicodeType.hpp> #include <i18nutil/unicode.hxx> #include <i18nutil/x_rtl_ustring.h> #include <breakiteratorImpl.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { // ---------------------------------------------------- // class cclass_Unicode // ----------------------------------------------------; cclass_Unicode::cclass_Unicode( uno::Reference < XMultiServiceFactory > xSMgr ) : xMSF( xSMgr ), pTable( NULL ), pStart( NULL ), pCont( NULL ), nStartTypes( 0 ), nContTypes( 0 ), eState( ssGetChar ), cGroupSep( ',' ), cDecimalSep( '.' ) { trans = new Transliteration_casemapping(); cClass = "com.sun.star.i18n.CharacterClassification_Unicode"; } cclass_Unicode::~cclass_Unicode() { destroyParserTable(); delete trans; } OUString SAL_CALL cclass_Unicode::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToUpper, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToLower, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToTitle, rLocale); rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); sal_Unicode* out = pStr->buffer; BreakIteratorImpl brk(xMSF); Boundary bdy = brk.getWordBoundary(Text, nPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES, sal_True); for (sal_Int32 i = nPos; i < nCount + nPos; i++, out++) { if (i >= bdy.endPos) bdy = brk.nextWord(Text, bdy.endPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES); *out = (i == bdy.startPos) ? trans->transliterateChar2Char(Text[i]) : Text[i]; } *out = 0; return OUString( pStr, SAL_NO_ACQUIRE ); } sal_Int16 SAL_CALL cclass_Unicode::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeType(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeDirection(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeScriptType(Text[nPos], (ScriptTypeList*) 0, 0); } sal_Int32 SAL_CALL cclass_Unicode::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getCharType(Text[nPos]); } sal_Int32 SAL_CALL cclass_Unicode::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; if ( Text.getLength() < nPos + nCount ) nCount = Text.getLength() - nPos; sal_Int32 result = 0; for (int i = 0; i < nCount; i++) result |= unicode::getCharType(Text[nPos+i]); return result; } ParseResult SAL_CALL cclass_Unicode::parseAnyToken( const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos ); return r; } ParseResult SAL_CALL cclass_Unicode::parsePredefinedToken( sal_Int32 nTokenType, const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos, nTokenType ); return r; } OUString SAL_CALL cclass_Unicode::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii(cClass); } sal_Bool SAL_CALL cclass_Unicode::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cClass); } Sequence< OUString > SAL_CALL cclass_Unicode::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cClass); return aRet; } } } } } <commit_msg>INTEGRATION: CWS warnings01 (1.8.14); FILE MERGED 2005/11/09 20:21:55 pl 1.8.14.1: #i53898# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cclass_unicode.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:43:36 $ * * 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 * ************************************************************************/ #include <cclass_unicode.hxx> #include <com/sun/star/i18n/UnicodeScript.hpp> #include <com/sun/star/i18n/UnicodeType.hpp> #include <i18nutil/unicode.hxx> #include <i18nutil/x_rtl_ustring.h> #include <breakiteratorImpl.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { // ---------------------------------------------------- // class cclass_Unicode // ----------------------------------------------------; cclass_Unicode::cclass_Unicode( uno::Reference < XMultiServiceFactory > xSMgr ) : xMSF( xSMgr ), pTable( NULL ), pStart( NULL ), pCont( NULL ), nStartTypes( 0 ), nContTypes( 0 ), eState( ssGetChar ), cGroupSep( ',' ), cDecimalSep( '.' ) { trans = new Transliteration_casemapping(); cClass = "com.sun.star.i18n.CharacterClassification_Unicode"; } cclass_Unicode::~cclass_Unicode() { destroyParserTable(); delete trans; } OUString SAL_CALL cclass_Unicode::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToUpper, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToLower, rLocale); return trans->transliterateString2String(Text, nPos, nCount); } OUString SAL_CALL cclass_Unicode::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { sal_Int32 len = Text.getLength(); if (nPos >= len) return OUString(); if (nCount + nPos > len) nCount = len - nPos; trans->setMappingType(MappingTypeToTitle, rLocale); rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); sal_Unicode* out = pStr->buffer; BreakIteratorImpl brk(xMSF); Boundary bdy = brk.getWordBoundary(Text, nPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES, sal_True); for (sal_Int32 i = nPos; i < nCount + nPos; i++, out++) { if (i >= bdy.endPos) bdy = brk.nextWord(Text, bdy.endPos, rLocale, WordType::ANYWORD_IGNOREWHITESPACES); *out = (i == bdy.startPos) ? trans->transliterateChar2Char(Text[i]) : Text[i]; } *out = 0; return OUString( pStr, SAL_NO_ACQUIRE ); } sal_Int16 SAL_CALL cclass_Unicode::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeType(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeDirection(Text[nPos]); } sal_Int16 SAL_CALL cclass_Unicode::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getUnicodeScriptType(Text[nPos], (ScriptTypeList*) 0, 0); } sal_Int32 SAL_CALL cclass_Unicode::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& /*rLocale*/ ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; return unicode::getCharType(Text[nPos]); } sal_Int32 SAL_CALL cclass_Unicode::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& /*rLocale*/ ) throw(RuntimeException) { if ( Text.getLength() <= nPos ) return 0; if ( Text.getLength() < nPos + nCount ) nCount = Text.getLength() - nPos; sal_Int32 result = 0; for (int i = 0; i < nCount; i++) result |= unicode::getCharType(Text[nPos+i]); return result; } ParseResult SAL_CALL cclass_Unicode::parseAnyToken( const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos ); return r; } ParseResult SAL_CALL cclass_Unicode::parsePredefinedToken( sal_Int32 nTokenType, const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { ParseResult r; if ( Text.getLength() <= nPos ) return r; setupParserTable( rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont ); parseText( r, Text, nPos, nTokenType ); return r; } OUString SAL_CALL cclass_Unicode::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii(cClass); } sal_Bool SAL_CALL cclass_Unicode::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cClass); } Sequence< OUString > SAL_CALL cclass_Unicode::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cClass); return aRet; } } } } } <|endoftext|>
<commit_before>#include "util/guidance/turn_lanes.hpp" #include <algorithm> #include <iostream> #include <boost/assert.hpp> namespace osrm { namespace util { namespace guidance { LaneTupel::LaneTupel() : lanes_in_turn(0), first_lane_from_the_right(INVALID_LANEID) { // basic constructor, set everything to zero } LaneTupel::LaneTupel(const LaneID lanes_in_turn, const LaneID first_lane_from_the_right) : lanes_in_turn(lanes_in_turn), first_lane_from_the_right(first_lane_from_the_right) { } // comparation based on interpretation as unsigned 32bit integer bool LaneTupel::operator==(const LaneTupel other) const { static_assert(sizeof(LaneTupel) == sizeof(std::uint16_t), "Comparation requires LaneTupel to be the of size 16Bit"); return *reinterpret_cast<const std::uint16_t *>(this) == *reinterpret_cast<const std::uint16_t *>(&other); } bool LaneTupel::operator!=(const LaneTupel other) const { return !(*this == other); } // comparation based on interpretation as unsigned 32bit integer bool LaneTupel::operator<(const LaneTupel other) const { static_assert(sizeof(LaneTupel) == sizeof(std::uint16_t), "Comparation requires LaneTupel to be the of size 16Bit"); return *reinterpret_cast<const std::uint16_t *>(this) < *reinterpret_cast<const std::uint16_t *>(&other); } } // namespace guidance } // namespace util } // namespace osrm <commit_msg>Fixes Undefined Behavior in LaneTupel (Strict Aliasing), resolves 2665<commit_after>#include "util/guidance/turn_lanes.hpp" #include <algorithm> #include <iostream> #include <tuple> #include <boost/assert.hpp> namespace osrm { namespace util { namespace guidance { LaneTupel::LaneTupel() : lanes_in_turn(0), first_lane_from_the_right(INVALID_LANEID) { // basic constructor, set everything to zero } LaneTupel::LaneTupel(const LaneID lanes_in_turn, const LaneID first_lane_from_the_right) : lanes_in_turn(lanes_in_turn), first_lane_from_the_right(first_lane_from_the_right) { } // comparation based on interpretation as unsigned 32bit integer bool LaneTupel::operator==(const LaneTupel other) const { return std::tie(lanes_in_turn, first_lane_from_the_right) == std::tie(other.lanes_in_turn, other.first_lane_from_the_right); } bool LaneTupel::operator!=(const LaneTupel other) const { return !(*this == other); } // comparation based on interpretation as unsigned 32bit integer bool LaneTupel::operator<(const LaneTupel other) const { return std::tie(lanes_in_turn, first_lane_from_the_right) < std::tie(other.lanes_in_turn, other.first_lane_from_the_right); } } // namespace guidance } // namespace util } // namespace osrm <|endoftext|>
<commit_before>/** * \file * \brief DynamicThreadBase class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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 INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #include "distortos/DynamicSignalsReceiver.hpp" #include "distortos/DynamicThreadParameters.hpp" #include "distortos/ThreadCommon.hpp" #include "distortos/internal/memory/storageDeleter.hpp" #include <functional> namespace distortos { #if CONFIG_THREAD_DETACH_ENABLE == 1 class DynamicThread; #endif // CONFIG_THREAD_DETACH_ENABLE == 1 namespace internal { /** * \brief DynamicThreadBase class is a type-erased interface for thread that has dynamic storage for bound function, * stack and internal DynamicSignalsReceiver object. * * If thread detachment is enabled (CONFIG_THREAD_DETACH_ENABLE is defined) then this class is dynamically allocated by * DynamicThread - which allows it to be "detached". Otherwise - if thread detachment is disabled * (CONFIG_THREAD_DETACH_ENABLE is not defined) - DynamicThread just inherits from this class. */ class DynamicThreadBase : public ThreadCommon { public: #if CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] owner is a reference to owner DynamicThread object * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args); #else // CONFIG_THREAD_DETACH_ENABLE != 1 /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThreadBase{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } #endif // CONFIG_THREAD_DETACH_ENABLE != 1 #if CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; #endif // CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - error codes returned by ThreadCommon::startInternal(); */ int start() { #if CONFIG_THREAD_DETACH_ENABLE == 1 return ThreadCommon::startInternal(run, preTerminationHook, terminationHook); #else // CONFIG_THREAD_DETACH_ENABLE != 1 return ThreadCommon::startInternal(run, nullptr, terminationHook); #endif // CONFIG_THREAD_DETACH_ENABLE != 1 } DynamicThreadBase(const DynamicThreadBase&) = delete; DynamicThreadBase(DynamicThreadBase&&) = default; const DynamicThreadBase& operator=(const DynamicThreadBase&) = delete; DynamicThreadBase& operator=(DynamicThreadBase&&) = delete; protected: #if CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief Pre-termination hook function of thread * * If thread is detached, locks object used for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void preTerminationHook(Thread& thread); /** * \brief Termination hook function of thread * * Calls ThreadCommon::terminationHook() and - if thread is detached - schedules itself for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void terminationHook(Thread& thread); #endif // CONFIG_THREAD_DETACH_ENABLE == 1 private: /** * \brief Helper function to make stack with size adjusted to alignment requirements * * Size of "stack guard" is added to function argument. * * \param [in] stackSize is the size of stack, bytes * * \return Stack object with size adjusted to alignment requirements */ static Stack makeStack(const size_t stackSize) { static_assert(alignof(max_align_t) >= CONFIG_ARCHITECTURE_STACK_ALIGNMENT, "Alignment of dynamically allocated memory is too low!"); const auto adjustedStackSize = (stackSize + CONFIG_ARCHITECTURE_STACK_ALIGNMENT - 1) / CONFIG_ARCHITECTURE_STACK_ALIGNMENT * CONFIG_ARCHITECTURE_STACK_ALIGNMENT; return {{new uint8_t[adjustedStackSize + stackGuardSize], storageDeleter<uint8_t>}, adjustedStackSize + stackGuardSize}; } /** * \brief Thread's "run" function. * * Executes bound function object. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void run(Thread& thread); /// internal DynamicSignalsReceiver object DynamicSignalsReceiver dynamicSignalsReceiver_; /// bound function object std::function<void()> boundFunction_; #if CONFIG_THREAD_DETACH_ENABLE == 1 /// pointer to owner DynamicThread object, nullptr if thread is detached DynamicThread* owner_; #endif // CONFIG_THREAD_DETACH_ENABLE == 1 }; #if CONFIG_THREAD_DETACH_ENABLE == 1 template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args) : ThreadCommon{makeStack(stackSize), priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}, owner_{&owner} { } #else // CONFIG_THREAD_DETACH_ENABLE != 1 template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : ThreadCommon{makeStack(stackSize), priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)} { } #endif // CONFIG_THREAD_DETACH_ENABLE != 1 } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ <commit_msg>Reduce size of DynamicThreadBase when signals are disabled<commit_after>/** * \file * \brief DynamicThreadBase class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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 INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ #include "distortos/DynamicSignalsReceiver.hpp" #include "distortos/DynamicThreadParameters.hpp" #include "distortos/ThreadCommon.hpp" #include "distortos/internal/memory/storageDeleter.hpp" #include <functional> namespace distortos { #if CONFIG_THREAD_DETACH_ENABLE == 1 class DynamicThread; #endif // CONFIG_THREAD_DETACH_ENABLE == 1 namespace internal { /** * \brief DynamicThreadBase class is a type-erased interface for thread that has dynamic storage for bound function, * stack and - if signals are enabled - internal DynamicSignalsReceiver object. * * If thread detachment is enabled (CONFIG_THREAD_DETACH_ENABLE is defined) then this class is dynamically allocated by * DynamicThread - which allows it to be "detached". Otherwise - if thread detachment is disabled * (CONFIG_THREAD_DETACH_ENABLE is not defined) - DynamicThread just inherits from this class. */ class DynamicThreadBase : public ThreadCommon { public: #if CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] owner is a reference to owner DynamicThread object * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args); #else // CONFIG_THREAD_DETACH_ENABLE != 1 /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThreadBase's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThreadBase(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThreadBase{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } #endif // CONFIG_THREAD_DETACH_ENABLE != 1 #if CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; #endif // CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - error codes returned by ThreadCommon::startInternal(); */ int start() { #if CONFIG_THREAD_DETACH_ENABLE == 1 return ThreadCommon::startInternal(run, preTerminationHook, terminationHook); #else // CONFIG_THREAD_DETACH_ENABLE != 1 return ThreadCommon::startInternal(run, nullptr, terminationHook); #endif // CONFIG_THREAD_DETACH_ENABLE != 1 } DynamicThreadBase(const DynamicThreadBase&) = delete; DynamicThreadBase(DynamicThreadBase&&) = default; const DynamicThreadBase& operator=(const DynamicThreadBase&) = delete; DynamicThreadBase& operator=(DynamicThreadBase&&) = delete; protected: #if CONFIG_THREAD_DETACH_ENABLE == 1 /** * \brief Pre-termination hook function of thread * * If thread is detached, locks object used for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void preTerminationHook(Thread& thread); /** * \brief Termination hook function of thread * * Calls ThreadCommon::terminationHook() and - if thread is detached - schedules itself for deferred deletion. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void terminationHook(Thread& thread); #endif // CONFIG_THREAD_DETACH_ENABLE == 1 private: /** * \brief Helper function to make stack with size adjusted to alignment requirements * * Size of "stack guard" is added to function argument. * * \param [in] stackSize is the size of stack, bytes * * \return Stack object with size adjusted to alignment requirements */ static Stack makeStack(const size_t stackSize) { static_assert(alignof(max_align_t) >= CONFIG_ARCHITECTURE_STACK_ALIGNMENT, "Alignment of dynamically allocated memory is too low!"); const auto adjustedStackSize = (stackSize + CONFIG_ARCHITECTURE_STACK_ALIGNMENT - 1) / CONFIG_ARCHITECTURE_STACK_ALIGNMENT * CONFIG_ARCHITECTURE_STACK_ALIGNMENT; return {{new uint8_t[adjustedStackSize + stackGuardSize], storageDeleter<uint8_t>}, adjustedStackSize + stackGuardSize}; } /** * \brief Thread's "run" function. * * Executes bound function object. * * \param [in] thread is a reference to Thread object, this must be DynamicThreadBase! */ static void run(Thread& thread); #if CONFIG_SIGNALS_ENABLE == 1 /// internal DynamicSignalsReceiver object DynamicSignalsReceiver dynamicSignalsReceiver_; #endif // CONFIG_SIGNALS_ENABLE == 1 /// bound function object std::function<void()> boundFunction_; #if CONFIG_THREAD_DETACH_ENABLE == 1 /// pointer to owner DynamicThread object, nullptr if thread is detached DynamicThread* owner_; #endif // CONFIG_THREAD_DETACH_ENABLE == 1 }; #if CONFIG_SIGNALS_ENABLE == 1 && CONFIG_THREAD_DETACH_ENABLE == 1 template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args) : ThreadCommon{makeStack(stackSize), priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}, owner_{&owner} { } #elif CONFIG_SIGNALS_ENABLE == 1 && CONFIG_THREAD_DETACH_ENABLE != 1 template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : ThreadCommon{makeStack(stackSize), priority, schedulingPolicy, nullptr, canReceiveSignals == true ? &dynamicSignalsReceiver_ : nullptr}, dynamicSignalsReceiver_{canReceiveSignals == true ? queuedSignals : 0, canReceiveSignals == true ? signalActions : 0}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)} { } #elif CONFIG_SIGNALS_ENABLE != 1 && CONFIG_THREAD_DETACH_ENABLE == 1 template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, bool, size_t, size_t, const uint8_t priority, const SchedulingPolicy schedulingPolicy, DynamicThread& owner, Function&& function, Args&&... args) : ThreadCommon{makeStack(stackSize), priority, schedulingPolicy, nullptr, nullptr}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}, owner_{&owner} { } #else // CONFIG_SIGNALS_ENABLE != 1 && CONFIG_THREAD_DETACH_ENABLE != 1 template<typename Function, typename... Args> DynamicThreadBase::DynamicThreadBase(const size_t stackSize, bool, size_t, size_t, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : ThreadCommon{makeStack(stackSize), priority, schedulingPolicy, nullptr, nullptr}, boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)} { } #endif // CONFIG_SIGNALS_ENABLE != 1 && CONFIG_THREAD_DETACH_ENABLE != 1 } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SCHEDULER_DYNAMICTHREADBASE_HPP_ <|endoftext|>
<commit_before>/* * MD5 hash in C and x86 assembly * * Copyright (c) 2016 Project Nayuki * https://www.nayuki.io/page/fast-md5-hash-implementation-in-x86-assembly * * (MIT License) * 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 "md5.h" // for rawspeed::md5::state, md5_hash #include <array> // for array #include <cstdint> // for UINT32_C, uint8_t #include <cstring> // for strlen #include <gtest/gtest.h> // for AssertionResult, IsNullLiteralHelper, Param... #include <utility> // for pair, make_pair using MD5Testcase = std::pair<rawspeed::md5::md5_state, const uint8_t*>; class MD5Test : public ::testing::TestWithParam<MD5Testcase> { protected: MD5Test() = default; virtual void SetUp() override { auto p = GetParam(); answer = p.first; message = p.second; } rawspeed::md5::md5_state answer; const uint8_t* message; }; #define TESTCASE(a, b, c, d, msg) \ { \ std::make_pair((rawspeed::md5::md5_state){{UINT32_C(a), UINT32_C(b), \ UINT32_C(c), UINT32_C(d)}}, \ (const uint8_t*)(msg)) \ } // Note: The MD5 standard specifies that uint32 are serialized to/from bytes in // little endian static MD5Testcase testCases[] = { TESTCASE(0xD98C1DD4, 0x04B2008F, 0x980980E9, 0x7E42F8EC, ""), TESTCASE(0xB975C10C, 0xA8B6F1C0, 0xE299C331, 0x61267769, "a"), TESTCASE(0x98500190, 0xB04FD23C, 0x7D3F96D6, 0x727FE128, "abc"), TESTCASE(0x7D696BF9, 0x8D93B77C, 0x312F5A52, 0xD061F1AA, "message digest"), TESTCASE(0xD7D3FCC3, 0x00E49261, 0x6C49FB7D, 0x3BE167CA, "abcdefghijklmnopqrstuvwxyz"), TESTCASE(0x98AB74D1, 0xF5D977D2, 0x2C1C61A5, 0x9F9D419F, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), TESTCASE(0xA2F4ED57, 0x55C9E32B, 0x2EDA49AC, 0x7AB60721, "12345678901234567890123456789012345678901234567890123456789012345" "678901234567890"), }; INSTANTIATE_TEST_CASE_P(MD5Test, MD5Test, ::testing::ValuesIn(testCases)); TEST_P(MD5Test, CheckTestCaseSet) { ASSERT_NO_THROW({ rawspeed::md5::md5_state hash; rawspeed::md5::md5_hash(message, strlen((const char*)message), &hash); ASSERT_EQ(hash, answer); }); } <commit_msg>MD5Test: nullptr-init that pointer<commit_after>/* * MD5 hash in C and x86 assembly * * Copyright (c) 2016 Project Nayuki * https://www.nayuki.io/page/fast-md5-hash-implementation-in-x86-assembly * * (MIT License) * 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 "md5.h" // for rawspeed::md5::state, md5_hash #include <array> // for array #include <cstdint> // for UINT32_C, uint8_t #include <cstring> // for strlen #include <gtest/gtest.h> // for AssertionResult, IsNullLiteralHelper, Param... #include <utility> // for pair, make_pair using MD5Testcase = std::pair<rawspeed::md5::md5_state, const uint8_t*>; class MD5Test : public ::testing::TestWithParam<MD5Testcase> { protected: MD5Test() = default; virtual void SetUp() override { auto p = GetParam(); answer = p.first; message = p.second; } rawspeed::md5::md5_state answer; const uint8_t* message = nullptr; }; #define TESTCASE(a, b, c, d, msg) \ { \ std::make_pair((rawspeed::md5::md5_state){{UINT32_C(a), UINT32_C(b), \ UINT32_C(c), UINT32_C(d)}}, \ (const uint8_t*)(msg)) \ } // Note: The MD5 standard specifies that uint32 are serialized to/from bytes in // little endian static MD5Testcase testCases[] = { TESTCASE(0xD98C1DD4, 0x04B2008F, 0x980980E9, 0x7E42F8EC, ""), TESTCASE(0xB975C10C, 0xA8B6F1C0, 0xE299C331, 0x61267769, "a"), TESTCASE(0x98500190, 0xB04FD23C, 0x7D3F96D6, 0x727FE128, "abc"), TESTCASE(0x7D696BF9, 0x8D93B77C, 0x312F5A52, 0xD061F1AA, "message digest"), TESTCASE(0xD7D3FCC3, 0x00E49261, 0x6C49FB7D, 0x3BE167CA, "abcdefghijklmnopqrstuvwxyz"), TESTCASE(0x98AB74D1, 0xF5D977D2, 0x2C1C61A5, 0x9F9D419F, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), TESTCASE(0xA2F4ED57, 0x55C9E32B, 0x2EDA49AC, 0x7AB60721, "12345678901234567890123456789012345678901234567890123456789012345" "678901234567890"), }; INSTANTIATE_TEST_CASE_P(MD5Test, MD5Test, ::testing::ValuesIn(testCases)); TEST_P(MD5Test, CheckTestCaseSet) { ASSERT_NO_THROW({ rawspeed::md5::md5_state hash; rawspeed::md5::md5_hash(message, strlen((const char*)message), &hash); ASSERT_EQ(hash, answer); }); } <|endoftext|>
<commit_before>#include "collision.h" #include <cmath> //if the sum of the radius is <= the distance, the spheres collide bool Overlap::isOverlapping(Shape::Circle left, Shape::Circle right){ return distance(left.center, right.center) <= left.radius + right.radius; } //Returns whether the point exists within the sphere bool Overlap::isOverlapping(Shape::Circle circle, Shape::Point point){ return distance(circle.center, point.center) <= circle.radius; } //sqrt( (x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2 ) double Overlap::distance(Vector2D a, Vector2D b) { return sqrt(pow(b.x() - a.x(), 2) + pow(b.y() - a.y(), 2) + pow(b.z() - a.z(), 2)); }<commit_msg>Renamed Collision to Overlap<commit_after>#include "overlap.h" #include <cmath> //if the sum of the radius is <= the distance, the spheres collide bool Overlap::isOverlapping(Shape::Circle left, Shape::Circle right){ return distance(left.center, right.center) <= left.radius + right.radius; } //Returns whether the point exists within the sphere bool Overlap::isOverlapping(Shape::Circle circle, Shape::Point point){ return distance(circle.center, point.center) <= circle.radius; } //sqrt( (x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2 ) double Overlap::distance(Vector2D a, Vector2D b) { return sqrt(pow(b.x() - a.x(), 2) + pow(b.y() - a.y(), 2) + pow(b.z() - a.z(), 2)); }<|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../StroikaPreComp.h" #include <cstdlib> #include <cstring> #include <ctime> #if qPlatform_POSIX #include <time.h> #endif #include "../Configuration/Common.h" #include "../Characters/String.h" #include "../Debug/Assertions.h" #include "DateTime.h" #include "Timezone.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Time; /* ******************************************************************************** ********************************* Time::GetTimezone **************************** ******************************************************************************** */ String Time::GetTimezone () { return GetTimezone (DateTime::Now ()); } String Time::GetTimezone (bool applyDST) { #if qPlatform_Windows TIME_ZONE_INFORMATION tzInfo; memset (&tzInfo, 0, sizeof (tzInfo)); (void)::GetTimeZoneInformation (&tzInfo); return String::FromSDKString (tzInfo.StandardName); #elif qPlatform_POSIX // @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html return String::FromSDKString (IsDaylightSavingsTime (DateTime::Now ()) ? tzname[1] : tzname[0]); #else AssertNotImplemented (); return String (); #endif } String Time::GetTimezone (const DateTime& d) { return GetTimezone (IsDaylightSavingsTime (d)); } /* ******************************************************************************** *********************** Time::IsDaylightSavingsTime **************************** ******************************************************************************** */ bool Time::IsDaylightSavingsTime (const DateTime& d) { struct tm asTM = d.As<struct tm> (); asTM.tm_isdst = -1; // force calc of correct daylight savings time flag // THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work... // So far it seems too however, --LGP 2011-10-15 time_t result = mktime (&asTM); return asTM.tm_isdst >= 1; } /* ******************************************************************************** ********************* Time::GetLocaltimeToGMTOffset **************************** ******************************************************************************** */ time_t Time::GetLocaltimeToGMTOffset (bool applyDST) { #if 0 // WRONG - but COULD use this API - but not sure needed #if qPlatform_Windows TIME_ZONE_INFORMATION tzInfo; memset (&tzInfo, 0, sizeof (tzInfo)); (void)::GetTimeZoneInformation (&tzInfo); int unsignedBias = abs (tzInfo.Bias); int hrs = unsignedBias / 60; int mins = unsignedBias - hrs * 60; tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0 ? L"-" : L"+"), hrs, mins); #endif #endif /* * COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the * timezone global var??? */ struct tm tm; memset (&tm, 0, sizeof(tm)); tm.tm_year = 70; tm.tm_mon = 0; // Jan tm.tm_mday = 1; tm.tm_isdst = applyDST; time_t result = mktime (&tm); return result; } time_t Time::GetLocaltimeToGMTOffset (const DateTime& forTime) { return GetLocaltimeToGMTOffset (IsDaylightSavingsTime (forTime)); }<commit_msg>minor fixes for windows narrow-A TCHAR builds<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../StroikaPreComp.h" #include <cstdlib> #include <cstring> #include <ctime> #if qPlatform_POSIX #include <time.h> #endif #include "../Configuration/Common.h" #include "../Characters/String.h" #include "../Debug/Assertions.h" #include "DateTime.h" #include "Timezone.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Time; /* ******************************************************************************** ********************************* Time::GetTimezone **************************** ******************************************************************************** */ String Time::GetTimezone () { return GetTimezone (DateTime::Now ()); } String Time::GetTimezone (bool applyDST) { #if qPlatform_Windows TIME_ZONE_INFORMATION tzInfo; memset (&tzInfo, 0, sizeof (tzInfo)); (void)::GetTimeZoneInformation (&tzInfo); return tzInfo.StandardName; #elif qPlatform_POSIX // @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html return String::FromSDKString (IsDaylightSavingsTime (DateTime::Now ()) ? tzname[1] : tzname[0]); #else AssertNotImplemented (); return String (); #endif } String Time::GetTimezone (const DateTime& d) { return GetTimezone (IsDaylightSavingsTime (d)); } /* ******************************************************************************** *********************** Time::IsDaylightSavingsTime **************************** ******************************************************************************** */ bool Time::IsDaylightSavingsTime (const DateTime& d) { struct tm asTM = d.As<struct tm> (); asTM.tm_isdst = -1; // force calc of correct daylight savings time flag // THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work... // So far it seems too however, --LGP 2011-10-15 time_t result = mktime (&asTM); return asTM.tm_isdst >= 1; } /* ******************************************************************************** ********************* Time::GetLocaltimeToGMTOffset **************************** ******************************************************************************** */ time_t Time::GetLocaltimeToGMTOffset (bool applyDST) { #if 0 // WRONG - but COULD use this API - but not sure needed #if qPlatform_Windows TIME_ZONE_INFORMATION tzInfo; memset (&tzInfo, 0, sizeof (tzInfo)); (void)::GetTimeZoneInformation (&tzInfo); int unsignedBias = abs (tzInfo.Bias); int hrs = unsignedBias / 60; int mins = unsignedBias - hrs * 60; tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0 ? L"-" : L"+"), hrs, mins); #endif #endif /* * COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the * timezone global var??? */ struct tm tm; memset (&tm, 0, sizeof(tm)); tm.tm_year = 70; tm.tm_mon = 0; // Jan tm.tm_mday = 1; tm.tm_isdst = applyDST; time_t result = mktime (&tm); return result; } time_t Time::GetLocaltimeToGMTOffset (const DateTime& forTime) { return GetLocaltimeToGMTOffset (IsDaylightSavingsTime (forTime)); }<|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QApplication> #include <QStyle> #include <QTimer> #include <QVBoxLayout> // CTK includes #include "ctkDirectoryButton.h" // STD includes #include <cstdlib> #include <iostream> //----------------------------------------------------------------------------- int ctkDirectoryButtonTest1(int argc, char * argv [] ) { QApplication app(argc, argv); QWidget topLevel; ctkDirectoryButton button; QIcon defaultIcon = button.style()->standardIcon(QStyle::SP_DirIcon); QIcon icon = button.style()->standardIcon(QStyle::SP_MessageBoxQuestion); QIcon icon2 = button.style()->standardIcon(QStyle::SP_DesktopIcon); ctkDirectoryButton button2("."); ctkDirectoryButton button3(icon, ".."); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(&button); layout->addWidget(&button2); layout->addWidget(&button3); topLevel.setLayout(layout); button.setCaption("Select a directory"); if (button.caption() != "Select a directory") { std::cerr << "ctkDirectoryButton::setCaption() failed." << std::endl; return EXIT_FAILURE; } if (button.icon().pixmap(20).toImage() != defaultIcon.pixmap(20).toImage()) { std::cerr << "ctkDirectoryButton::icon() failed." << std::endl; return EXIT_FAILURE; } button3.setIcon(icon2); if (button3.icon().pixmap(20).toImage() != icon2.pixmap(20).toImage()) { std::cerr << "ctkDirectoryButton::setIcon() failed." << std::endl; return EXIT_FAILURE; } #ifdef USE_QFILEDIALOG_OPTIONS button.setOptions(QFileDialog::ShowDirsOnly | QFileDialog::ReadOnly); if (button.options() != (QFileDialog::ShowDirsOnly | QFileDialog::ReadOnly)) #else button.setOptions(ctkDirectoryButton::ShowDirsOnly | ctkDirectoryButton::ReadOnly); if (button.options() != (ctkDirectoryButton::ShowDirsOnly | ctkDirectoryButton::ReadOnly)) #endif { std::cerr<< "ctkDirectoryButton::setOptions failed" << std::endl; return EXIT_FAILURE; } button.setDirectory(QDir::home().absolutePath()); if ( QDir(button.directory()) != QDir::home()) { std::cerr<< "ctkDirectoryButton::setDirectory failed" << button.directory().toStdString() << std::endl; return EXIT_FAILURE; } //button.browse(); topLevel.show(); if (argc < 2 || QString(argv[1]) != "-I" ) { QTimer::singleShot(200, &app, SLOT(quit())); } return app.exec(); } <commit_msg>Add more tests to ctkDirectoryButtonTest1<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QApplication> #include <QSignalSpy> #include <QStyle> #include <QTimer> #include <QVBoxLayout> // CTK includes #include "ctkDirectoryButton.h" // STD includes #include <cstdlib> #include <iostream> //----------------------------------------------------------------------------- int ctkDirectoryButtonTest1(int argc, char * argv [] ) { QApplication app(argc, argv); QWidget topLevel; ctkDirectoryButton button; QIcon defaultIcon = button.style()->standardIcon(QStyle::SP_DirIcon); QIcon icon = button.style()->standardIcon(QStyle::SP_MessageBoxQuestion); QIcon icon2 = button.style()->standardIcon(QStyle::SP_DesktopIcon); ctkDirectoryButton button2("."); ctkDirectoryButton button3(icon, ".."); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(&button); layout->addWidget(&button2); layout->addWidget(&button3); topLevel.setLayout(layout); button.setCaption("Select a directory"); if (button.caption() != "Select a directory") { std::cerr << "ctkDirectoryButton::setCaption() failed." << std::endl; return EXIT_FAILURE; } if (button.icon().pixmap(20).toImage() != defaultIcon.pixmap(20).toImage()) { std::cerr << "ctkDirectoryButton::icon() failed." << std::endl; return EXIT_FAILURE; } button3.setIcon(icon2); if (button3.icon().pixmap(20).toImage() != icon2.pixmap(20).toImage()) { std::cerr << "ctkDirectoryButton::setIcon() failed." << std::endl; return EXIT_FAILURE; } #ifdef USE_QFILEDIALOG_OPTIONS button.setOptions(QFileDialog::ShowDirsOnly | QFileDialog::ReadOnly); if (button.options() != (QFileDialog::ShowDirsOnly | QFileDialog::ReadOnly)) #else button.setOptions(ctkDirectoryButton::ShowDirsOnly | ctkDirectoryButton::ReadOnly); if (button.options() != (ctkDirectoryButton::ShowDirsOnly | ctkDirectoryButton::ReadOnly)) #endif { std::cerr<< "ctkDirectoryButton::setOptions failed" << std::endl; return EXIT_FAILURE; } QSignalSpy spyDirectoryChanged(&button, SIGNAL(directoryChanged(const QString&))); QSignalSpy spyDirectorySelected(&button, SIGNAL(directorySelected(const QString&))); button.setDirectory(QDir::home().absolutePath()); if ( QDir(button.directory()) != QDir::home() || spyDirectoryChanged.count() != 1 || spyDirectorySelected.count() != 1) { std::cerr<< "ctkDirectoryButton::setDirectory failed" << button.directory().toStdString() << std::endl; return EXIT_FAILURE; } spyDirectoryChanged.clear(); spyDirectorySelected.clear(); // set it again... just to check that it doesn't fire a new signal button.setDirectory(QDir::home().absolutePath()); if ( QDir(button.directory()) != QDir::home() || spyDirectoryChanged.count() != 0 || spyDirectorySelected.count() != 1) { std::cerr<< "ctkDirectoryButton::setDirectory failed" << button.directory().toStdString() << std::endl; return EXIT_FAILURE; } topLevel.show(); if (argc < 2 || QString(argv[1]) != "-I" ) { QTimer::singleShot(200, &app, SLOT(quit())); } QTimer::singleShot(100, &button, SLOT(browse())); return app.exec(); } <|endoftext|>