text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * $RCSfile: salobj.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kr $ $Date: 2001-02-22 14:13:05 $ * * 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): _______________________________________ * * ************************************************************************/ #define _SV_SALOBJ_CXX #include <prex.h> #include <X11/Xlib.h> #include <X11/extensions/shape.h> #ifdef USE_MOTIF #include <Xm/DrawingA.h> #else #include <X11/Xaw/Label.h> #endif #include <postx.h> #include <salunx.h> #include <salstd.hxx> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALINST_HXX #include <salinst.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALFRAME_HXX #include <salframe.hxx> #endif #ifndef _SV_SALOBJ_HXX #include <salobj.hxx> #endif #ifdef USE_MOTIF #define OBJECT_WIDGET_CLASS xmDrawingAreaWidgetClass #else #define OBJECT_WIDGET_CLASS labelWidgetClass #endif SalObjectList SalObjectData::aAllObjects; // ======================================================================= long ImplSalObjCallbackDummy( void*, SalObject*, USHORT, const void* ) { return 0; } // ======================================================================= // SalInstance memberfkts to create and destroy a SalObject SalObject* SalInstance::CreateObject( SalFrame* pParent ) { int error_base, event_base; SalObject* pObject = new SalObject; SystemChildData* pObjData = const_cast<SystemChildData*>(pObject->GetSystemData()); if ( ! XShapeQueryExtension( (Display*)pObjData->pDisplay, &event_base, &error_base ) ) { delete pObject; return NULL; } SalDisplay* pSalDisp = pParent->maFrameData.GetDisplay(); Widget pWidgetParent = pParent->maFrameData.GetWidget(); pObject->maObjectData.maPrimary = XtVaCreateWidget( "salobject primary", OBJECT_WIDGET_CLASS, pWidgetParent, NULL ); pObject->maObjectData.maSecondary = XtVaCreateWidget( "salobject secondary", OBJECT_WIDGET_CLASS, pObject->maObjectData.maPrimary, NULL ); XtRealizeWidget( pObject->maObjectData.maPrimary ); XtRealizeWidget( pObject->maObjectData.maSecondary ); pObjData->pDisplay = XtDisplay( pObject->maObjectData.maPrimary ); pObjData->aWindow = XtWindow( pObject->maObjectData.maSecondary ); pObjData->pWidget = pObject->maObjectData.maSecondary; pObjData->pVisual = pSalDisp->GetVisual()->GetVisual(); pObjData->nDepth = pSalDisp->GetVisual()->GetDepth(); pObjData->aColormap = pSalDisp->GetColormap().GetXColormap(); pObjData->pAppContext = pSalDisp->GetXLib()->GetAppContext(); return pObject; } void SalInstance::DestroyObject( SalObject* pObject ) { delete pObject; } // ====================================================================== // SalClipRegion is a member of SalObject // definition of SalClipRegion my be found in unx/inc/salobj.h SalClipRegion::SalClipRegion() { ClipRectangleList = NULL; numClipRectangles = 0; maxClipRectangles = 0; nClipRegionType = SAL_OBJECT_CLIP_INCLUDERECTS; } SalClipRegion::~SalClipRegion() { if ( ClipRectangleList ) delete ClipRectangleList; } void SalClipRegion::BeginSetClipRegion( ULONG nRects ) { if (ClipRectangleList) delete ClipRectangleList; ClipRectangleList = new XRectangle[nRects]; numClipRectangles = 0; maxClipRectangles = nRects; } void SalClipRegion::UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) { if ( nWidth && nHeight && (numClipRectangles < maxClipRectangles) ) { XRectangle *aRect = ClipRectangleList + numClipRectangles; aRect->x = (short) nX; aRect->y = (short) nY; aRect->width = (unsigned short) nWidth; aRect->height= (unsigned short) nHeight; numClipRectangles++; } } // ======================================================================= // SalObject Implementation SalObject::SalObject() { maObjectData.maSystemChildData.nSize = sizeof( SystemChildData ); maObjectData.maSystemChildData.pDisplay = GetSalData()->GetDefDisp()->GetDisplay(); maObjectData.maSystemChildData.aWindow = None; maObjectData.maSystemChildData.pSalFrame = 0; maObjectData.maSystemChildData.pWidget = 0; maObjectData.maSystemChildData.pVisual = 0; maObjectData.maSystemChildData.nDepth = 0; maObjectData.maSystemChildData.aColormap = 0; maObjectData.maSystemChildData.pAppContext = NULL; maObjectData.maSystemChildData.aShellWindow = 0; maObjectData.maSystemChildData.pShellWidget = NULL; maObjectData.mpInst = NULL; maObjectData.mpProc = ImplSalObjCallbackDummy; maObjectData.maPrimary = NULL; maObjectData.maSecondary = NULL; SalObjectData::aAllObjects.Insert( this, LIST_APPEND ); } SalObject::~SalObject() { SalObjectData::aAllObjects.Remove( this ); if ( maObjectData.maPrimary ) XtDestroyWidget ( maObjectData.maPrimary ); if ( maObjectData.maSecondary ) XtDestroyWidget ( maObjectData.maSecondary ); } void SalObject::ResetClipRegion() { maObjectData.maClipRegion.ResetClipRegion(); const int dest_kind = ShapeBounding; const int op = ShapeSet; const int ordering = YSorted; XWindowAttributes win_attrib; XRectangle win_size; XGetWindowAttributes ( (Display*)maObjectData.maSystemChildData.pDisplay, maObjectData.maSystemChildData.aWindow, &win_attrib ); win_size.x = 0; win_size.y = 0; win_size.width = win_attrib.width; win_size.height = win_attrib.width; XShapeCombineRectangles ( (Display*)maObjectData.maSystemChildData.pDisplay, maObjectData.maSystemChildData.aWindow, dest_kind, 0, 0, // x_off, y_off &win_size, // list of rectangles 1, // number of rectangles op, ordering ); } void SalObject::BeginSetClipRegion( ULONG nRectCount ) { maObjectData.maClipRegion.BeginSetClipRegion ( nRectCount ); } void SalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) { maObjectData.maClipRegion.UnionClipRegion ( nX, nY, nWidth, nHeight ); } void SalObject::EndSetClipRegion() { XRectangle *pRectangles = maObjectData.maClipRegion.EndSetClipRegion (); const int nType = maObjectData.maClipRegion.GetClipRegionType(); const int nRectangles = maObjectData.maClipRegion.GetRectangleCount(); const int dest_kind = ShapeBounding; const int ordering = YSorted; int op; switch ( nType ) { case SAL_OBJECT_CLIP_INCLUDERECTS : op = ShapeSet; break; case SAL_OBJECT_CLIP_EXCLUDERECTS : op = ShapeSubtract; break; case SAL_OBJECT_CLIP_ABSOLUTE : op = ShapeSet; break; default : op = ShapeUnion; } XShapeCombineRectangles ( (Display*)maObjectData.maSystemChildData.pDisplay, maObjectData.maSystemChildData.aWindow, dest_kind, 0, 0, // x_off, y_off pRectangles, nRectangles, op, ordering ); } USHORT SalObject::GetClipRegionType() { return maObjectData.maClipRegion.GetClipRegionType(); } // ----------------------------------------------------------------------- void SalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight ) { if ( maObjectData.maPrimary && maObjectData.maSecondary && nWidth && nHeight ) { XtConfigureWidget( maObjectData.maPrimary, nX, nY, nWidth, nHeight, 0 ); XtConfigureWidget( maObjectData.maSecondary, 0, 0, nWidth, nHeight, 0 ); } } void SalObject::Show( BOOL bVisible ) { if ( ! maObjectData.maSystemChildData.aWindow ) return; if ( bVisible ) XtMapWidget( (Widget)maObjectData.maPrimary ); else XtUnmapWidget( (Widget)maObjectData.maPrimary ); maObjectData.mbVisible = bVisible; } // ----------------------------------------------------------------------- void SalObject::Enable( BOOL bEnable ) { } // ----------------------------------------------------------------------- void SalObject::GrabFocus() { if( maObjectData.mbVisible ) XSetInputFocus( (Display*)maObjectData.maSystemChildData.pDisplay, maObjectData.maSystemChildData.aWindow, RevertToNone, CurrentTime ); } // ----------------------------------------------------------------------- void SalObject::SetBackground() { } // ----------------------------------------------------------------------- void SalObject::SetBackground( SalColor nSalColor ) { } // ----------------------------------------------------------------------- const SystemChildData* SalObject::GetSystemData() const { return &maObjectData.maSystemChildData; } // ----------------------------------------------------------------------- void SalObject::SetCallback( void* pInst, SALOBJECTPROC pProc ) { maObjectData.mpInst = pInst; if ( pProc ) maObjectData.mpProc = pProc; else maObjectData.mpProc = ImplSalObjCallbackDummy; } long SalObjectData::Dispatch( XEvent* pEvent ) { for( int n= 0; n < aAllObjects.Count(); n++ ) { SalObject* pObject = aAllObjects.GetObject( n ); if( pEvent->xany.window == XtWindow( pObject->maObjectData.maPrimary ) || pEvent->xany.window == XtWindow( pObject->maObjectData.maSecondary ) ) { switch( pEvent->type ) { case UnmapNotify: pObject->maObjectData.mbVisible = FALSE; return 1; case MapNotify: pObject->maObjectData.mbVisible = TRUE; return 1; case ButtonPress: pObject->maObjectData.mpProc( pObject->maObjectData.mpInst, pObject, SALOBJ_EVENT_TOTOP, NULL ); return 1; case FocusIn: pObject->maObjectData.mpProc( pObject->maObjectData.mpInst, pObject, SALOBJ_EVENT_GETFOCUS, NULL ); return 1; case FocusOut: pObject->maObjectData.mpProc( pObject->maObjectData.mpInst, pObject, SALOBJ_EVENT_LOSEFOCUS, NULL ); return 1; default: break; } return 0; } } return 0; } <commit_msg>shape fixed; map sencondary; destroy in correct order (#79689#)<commit_after>/************************************************************************* * * $RCSfile: salobj.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kr $ $Date: 2001-08-07 14:43:13 $ * * 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): _______________________________________ * * ************************************************************************/ #define _SV_SALOBJ_CXX #include <prex.h> #include <X11/Xlib.h> #include <X11/extensions/shape.h> #ifdef USE_MOTIF #include <Xm/DrawingA.h> #else #include <X11/Xaw/Label.h> #endif #include <postx.h> #include <salunx.h> #include <salstd.hxx> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALINST_HXX #include <salinst.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALFRAME_HXX #include <salframe.hxx> #endif #ifndef _SV_SALOBJ_HXX #include <salobj.hxx> #endif #ifdef USE_MOTIF #define OBJECT_WIDGET_CLASS xmDrawingAreaWidgetClass #else #define OBJECT_WIDGET_CLASS labelWidgetClass #endif SalObjectList SalObjectData::aAllObjects; // ======================================================================= long ImplSalObjCallbackDummy( void*, SalObject*, USHORT, const void* ) { return 0; } // ======================================================================= // SalInstance memberfkts to create and destroy a SalObject SalObject* SalInstance::CreateObject( SalFrame* pParent ) { int error_base, event_base; SalObject* pObject = new SalObject; SystemChildData* pObjData = const_cast<SystemChildData*>(pObject->GetSystemData()); if ( ! XShapeQueryExtension( (Display*)pObjData->pDisplay, &event_base, &error_base ) ) { delete pObject; return NULL; } SalDisplay* pSalDisp = pParent->maFrameData.GetDisplay(); Widget pWidgetParent = pParent->maFrameData.GetWidget(); pObject->maObjectData.maPrimary = XtVaCreateWidget( "salobject primary", OBJECT_WIDGET_CLASS, pWidgetParent, NULL ); pObject->maObjectData.maSecondary = XtVaCreateWidget( "salobject secondary", OBJECT_WIDGET_CLASS, pObject->maObjectData.maPrimary, NULL ); XtRealizeWidget( pObject->maObjectData.maPrimary ); XtRealizeWidget( pObject->maObjectData.maSecondary ); pObjData->pDisplay = XtDisplay( pObject->maObjectData.maPrimary ); pObjData->aWindow = XtWindow( pObject->maObjectData.maSecondary ); pObjData->pWidget = pObject->maObjectData.maSecondary; pObjData->pVisual = pSalDisp->GetVisual()->GetVisual(); pObjData->nDepth = pSalDisp->GetVisual()->GetDepth(); pObjData->aColormap = pSalDisp->GetColormap().GetXColormap(); pObjData->pAppContext = pSalDisp->GetXLib()->GetAppContext(); return pObject; } void SalInstance::DestroyObject( SalObject* pObject ) { delete pObject; } // ====================================================================== // SalClipRegion is a member of SalObject // definition of SalClipRegion my be found in unx/inc/salobj.h SalClipRegion::SalClipRegion() { ClipRectangleList = NULL; numClipRectangles = 0; maxClipRectangles = 0; nClipRegionType = SAL_OBJECT_CLIP_INCLUDERECTS; } SalClipRegion::~SalClipRegion() { if ( ClipRectangleList ) delete ClipRectangleList; } void SalClipRegion::BeginSetClipRegion( ULONG nRects ) { if (ClipRectangleList) delete ClipRectangleList; ClipRectangleList = new XRectangle[nRects]; numClipRectangles = 0; maxClipRectangles = nRects; } void SalClipRegion::UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) { if ( nWidth && nHeight && (numClipRectangles < maxClipRectangles) ) { XRectangle *aRect = ClipRectangleList + numClipRectangles; aRect->x = (short) nX; aRect->y = (short) nY; aRect->width = (unsigned short) nWidth; aRect->height= (unsigned short) nHeight; numClipRectangles++; } } // ======================================================================= // SalObject Implementation SalObject::SalObject() { maObjectData.maSystemChildData.nSize = sizeof( SystemChildData ); maObjectData.maSystemChildData.pDisplay = GetSalData()->GetDefDisp()->GetDisplay(); maObjectData.maSystemChildData.aWindow = None; maObjectData.maSystemChildData.pSalFrame = 0; maObjectData.maSystemChildData.pWidget = 0; maObjectData.maSystemChildData.pVisual = 0; maObjectData.maSystemChildData.nDepth = 0; maObjectData.maSystemChildData.aColormap = 0; maObjectData.maSystemChildData.pAppContext = NULL; maObjectData.maSystemChildData.aShellWindow = 0; maObjectData.maSystemChildData.pShellWidget = NULL; maObjectData.mpInst = NULL; maObjectData.mpProc = ImplSalObjCallbackDummy; maObjectData.maPrimary = NULL; maObjectData.maSecondary = NULL; SalObjectData::aAllObjects.Insert( this, LIST_APPEND ); } SalObject::~SalObject() { SalObjectData::aAllObjects.Remove( this ); if ( maObjectData.maSecondary ) XtDestroyWidget ( maObjectData.maSecondary ); if ( maObjectData.maPrimary ) XtDestroyWidget ( maObjectData.maPrimary ); } void SalObject::ResetClipRegion() { maObjectData.maClipRegion.ResetClipRegion(); const int dest_kind = ShapeBounding; const int op = ShapeSet; const int ordering = YSorted; XWindowAttributes win_attrib; XRectangle win_size; XLIB_Window aShapeWindow = XtWindow( maObjectData.maPrimary ); XGetWindowAttributes ( (Display*)maObjectData.maSystemChildData.pDisplay, aShapeWindow, &win_attrib ); win_size.x = 0; win_size.y = 0; win_size.width = win_attrib.width; win_size.height = win_attrib.width; XShapeCombineRectangles ( (Display*)maObjectData.maSystemChildData.pDisplay, aShapeWindow, dest_kind, 0, 0, // x_off, y_off &win_size, // list of rectangles 1, // number of rectangles op, ordering ); } void SalObject::BeginSetClipRegion( ULONG nRectCount ) { maObjectData.maClipRegion.BeginSetClipRegion ( nRectCount ); } void SalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) { maObjectData.maClipRegion.UnionClipRegion ( nX, nY, nWidth, nHeight ); } void SalObject::EndSetClipRegion() { XRectangle *pRectangles = maObjectData.maClipRegion.EndSetClipRegion (); const int nType = maObjectData.maClipRegion.GetClipRegionType(); const int nRectangles = maObjectData.maClipRegion.GetRectangleCount(); const int dest_kind = ShapeBounding; const int ordering = YSorted; int op; switch ( nType ) { case SAL_OBJECT_CLIP_INCLUDERECTS : op = ShapeSet; break; case SAL_OBJECT_CLIP_EXCLUDERECTS : op = ShapeSubtract; break; case SAL_OBJECT_CLIP_ABSOLUTE : op = ShapeSet; break; default : op = ShapeUnion; } XLIB_Window aShapeWindow = XtWindow( maObjectData.maPrimary ); XShapeCombineRectangles ( (Display*)maObjectData.maSystemChildData.pDisplay, aShapeWindow, dest_kind, 0, 0, // x_off, y_off pRectangles, nRectangles, op, ordering ); } USHORT SalObject::GetClipRegionType() { return maObjectData.maClipRegion.GetClipRegionType(); } // ----------------------------------------------------------------------- void SalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight ) { if ( maObjectData.maPrimary && maObjectData.maSecondary && nWidth && nHeight ) { XtConfigureWidget( maObjectData.maPrimary, nX, nY, nWidth, nHeight, 0 ); XtConfigureWidget( maObjectData.maSecondary, 0, 0, nWidth, nHeight, 0 ); } } void SalObject::Show( BOOL bVisible ) { if ( ! maObjectData.maSystemChildData.aWindow ) return; if ( bVisible ) { XtMapWidget( (Widget)maObjectData.maPrimary ); XtMapWidget( (Widget)maObjectData.maSecondary ); } else { XtUnmapWidget( (Widget)maObjectData.maSecondary ); XtUnmapWidget( (Widget)maObjectData.maPrimary ); } maObjectData.mbVisible = bVisible; } // ----------------------------------------------------------------------- void SalObject::Enable( BOOL bEnable ) { } // ----------------------------------------------------------------------- void SalObject::GrabFocus() { if( maObjectData.mbVisible ) XSetInputFocus( (Display*)maObjectData.maSystemChildData.pDisplay, maObjectData.maSystemChildData.aWindow, RevertToNone, CurrentTime ); } // ----------------------------------------------------------------------- void SalObject::SetBackground() { } // ----------------------------------------------------------------------- void SalObject::SetBackground( SalColor nSalColor ) { } // ----------------------------------------------------------------------- const SystemChildData* SalObject::GetSystemData() const { return &maObjectData.maSystemChildData; } // ----------------------------------------------------------------------- void SalObject::SetCallback( void* pInst, SALOBJECTPROC pProc ) { maObjectData.mpInst = pInst; if ( pProc ) maObjectData.mpProc = pProc; else maObjectData.mpProc = ImplSalObjCallbackDummy; } long SalObjectData::Dispatch( XEvent* pEvent ) { for( int n= 0; n < aAllObjects.Count(); n++ ) { SalObject* pObject = aAllObjects.GetObject( n ); if( pEvent->xany.window == XtWindow( pObject->maObjectData.maPrimary ) || pEvent->xany.window == XtWindow( pObject->maObjectData.maSecondary ) ) { switch( pEvent->type ) { case UnmapNotify: pObject->maObjectData.mbVisible = FALSE; return 1; case MapNotify: pObject->maObjectData.mbVisible = TRUE; return 1; case ButtonPress: pObject->maObjectData.mpProc( pObject->maObjectData.mpInst, pObject, SALOBJ_EVENT_TOTOP, NULL ); return 1; case FocusIn: pObject->maObjectData.mpProc( pObject->maObjectData.mpInst, pObject, SALOBJ_EVENT_GETFOCUS, NULL ); return 1; case FocusOut: pObject->maObjectData.mpProc( pObject->maObjectData.mpInst, pObject, SALOBJ_EVENT_LOSEFOCUS, NULL ); return 1; default: break; } return 0; } } return 0; } <|endoftext|>
<commit_before>#include "gamemechanics.h" #include <QPainter> #include <QtCore/qmath.h> #include <QLabel> #include <QMouseEvent> #include <QtDebug> GameMechanics::GameMechanics(QWidget *parent) : QWidget(parent) { imageName = new QString(); pieceCount = 3; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } typeOfPainting = empty; winflag = false; } //----------------------------------------- void GameMechanics::mixArray() //Начинаем перемешивать части картинок по алгоритму { int mas[2] = {-1,1}; int x, y; for(int i = 0; i<23 * pieceCount; i++) { x = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); y = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); if (!swapEmpty(x, emptyImagePos.y())) i--; if (!swapEmpty(emptyImagePos.x(), y)) i--; } } //----------------------------------------- void GameMechanics::newGame() { pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; typeOfPainting = fullImage; QImage temp(*imageName); temp = temp.scaled(QSize(this->width() + pieceCount, this->height())); image = &temp; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) array[x][y].img = image->copy(pieceWidth * x, pieceHeight * y, pieceWidth, pieceHeight); emptyImagePos.setX(pieceCount - 1); emptyImagePos.setY(pieceCount - 1); winflag = false; repaint(); mixArray(); qDebug() << "\n\n\n---------------------\n\n\n" << *imageName; typeOfPainting = fullImage; } //---------------------------------------- void GameMechanics::hint() { typeOfPainting = fullImage; repaint(); } //---------------------------------------- GameMechanics::~GameMechanics() { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; } //---------------------------------------- void GameMechanics::paintEvent(QPaintEvent *paintEvent) { QPainter painter(this); painter.begin(this); int n = 0; switch(typeOfPainting) { case pieces: pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; //рисуем картинки for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * x,pieceHeight * y + y, array[x][y].img); painter.setPen(QColor(0, 0, 0)); painter.setBrush(QColor(255, 255, 255)); painter.drawRect(pieceWidth * emptyImagePos.x(), pieceHeight * emptyImagePos.y() + emptyImagePos.y(), pieceWidth, pieceHeight); //рисуем линии между картинками for(int x = pieceWidth; x < this->width(); x += pieceWidth) painter.drawLine(x, 0, x, this->height()); for(int y = pieceHeight; y < this->height(); y += pieceHeight, n++) painter.drawLine(0, y + n, this->width(), y+n); break; case fullImage: for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * array[x][y].x, pieceHeight * array[x][y].y, array[x][y].img); break; default: painter.drawText(this->width() / 2 - 70, this->height() / 2 - 15, "Begin the game, please!"); break; }; painter.end(); } //---------------------------------------- void GameMechanics::mousePressEvent(QMouseEvent *event) { imagePressed(event->localPos()); } //---------------------------------------- void GameMechanics::imagePressed(QPointF pos) { if(typeOfPainting == pieces) { int x = (int)pos.x(); int y = (int)pos.y(); x /= pieceWidth; y /= pieceHeight; if ( x == emptyImagePos.x() && y == emptyImagePos.y()) return; swapEmpty(x,y); repaint(); if(!winflag && checkArray()) { win(); typeOfPainting = fullImage; } } if(typeOfPainting == fullImage && !winflag) { typeOfPainting = pieces; repaint(); } if(typeOfPainting == fullImage && winflag) { repaint(); } } //---------------------------------------- int GameMechanics::swapEmpty(int x, int y) { if( (abs(x - emptyImagePos.x()) == 1 && y == emptyImagePos.y()) || (abs(y - emptyImagePos.y()) == 1 && x == emptyImagePos.x()) ) { Piece tempPiece = array[x][y]; array[x][y] = array[emptyImagePos.x()][emptyImagePos.y()]; array[emptyImagePos.x()][emptyImagePos.y()] = tempPiece; emptyImagePos.setX(x); emptyImagePos.setY(y); return 1; } else return 0; } //---------------------------------------- bool GameMechanics::checkArray() { for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) if(array[x][y].x != x || array[x][y].y != y) return 0; winflag = true; return 1; } //---------------------------------------- void GameMechanics::changeLevel(int level) { if (level > 1 && level <6) { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; pieceCount = level; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } } } //---------------------------------------- void GameMechanics::deleteImageName() { delete imageName; } <commit_msg>Обновил перевод.<commit_after>#include "gamemechanics.h" #include <QPainter> #include <QtCore/qmath.h> #include <QLabel> #include <QMouseEvent> GameMechanics::GameMechanics(QWidget *parent) : QWidget(parent) { imageName = new QString(); pieceCount = 3; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } typeOfPainting = empty; winflag = false; } //----------------------------------------- void GameMechanics::mixArray() //Начинаем перемешивать части картинок по алгоритму { int mas[2] = {-1,1}; int x, y; for(int i = 0; i<23 * pieceCount; i++) { x = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); y = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); if (!swapEmpty(x, emptyImagePos.y())) i--; if (!swapEmpty(emptyImagePos.x(), y)) i--; } } //----------------------------------------- void GameMechanics::newGame() { pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; typeOfPainting = fullImage; QImage temp(*imageName); temp = temp.scaled(QSize(this->width() + pieceCount, this->height())); image = &temp; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) array[x][y].img = image->copy(pieceWidth * x, pieceHeight * y, pieceWidth, pieceHeight); emptyImagePos.setX(pieceCount - 1); emptyImagePos.setY(pieceCount - 1); winflag = false; repaint(); mixArray(); typeOfPainting = fullImage; } //---------------------------------------- void GameMechanics::hint() { typeOfPainting = fullImage; repaint(); } //---------------------------------------- GameMechanics::~GameMechanics() { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; } //---------------------------------------- void GameMechanics::paintEvent(QPaintEvent *paintEvent) { QPainter painter(this); painter.begin(this); int n = 0; switch(typeOfPainting) { case pieces: pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; //рисуем картинки for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * x,pieceHeight * y + y, array[x][y].img); painter.setPen(QColor(0, 0, 0)); painter.setBrush(QColor(255, 255, 255)); painter.drawRect(pieceWidth * emptyImagePos.x(), pieceHeight * emptyImagePos.y() + emptyImagePos.y(), pieceWidth, pieceHeight); //рисуем линии между картинками for(int x = pieceWidth; x < this->width(); x += pieceWidth) painter.drawLine(x, 0, x, this->height()); for(int y = pieceHeight; y < this->height(); y += pieceHeight, n++) painter.drawLine(0, y + n, this->width(), y+n); break; case fullImage: for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * array[x][y].x, pieceHeight * array[x][y].y, array[x][y].img); break; default: painter.drawText(this->width() / 2 - 70, this->height() / 2 - 15, tr("Begin the game, please!")); break; }; painter.end(); } //---------------------------------------- void GameMechanics::mousePressEvent(QMouseEvent *event) { imagePressed(event->localPos()); } //---------------------------------------- void GameMechanics::imagePressed(QPointF pos) { if(typeOfPainting == pieces) { int x = (int)pos.x(); int y = (int)pos.y(); x /= pieceWidth; y /= pieceHeight; if ( x == emptyImagePos.x() && y == emptyImagePos.y()) return; swapEmpty(x,y); repaint(); if(!winflag && checkArray()) { win(); typeOfPainting = fullImage; } } if(typeOfPainting == fullImage && !winflag) { typeOfPainting = pieces; repaint(); } if(typeOfPainting == fullImage && winflag) { repaint(); } } //---------------------------------------- int GameMechanics::swapEmpty(int x, int y) { if( (abs(x - emptyImagePos.x()) == 1 && y == emptyImagePos.y()) || (abs(y - emptyImagePos.y()) == 1 && x == emptyImagePos.x()) ) { Piece tempPiece = array[x][y]; array[x][y] = array[emptyImagePos.x()][emptyImagePos.y()]; array[emptyImagePos.x()][emptyImagePos.y()] = tempPiece; emptyImagePos.setX(x); emptyImagePos.setY(y); return 1; } else return 0; } //---------------------------------------- bool GameMechanics::checkArray() { for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) if(array[x][y].x != x || array[x][y].y != y) return 0; winflag = true; return 1; } //---------------------------------------- void GameMechanics::changeLevel(int level) { if (level > 1 && level <6) { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; pieceCount = level; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } } } //---------------------------------------- void GameMechanics::deleteImageName() { delete imageName; } <|endoftext|>
<commit_before>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <thrift/lib/cpp2/server/CPUConcurrencyController.h> #include <algorithm> namespace apache::thrift { namespace detail { THRIFT_PLUGGABLE_FUNC_REGISTER( folly::observer::Observer<CPUConcurrencyController::Config>, makeCPUConcurrencyControllerConfig) { return folly::observer::makeStaticObserver( CPUConcurrencyController::Config{}); } THRIFT_PLUGGABLE_FUNC_REGISTER( int64_t, getCPULoadCounter, std::chrono::milliseconds, bool) { return -1; } } // namespace detail void CPUConcurrencyController::cycleOnce() { if (config().mode == Mode::DISABLED) { return; } auto load = getLoad(); if (load >= config().cpuTarget) { lastOverloadStart_ = std::chrono::steady_clock::now(); auto lim = this->getLimit(); auto newLim = lim - std::max<int64_t>( static_cast<int64_t>(lim * config().decreaseMultiplier), 1); this->setLimit(std::max<int64_t>(newLim, config().concurrencyLowerBound)); } else { auto currentLimitUsage = this->getLimitUsage(); if (currentLimitUsage == 0 || load <= 0) { return; } // Estimate stable concurrency only if we haven't been overloaded recently // (and thus current concurrency/CPU is not a good indicator). if (!isRefractoryPeriod() && config().collectionSampleSize > stableConcurrencySamples_.size()) { auto concurrencyEstimate = static_cast<double>(currentLimitUsage) / load * config().cpuTarget; stableConcurrencySamples_.push_back( config().initialEstimateFactor * concurrencyEstimate); if (stableConcurrencySamples_.size() >= config().collectionSampleSize) { // Take percentile to hopefully account for inaccuracies. We don't // need a very accurate value as we will adjust this later in the // algorithm. // // The purpose of stable concurrency estimate is to optimistically // avoid causing too much request ingestion during initial overload, and // thus causing high tail latencies during initial overload. auto pct = stableConcurrencySamples_.begin() + static_cast<size_t>( stableConcurrencySamples_.size() * config().initialEstimatePercentile); std::nth_element( stableConcurrencySamples_.begin(), pct, stableConcurrencySamples_.end()); auto result = std::clamp<int64_t>( *pct, config().concurrencyLowerBound, config().concurrencyUpperBound); stableEstimate_.store(result, std::memory_order_relaxed); this->setLimit(result); return; } } // We prevent unbounded increase of limits by only changing when // necessary (i.e., we are getting near breaching existing limit). We try // and push the limit back to stable estimate if we are not overloaded as // after an overload event the limit will be set aggressively and may cause // steady-state load shedding due to bursty traffic. auto lim = this->getLimit(); bool nearExistingLimit = currentLimitUsage >= (1.0 - config().increaseDistanceRatio) * lim; bool shouldConvergeStable = !isRefractoryPeriod() && lim < getStableEstimate(); if (nearExistingLimit || shouldConvergeStable) { auto newLim = lim + std::max<int64_t>( static_cast<int64_t>(lim * config().additiveMultiplier), 1); this->setLimit(std::min<int64_t>(config().concurrencyUpperBound, newLim)); } } } void CPUConcurrencyController::schedule() { using time_point = std::chrono::steady_clock::time_point; if (config().mode == Mode::DISABLED) { return; } LOG(INFO) << "Enabling CPUConcurrencyController. CPU Target: " << static_cast<int32_t>(this->config().cpuTarget) << " Refresh Period Ms: " << this->config().refreshPeriodMs.count(); scheduler_.addFunctionGenericNextRunTimeFunctor( [this] { this->cycleOnce(); }, [this](time_point, time_point now) { return now + this->config().refreshPeriodMs; }, "cpu-shed-loop", "cpu-shed-interval", this->config().refreshPeriodMs); } void CPUConcurrencyController::cancel() { scheduler_.cancelAllFunctionsAndWait(); stableConcurrencySamples_.clear(); stableEstimate_.exchange(-1); } void CPUConcurrencyController::requestStarted() { if (config().mode == Mode::DISABLED) { return; } totalRequestCount_ += 1; } uint32_t CPUConcurrencyController::getLimit() const { uint32_t limit = 0; switch (config().mode) { case Mode::ENABLED_CONCURRENCY_LIMITS: limit = serverConfigs_.getMaxRequests(); break; case Mode::ENABLED_TOKEN_BUCKET: limit = serverConfigs_.getMaxQps(); break; default: DCHECK(false); } // Fallback to concurrency upper bound if no limit is set yet. // This is most sensible value until we collect enough samples // to estimate a better upper bound; return limit ? limit : config().concurrencyUpperBound; } void CPUConcurrencyController::setLimit(uint32_t newLimit) { switch (config().mode) { case Mode::ENABLED_CONCURRENCY_LIMITS: serverConfigs_.setMaxRequests(newLimit); break; case Mode::ENABLED_TOKEN_BUCKET: serverConfigs_.setMaxQps(newLimit); break; default: DCHECK(false); } } uint32_t CPUConcurrencyController::getLimitUsage() { using namespace std::chrono; switch (config().mode) { case Mode::ENABLED_CONCURRENCY_LIMITS: // Note: estimating concurrency from this is fairly lossy as it's a // gauge metric and we can't use techniques to measure it over a duration. // We may be able to get much better estimates if we switch to use QPS // and a token bucket for rate limiting. // TODO: We should exclude fb303 methods. return serverConfigs_.getActiveRequests(); case Mode::ENABLED_TOKEN_BUCKET: { auto now = steady_clock::now(); auto milliSince = duration_cast<milliseconds>(now - lastTotalRequestReset_).count(); if (milliSince == 0) { return 0; } auto totalRequestSince = totalRequestCount_.load(); totalRequestCount_ = 0; lastTotalRequestReset_ = now; return totalRequestSince * 1000L / milliSince; } default: DCHECK(false); return 0; } } } // namespace apache::thrift <commit_msg>Set limit to concurrencyUpperBound before starting CPUConcurrencyController<commit_after>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <thrift/lib/cpp2/server/CPUConcurrencyController.h> #include <algorithm> namespace apache::thrift { namespace detail { THRIFT_PLUGGABLE_FUNC_REGISTER( folly::observer::Observer<CPUConcurrencyController::Config>, makeCPUConcurrencyControllerConfig) { return folly::observer::makeStaticObserver( CPUConcurrencyController::Config{}); } THRIFT_PLUGGABLE_FUNC_REGISTER( int64_t, getCPULoadCounter, std::chrono::milliseconds, bool) { return -1; } } // namespace detail namespace { struct ModeInfo { std::string_view name; std::string_view concurrencyUnit; }; ModeInfo getModeInfo(CPUConcurrencyController::Mode mode) { if (mode == CPUConcurrencyController::Mode::ENABLED_CONCURRENCY_LIMITS) { return {"CONCURRENCY_LIMITS", "Active Requests"}; } else if (mode == CPUConcurrencyController::Mode::ENABLED_TOKEN_BUCKET) { return {"TOKEN_BUCKET", "QPS"}; } DCHECK(false); return {"UNKNOWN", "UNKNOWN"}; } } // namespace void CPUConcurrencyController::cycleOnce() { if (config().mode == Mode::DISABLED) { return; } auto load = getLoad(); if (load >= config().cpuTarget) { lastOverloadStart_ = std::chrono::steady_clock::now(); auto lim = this->getLimit(); auto newLim = lim - std::max<int64_t>( static_cast<int64_t>(lim * config().decreaseMultiplier), 1); this->setLimit(std::max<int64_t>(newLim, config().concurrencyLowerBound)); } else { auto currentLimitUsage = this->getLimitUsage(); if (currentLimitUsage == 0 || load <= 0) { return; } // Estimate stable concurrency only if we haven't been overloaded recently // (and thus current concurrency/CPU is not a good indicator). if (!isRefractoryPeriod() && config().collectionSampleSize > stableConcurrencySamples_.size()) { auto concurrencyEstimate = static_cast<double>(currentLimitUsage) / load * config().cpuTarget; stableConcurrencySamples_.push_back( config().initialEstimateFactor * concurrencyEstimate); if (stableConcurrencySamples_.size() >= config().collectionSampleSize) { // Take percentile to hopefully account for inaccuracies. We don't // need a very accurate value as we will adjust this later in the // algorithm. // // The purpose of stable concurrency estimate is to optimistically // avoid causing too much request ingestion during initial overload, and // thus causing high tail latencies during initial overload. auto pct = stableConcurrencySamples_.begin() + static_cast<size_t>( stableConcurrencySamples_.size() * config().initialEstimatePercentile); std::nth_element( stableConcurrencySamples_.begin(), pct, stableConcurrencySamples_.end()); auto result = std::clamp<int64_t>( *pct, config().concurrencyLowerBound, config().concurrencyUpperBound); stableEstimate_.store(result, std::memory_order_relaxed); this->setLimit(result); return; } } // We prevent unbounded increase of limits by only changing when // necessary (i.e., we are getting near breaching existing limit). We try // and push the limit back to stable estimate if we are not overloaded as // after an overload event the limit will be set aggressively and may cause // steady-state load shedding due to bursty traffic. auto lim = this->getLimit(); bool nearExistingLimit = currentLimitUsage >= (1.0 - config().increaseDistanceRatio) * lim; bool shouldConvergeStable = !isRefractoryPeriod() && lim < getStableEstimate(); if (nearExistingLimit || shouldConvergeStable) { auto newLim = lim + std::max<int64_t>( static_cast<int64_t>(lim * config().additiveMultiplier), 1); this->setLimit(std::min<int64_t>(config().concurrencyUpperBound, newLim)); } } } void CPUConcurrencyController::schedule() { using time_point = std::chrono::steady_clock::time_point; if (config().mode == Mode::DISABLED) { return; } auto modeInfo = getModeInfo(config().mode); LOG(INFO) << "Enabling CPUConcurrencyController. Mode: " << modeInfo.name << " CPU Target: " << static_cast<int32_t>(this->config().cpuTarget) << " Refresh Period (Ms): " << this->config().refreshPeriodMs.count() << " Concurrency Upper Bound (" << modeInfo.concurrencyUnit << "): " << this->config().concurrencyUpperBound; this->setLimit(this->config().concurrencyUpperBound); scheduler_.addFunctionGenericNextRunTimeFunctor( [this] { this->cycleOnce(); }, [this](time_point, time_point now) { return now + this->config().refreshPeriodMs; }, "cpu-shed-loop", "cpu-shed-interval", this->config().refreshPeriodMs); } void CPUConcurrencyController::cancel() { scheduler_.cancelAllFunctionsAndWait(); stableConcurrencySamples_.clear(); stableEstimate_.exchange(-1); } void CPUConcurrencyController::requestStarted() { if (config().mode == Mode::DISABLED) { return; } totalRequestCount_ += 1; } uint32_t CPUConcurrencyController::getLimit() const { uint32_t limit = 0; switch (config().mode) { case Mode::ENABLED_CONCURRENCY_LIMITS: limit = serverConfigs_.getMaxRequests(); break; case Mode::ENABLED_TOKEN_BUCKET: limit = serverConfigs_.getMaxQps(); break; default: DCHECK(false); } // Fallback to concurrency upper bound if no limit is set yet. // This is most sensible value until we collect enough samples // to estimate a better upper bound; return limit ? limit : config().concurrencyUpperBound; } void CPUConcurrencyController::setLimit(uint32_t newLimit) { switch (config().mode) { case Mode::ENABLED_CONCURRENCY_LIMITS: serverConfigs_.setMaxRequests(newLimit); break; case Mode::ENABLED_TOKEN_BUCKET: serverConfigs_.setMaxQps(newLimit); break; default: DCHECK(false); } } uint32_t CPUConcurrencyController::getLimitUsage() { using namespace std::chrono; switch (config().mode) { case Mode::ENABLED_CONCURRENCY_LIMITS: // Note: estimating concurrency from this is fairly lossy as it's a // gauge metric and we can't use techniques to measure it over a duration. // We may be able to get much better estimates if we switch to use QPS // and a token bucket for rate limiting. // TODO: We should exclude fb303 methods. return serverConfigs_.getActiveRequests(); case Mode::ENABLED_TOKEN_BUCKET: { auto now = steady_clock::now(); auto milliSince = duration_cast<milliseconds>(now - lastTotalRequestReset_).count(); if (milliSince == 0) { return 0; } auto totalRequestSince = totalRequestCount_.load(); totalRequestCount_ = 0; lastTotalRequestReset_ = now; return totalRequestSince * 1000L / milliSince; } default: DCHECK(false); return 0; } } } // namespace apache::thrift <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <boost/unordered_map.hpp> ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget> void pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output) { pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (output, Eigen::Matrix4f::Identity()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget> void pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output, const Eigen::Matrix4f &guess) { // Allocate enough space to hold the results std::vector<int> nn_indices (1); std::vector<float> nn_dists (1); // Point cloud containing the correspondences of each point in <input, indices> PointCloudTarget input_corresp; input_corresp.points.resize (indices_->size ()); nr_iterations_ = 0; converged_ = false; double dist_threshold = corr_dist_threshold_ * corr_dist_threshold_; // If the guessed transformation is non identity if (guess != Eigen::Matrix4f::Identity ()) { // Initialise final transformation to the guessed one final_transformation_ = guess; // Apply guessed transformation prior to search for neighbours transformPointCloud (output, output, guess); } // Resize the vector of distances between correspondences std::vector<float> previous_correspondence_distances (indices_->size ()); correspondence_distances_.resize (indices_->size ()); while (!converged_) // repeat until convergence { // Save the previously estimated transformation previous_transformation_ = transformation_; // And the previous set of distances previous_correspondence_distances = correspondence_distances_; int cnt = 0; std::vector<int> source_indices (indices_->size ()); std::vector<int> target_indices (indices_->size ()); // Iterating over the entire index vector and find all correspondences for (size_t idx = 0; idx < indices_->size (); ++idx) { if (!searchForNeighbors (output, idx, nn_indices, nn_dists)) { PCL_ERROR ("[pcl::%s::computeTransformation] Unable to find a nearest neighbor in the target dataset for point %d in the source!\n", getClassName ().c_str (), (*indices_)[idx]); return; } // Check if the distance to the nearest neighbor is smaller than the user imposed threshold if (nn_dists[0] < dist_threshold) { source_indices[cnt] = idx; target_indices[cnt] = nn_indices[0]; cnt++; } // Save the nn_dists[0] to a global vector of distances correspondence_distances_[idx] = std::min (nn_dists[0], (float)dist_threshold); } // Resize to the actual number of valid correspondences source_indices.resize (cnt); target_indices.resize (cnt); std::vector<int> source_indices_good; std::vector<int> target_indices_good; { // From the set of correspondences found, attempt to remove outliers // Create the registration model typedef typename SampleConsensusModelRegistration<PointSource>::Ptr SampleConsensusModelRegistrationPtr; SampleConsensusModelRegistrationPtr model; model.reset (new SampleConsensusModelRegistration<PointSource> (output.makeShared (), source_indices)); // Pass the target_indices model->setInputTarget (target_, target_indices); // Create a RANSAC model RandomSampleConsensus<PointSource> sac (model, inlier_threshold_); sac.setMaxIterations (1000); // Compute the set of inliers if (!sac.computeModel ()) { source_indices_good = source_indices; target_indices_good = target_indices; } else { std::vector<int> inliers; // Get the inliers sac.getInliers (inliers); source_indices_good.resize (inliers.size ()); target_indices_good.resize (inliers.size ()); boost::unordered_map<int, int> source_to_target; for (unsigned int i = 0; i < source_indices.size(); ++i) source_to_target[source_indices[i]] = target_indices[i]; // Copy just the inliers std::copy(inliers.begin(), inliers.end(), source_indices_good.begin()); for (size_t i = 0; i < inliers.size (); ++i) target_indices_good[i] = source_to_target[inliers[i]]; } } // Check whether we have enough correspondences cnt = (int)source_indices_good.size (); if (cnt < min_number_correspondences_) { PCL_ERROR ("[pcl::%s::computeTransformation] Not enough correspondences found. Relax your threshold parameters.\n", getClassName ().c_str ()); converged_ = false; return; } PCL_DEBUG ("[pcl::%s::computeTransformation] Number of correspondences %d [%f%%] out of %lu points [100.0%%], RANSAC rejected: %lu [%f%%].\n", getClassName ().c_str (), cnt, (cnt * 100.0) / indices_->size (), (unsigned long)indices_->size (), (unsigned long)source_indices.size () - cnt, (source_indices.size () - cnt) * 100.0 / source_indices.size ()); // Estimate the transform rigid_transformation_estimation_(output, source_indices_good, *target_, target_indices_good, transformation_); // Tranform the data transformPointCloud (output, output, transformation_); // Obtain the final transformation final_transformation_ = transformation_ * final_transformation_; nr_iterations_++; // Update the vizualization of icp convergence if (update_visualizer_ != 0) update_visualizer_(output, source_indices_good, *target_, target_indices_good ); // Various/Different convergence termination criteria // 1. Number of iterations has reached the maximum user imposed number of iterations (via // setMaximumIterations) // 2. The epsilon (difference) between the previous transformation and the current estimated transformation // is smaller than an user imposed value (via setTransformationEpsilon) // 3. The sum of Euclidean squared errors is smaller than a user defined threshold (via // setEuclideanFitnessEpsilon) if (nr_iterations_ >= max_iterations_ || fabs ((transformation_ - previous_transformation_).sum ()) < transformation_epsilon_ || fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) <= euclidean_fitness_epsilon_ ) { converged_ = true; PCL_DEBUG ("[pcl::%s::computeTransformation] Convergence reached. Number of iterations: %d out of %d. Transformation difference: %f\n", getClassName ().c_str (), nr_iterations_, max_iterations_, fabs ((transformation_ - previous_transformation_).sum ())); PCL_INFO ("nr_iterations_ (%d) >= max_iterations_ (%d)\n", nr_iterations_, max_iterations_); PCL_INFO ("fabs ((transformation_ - previous_transformation_).sum ()) (%f) < transformation_epsilon_ (%f)\n", fabs ((transformation_ - previous_transformation_).sum ()), transformation_epsilon_); PCL_INFO ("fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) (%f) <= euclidean_fitness_epsilon_ (%f)\n", fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)), euclidean_fitness_epsilon_); } } } <commit_msg>INFO->DEBUG<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <boost/unordered_map.hpp> ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget> void pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output) { pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (output, Eigen::Matrix4f::Identity()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointSource, typename PointTarget> void pcl::IterativeClosestPoint<PointSource, PointTarget>::computeTransformation (PointCloudSource &output, const Eigen::Matrix4f &guess) { // Allocate enough space to hold the results std::vector<int> nn_indices (1); std::vector<float> nn_dists (1); // Point cloud containing the correspondences of each point in <input, indices> PointCloudTarget input_corresp; input_corresp.points.resize (indices_->size ()); nr_iterations_ = 0; converged_ = false; double dist_threshold = corr_dist_threshold_ * corr_dist_threshold_; // If the guessed transformation is non identity if (guess != Eigen::Matrix4f::Identity ()) { // Initialise final transformation to the guessed one final_transformation_ = guess; // Apply guessed transformation prior to search for neighbours transformPointCloud (output, output, guess); } // Resize the vector of distances between correspondences std::vector<float> previous_correspondence_distances (indices_->size ()); correspondence_distances_.resize (indices_->size ()); while (!converged_) // repeat until convergence { // Save the previously estimated transformation previous_transformation_ = transformation_; // And the previous set of distances previous_correspondence_distances = correspondence_distances_; int cnt = 0; std::vector<int> source_indices (indices_->size ()); std::vector<int> target_indices (indices_->size ()); // Iterating over the entire index vector and find all correspondences for (size_t idx = 0; idx < indices_->size (); ++idx) { if (!searchForNeighbors (output, idx, nn_indices, nn_dists)) { PCL_ERROR ("[pcl::%s::computeTransformation] Unable to find a nearest neighbor in the target dataset for point %d in the source!\n", getClassName ().c_str (), (*indices_)[idx]); return; } // Check if the distance to the nearest neighbor is smaller than the user imposed threshold if (nn_dists[0] < dist_threshold) { source_indices[cnt] = idx; target_indices[cnt] = nn_indices[0]; cnt++; } // Save the nn_dists[0] to a global vector of distances correspondence_distances_[idx] = std::min (nn_dists[0], (float)dist_threshold); } // Resize to the actual number of valid correspondences source_indices.resize (cnt); target_indices.resize (cnt); std::vector<int> source_indices_good; std::vector<int> target_indices_good; { // From the set of correspondences found, attempt to remove outliers // Create the registration model typedef typename SampleConsensusModelRegistration<PointSource>::Ptr SampleConsensusModelRegistrationPtr; SampleConsensusModelRegistrationPtr model; model.reset (new SampleConsensusModelRegistration<PointSource> (output.makeShared (), source_indices)); // Pass the target_indices model->setInputTarget (target_, target_indices); // Create a RANSAC model RandomSampleConsensus<PointSource> sac (model, inlier_threshold_); sac.setMaxIterations (1000); // Compute the set of inliers if (!sac.computeModel ()) { source_indices_good = source_indices; target_indices_good = target_indices; } else { std::vector<int> inliers; // Get the inliers sac.getInliers (inliers); source_indices_good.resize (inliers.size ()); target_indices_good.resize (inliers.size ()); boost::unordered_map<int, int> source_to_target; for (unsigned int i = 0; i < source_indices.size(); ++i) source_to_target[source_indices[i]] = target_indices[i]; // Copy just the inliers std::copy(inliers.begin(), inliers.end(), source_indices_good.begin()); for (size_t i = 0; i < inliers.size (); ++i) target_indices_good[i] = source_to_target[inliers[i]]; } } // Check whether we have enough correspondences cnt = (int)source_indices_good.size (); if (cnt < min_number_correspondences_) { PCL_ERROR ("[pcl::%s::computeTransformation] Not enough correspondences found. Relax your threshold parameters.\n", getClassName ().c_str ()); converged_ = false; return; } PCL_DEBUG ("[pcl::%s::computeTransformation] Number of correspondences %d [%f%%] out of %lu points [100.0%%], RANSAC rejected: %lu [%f%%].\n", getClassName ().c_str (), cnt, (cnt * 100.0) / indices_->size (), (unsigned long)indices_->size (), (unsigned long)source_indices.size () - cnt, (source_indices.size () - cnt) * 100.0 / source_indices.size ()); // Estimate the transform rigid_transformation_estimation_(output, source_indices_good, *target_, target_indices_good, transformation_); // Tranform the data transformPointCloud (output, output, transformation_); // Obtain the final transformation final_transformation_ = transformation_ * final_transformation_; nr_iterations_++; // Update the vizualization of icp convergence if (update_visualizer_ != 0) update_visualizer_(output, source_indices_good, *target_, target_indices_good ); // Various/Different convergence termination criteria // 1. Number of iterations has reached the maximum user imposed number of iterations (via // setMaximumIterations) // 2. The epsilon (difference) between the previous transformation and the current estimated transformation // is smaller than an user imposed value (via setTransformationEpsilon) // 3. The sum of Euclidean squared errors is smaller than a user defined threshold (via // setEuclideanFitnessEpsilon) if (nr_iterations_ >= max_iterations_ || fabs ((transformation_ - previous_transformation_).sum ()) < transformation_epsilon_ || fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) <= euclidean_fitness_epsilon_ ) { converged_ = true; PCL_DEBUG ("[pcl::%s::computeTransformation] Convergence reached. Number of iterations: %d out of %d. Transformation difference: %f\n", getClassName ().c_str (), nr_iterations_, max_iterations_, fabs ((transformation_ - previous_transformation_).sum ())); PCL_DEBUG ("nr_iterations_ (%d) >= max_iterations_ (%d)\n", nr_iterations_, max_iterations_); PCL_DEBUG ("fabs ((transformation_ - previous_transformation_).sum ()) (%f) < transformation_epsilon_ (%f)\n", fabs ((transformation_ - previous_transformation_).sum ()), transformation_epsilon_); PCL_DEBUG ("fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)) (%f) <= euclidean_fitness_epsilon_ (%f)\n", fabs (getFitnessScore (correspondence_distances_, previous_correspondence_distances)), euclidean_fitness_epsilon_); } } } <|endoftext|>
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "InteriorWorldPinController.h" #include "InteriorMarkerModelRepository.h" #include "IWorldPinsService.h" #include "InteriorMarkerModel.h" #include "WorldPinInteriorData.h" #include "WorldPinFocusData.h" #include "InteriorId.h" #include "InteriorWorldPinSelectionHandler.h" #include "WorldPinVisibility.h" #include "MenuDragStateChangedMessage.h" namespace ExampleApp { namespace InteriorsExplorer { namespace SdkModel { InteriorWorldPinController::InteriorWorldPinController(Eegeo::Resources::Interiors::InteriorController& interiorController, Eegeo::Resources::Interiors::Markers::InteriorMarkerModelRepository& markerRepository, WorldPins::SdkModel::IWorldPinsService& worldPinsService, InteriorsExplorerCameraController& cameraController, ExampleAppMessaging::TMessageBus& messageBus) : m_interiorController(interiorController) , m_markerRepository(markerRepository) , m_worldPinsService(worldPinsService) , m_cameraController(cameraController) , m_messageBus(messageBus) , m_markerAddedCallback(this, &InteriorWorldPinController::HandleMarkerAdded) , m_markerRemovedCallback(this, &InteriorWorldPinController::HandleMarkerRemoved) , m_menuDraggedCallback(this, &InteriorWorldPinController::HandleMenuDragged) , m_menuIsDragging(false) { m_markerRepository.RegisterNotifyAddedCallback(m_markerAddedCallback); m_markerRepository.RegisterNotifyRemovedCallback(m_markerRemovedCallback); m_messageBus.SubscribeNative(m_menuDraggedCallback); } InteriorWorldPinController::~InteriorWorldPinController() { m_messageBus.UnsubscribeNative(m_menuDraggedCallback); m_markerRepository.UnregisterNotifyAddedCallback(m_markerAddedCallback); m_markerRepository.UnregisterNotifyRemovedCallback(m_markerRemovedCallback); for(std::map<std::string, WorldPins::SdkModel::WorldPinItemModel*>::iterator it = m_interiorIdToWorldPinMap.begin(); it != m_interiorIdToWorldPinMap.end(); ++it) { WorldPins::SdkModel::WorldPinItemModel* pPinModel = it->second; m_worldPinsService.RemovePin(pPinModel); } m_interiorIdToWorldPinMap.clear(); } const bool InteriorWorldPinController::PinInteractionAllowed() const { return !m_menuIsDragging && m_interiorController.GetCurrentState() == Eegeo::Resources::Interiors::InteriorViewState::NoInteriorSelected; } void InteriorWorldPinController::HandleMarkerAdded(const Eegeo::Resources::Interiors::Markers::InteriorMarkerModel& markerModel) { Eegeo_ASSERT(m_interiorIdToWorldPinMap.find(markerModel.GetInteriorId().Value()) == m_interiorIdToWorldPinMap.end(), "InteriorWorldPinController already has a pin with that Id"); const float heightOffsetMetres = 0.0f; const bool isInterior = false; const int iconIndex = 11; WorldPins::SdkModel::WorldPinInteriorData worldPinInteriorData; // Don't have a human readable 'Name' for Interiors at this point. Can map IDS -> Names per app? ExampleApp::WorldPins::SdkModel::WorldPinFocusData worldPinFocusData("Interior", markerModel.GetInteriorId().Value()); Eegeo::Space::LatLong location = Eegeo::Space::LatLong::FromDegrees(markerModel.GetMarkerLatLongAltitude().GetLatitudeInDegrees(), markerModel.GetMarkerLatLongAltitude().GetLongitudeInDegrees()); InteriorWorldPinSelectionHandler* pSelectionHandler = Eegeo_NEW(InteriorWorldPinSelectionHandler)(markerModel.GetInteriorId(), m_interiorController, m_cameraController, markerModel.GetMarkerLatLongAltitude().ToECEF(), *this); WorldPins::SdkModel::WorldPinItemModel* pItemModel = m_worldPinsService.AddPin(pSelectionHandler, NULL, worldPinFocusData, isInterior, worldPinInteriorData, location, iconIndex, heightOffsetMetres, WorldPins::SdkModel::WorldPinVisibility::World); m_interiorIdToWorldPinMap[markerModel.GetInteriorId().Value()] = pItemModel; } void InteriorWorldPinController::HandleMarkerRemoved(const Eegeo::Resources::Interiors::Markers::InteriorMarkerModel &markerModel) { Eegeo_ASSERT(m_interiorIdToWorldPinMap.find(markerModel.GetInteriorId().Value()) != m_interiorIdToWorldPinMap.end(), "InteriorWorldPinController does not have a pin with that Id"); WorldPins::SdkModel::WorldPinItemModel* pPinModel = m_interiorIdToWorldPinMap[markerModel.GetInteriorId().Value()]; m_worldPinsService.RemovePin(pPinModel); m_interiorIdToWorldPinMap.erase(markerModel.GetInteriorId().Value()); } void InteriorWorldPinController::HandleMenuDragged(const Menu::MenuDragStateChangedMessage &message) { m_menuIsDragging = message.IsDragging(); } } } }<commit_msg>Interior pins now use additional marker data if available. Buddy: Ian H<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "InteriorWorldPinController.h" #include "InteriorMarkerModelRepository.h" #include "IWorldPinsService.h" #include "InteriorMarkerModel.h" #include "WorldPinInteriorData.h" #include "WorldPinFocusData.h" #include "InteriorId.h" #include "InteriorWorldPinSelectionHandler.h" #include "WorldPinVisibility.h" #include "MenuDragStateChangedMessage.h" namespace ExampleApp { namespace InteriorsExplorer { namespace SdkModel { InteriorWorldPinController::InteriorWorldPinController(Eegeo::Resources::Interiors::InteriorController& interiorController, Eegeo::Resources::Interiors::Markers::InteriorMarkerModelRepository& markerRepository, WorldPins::SdkModel::IWorldPinsService& worldPinsService, InteriorsExplorerCameraController& cameraController, ExampleAppMessaging::TMessageBus& messageBus) : m_interiorController(interiorController) , m_markerRepository(markerRepository) , m_worldPinsService(worldPinsService) , m_cameraController(cameraController) , m_messageBus(messageBus) , m_markerAddedCallback(this, &InteriorWorldPinController::HandleMarkerAdded) , m_markerRemovedCallback(this, &InteriorWorldPinController::HandleMarkerRemoved) , m_menuDraggedCallback(this, &InteriorWorldPinController::HandleMenuDragged) , m_menuIsDragging(false) { m_markerRepository.RegisterNotifyAddedCallback(m_markerAddedCallback); m_markerRepository.RegisterNotifyRemovedCallback(m_markerRemovedCallback); m_messageBus.SubscribeNative(m_menuDraggedCallback); } InteriorWorldPinController::~InteriorWorldPinController() { m_messageBus.UnsubscribeNative(m_menuDraggedCallback); m_markerRepository.UnregisterNotifyAddedCallback(m_markerAddedCallback); m_markerRepository.UnregisterNotifyRemovedCallback(m_markerRemovedCallback); for(std::map<std::string, WorldPins::SdkModel::WorldPinItemModel*>::iterator it = m_interiorIdToWorldPinMap.begin(); it != m_interiorIdToWorldPinMap.end(); ++it) { WorldPins::SdkModel::WorldPinItemModel* pPinModel = it->second; m_worldPinsService.RemovePin(pPinModel); } m_interiorIdToWorldPinMap.clear(); } const bool InteriorWorldPinController::PinInteractionAllowed() const { return !m_menuIsDragging && m_interiorController.GetCurrentState() == Eegeo::Resources::Interiors::InteriorViewState::NoInteriorSelected; } void InteriorWorldPinController::HandleMarkerAdded(const Eegeo::Resources::Interiors::Markers::InteriorMarkerModel& markerModel) { Eegeo_ASSERT(m_interiorIdToWorldPinMap.find(markerModel.GetInteriorId().Value()) == m_interiorIdToWorldPinMap.end(), "InteriorWorldPinController already has a pin with that Id"); const float heightOffsetMetres = 0.0f; const bool isInterior = false; const int iconIndex = 11; WorldPins::SdkModel::WorldPinInteriorData worldPinInteriorData; // Don't have a human readable 'Name' for Interiors at this point. Can map IDS -> Names per app? ExampleApp::WorldPins::SdkModel::WorldPinFocusData worldPinFocusData(markerModel.GetInteriorName(), markerModel.GetInteriorOwner()); Eegeo::Space::LatLong location = Eegeo::Space::LatLong::FromDegrees(markerModel.GetMarkerLatLongAltitude().GetLatitudeInDegrees(), markerModel.GetMarkerLatLongAltitude().GetLongitudeInDegrees()); InteriorWorldPinSelectionHandler* pSelectionHandler = Eegeo_NEW(InteriorWorldPinSelectionHandler)(markerModel.GetInteriorId(), m_interiorController, m_cameraController, markerModel.GetMarkerLatLongAltitude().ToECEF(), *this); WorldPins::SdkModel::WorldPinItemModel* pItemModel = m_worldPinsService.AddPin(pSelectionHandler, NULL, worldPinFocusData, isInterior, worldPinInteriorData, location, iconIndex, heightOffsetMetres, WorldPins::SdkModel::WorldPinVisibility::World); m_interiorIdToWorldPinMap[markerModel.GetInteriorId().Value()] = pItemModel; } void InteriorWorldPinController::HandleMarkerRemoved(const Eegeo::Resources::Interiors::Markers::InteriorMarkerModel &markerModel) { Eegeo_ASSERT(m_interiorIdToWorldPinMap.find(markerModel.GetInteriorId().Value()) != m_interiorIdToWorldPinMap.end(), "InteriorWorldPinController does not have a pin with that Id"); WorldPins::SdkModel::WorldPinItemModel* pPinModel = m_interiorIdToWorldPinMap[markerModel.GetInteriorId().Value()]; m_worldPinsService.RemovePin(pPinModel); m_interiorIdToWorldPinMap.erase(markerModel.GetInteriorId().Value()); } void InteriorWorldPinController::HandleMenuDragged(const Menu::MenuDragStateChangedMessage &message) { m_menuIsDragging = message.IsDragging(); } } } }<|endoftext|>
<commit_before>#pragma once #include <mutex> #include <boost/thread.hpp> #include "blackhole/logger.hpp" namespace blackhole { template<class Logger, class Mutex = std::mutex> class synchronized { public: typedef Logger logger_type; typedef Mutex mutex_type; private: logger_type log; mutable mutex_type mutex; public: synchronized() {} explicit synchronized(logger_type&& logger) : log(std::move(logger)) {} synchronized(synchronized&& other) { *this = std::move(other); } synchronized& operator=(synchronized&& other) { //! @compat GCC4.4 //! GCC4.4 doesn't implement `std::lock` as like as `std::adopt_lock`. boost::lock(mutex, other.mutex); boost::lock_guard<mutex_type> lock(mutex, boost::adopt_lock); boost::lock_guard<mutex_type> other_lock(other.mutex, boost::adopt_lock); log = std::move(other.log); return *this; } bool enabled() const { std::lock_guard<mutex_type> lock(mutex); return log.enabled(); } void enable() { std::lock_guard<mutex_type> lock(mutex); log.enable(); } void disable() { std::lock_guard<mutex_type> lock(mutex); log.disable(); } void set_filter(filter_t&& filter) { std::lock_guard<mutex_type> lock(mutex); log.set_filter(std::move(filter)); } void add_attribute(const log::attribute_pair_t& attr) { std::lock_guard<mutex_type> lock(mutex); log.add_attribute(attr); } void add_frontend(std::unique_ptr<base_frontend_t> frontend) { std::lock_guard<mutex_type> lock(mutex); log.add_frontend(std::move(frontend)); } void set_exception_handler(log::exception_handler_t&& handler) { std::lock_guard<mutex_type> lock(mutex); log.set_exception_handler(std::move(handler)); } template<typename... Args> log::record_t open_record(Args&&... args) const { std::lock_guard<mutex_type> lock(mutex); return log.open_record(std::forward<Args>(args)...); } void push(log::record_t&& record) const { std::lock_guard<mutex_type> lock(mutex); log.push(std::move(record)); } } }; } // namespace blackhole <commit_msg>[Aux] Compatibility with scoped guards.<commit_after>#pragma once #include <mutex> #include <boost/thread.hpp> #include "blackhole/forwards.hpp" #include "blackhole/logger.hpp" namespace blackhole { template<class Logger, class Mutex> class synchronized { public: typedef Logger logger_type; typedef Mutex mutex_type; private: logger_type log; mutable mutex_type mutex; friend class scoped_attributes_t; public: synchronized() {} explicit synchronized(logger_type&& logger) : log(std::move(logger)) {} synchronized(synchronized&& other) { *this = std::move(other); } synchronized& operator=(synchronized&& other) { //! @compat GCC4.4 //! GCC4.4 doesn't implement `std::lock` as like as `std::adopt_lock`. boost::lock(mutex, other.mutex); boost::lock_guard<mutex_type> lock(mutex, boost::adopt_lock); boost::lock_guard<mutex_type> other_lock(other.mutex, boost::adopt_lock); log = std::move(other.log); return *this; } bool enabled() const { std::lock_guard<mutex_type> lock(mutex); return log.enabled(); } void enable() { std::lock_guard<mutex_type> lock(mutex); log.enable(); } void disable() { std::lock_guard<mutex_type> lock(mutex); log.disable(); } void set_filter(filter_t&& filter) { std::lock_guard<mutex_type> lock(mutex); log.set_filter(std::move(filter)); } void add_attribute(const log::attribute_pair_t& attr) { std::lock_guard<mutex_type> lock(mutex); log.add_attribute(attr); } void add_frontend(std::unique_ptr<base_frontend_t> frontend) { std::lock_guard<mutex_type> lock(mutex); log.add_frontend(std::move(frontend)); } void set_exception_handler(log::exception_handler_t&& handler) { std::lock_guard<mutex_type> lock(mutex); log.set_exception_handler(std::move(handler)); } template<typename... Args> log::record_t open_record(Args&&... args) const { std::lock_guard<mutex_type> lock(mutex); return log.open_record(std::forward<Args>(args)...); } void push(log::record_t&& record) const { std::lock_guard<mutex_type> lock(mutex); log.push(std::move(record)); } } }; } // namespace blackhole <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2014 Baptiste Burles, Kliplab 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 "../klipframework.h" static uint32_t m_z = 12434 ; static uint32_t m_w = 33254; void setRandomSeed(uint32_t s) { m_z = s; } uint32_t getRandom(void) { m_z = 36969 * (m_z & 65535) + (m_z >>16); m_w = 18000 * (m_w & 65535) + (m_w >>16); return ((m_z <<16) + m_w); } int32_t getRandomBetween(int32_t lowBoundary, int32_t highBoundary) { return (getRandom() % (highBoundary - lowBoundary + 1) + lowBoundary); } uint32_t read32bitsFromBuffer(uint8_t *buffer) { uint32_t integer; uint32_t temp; temp = buffer[3]; integer = temp << 24UL; temp = buffer[2]; integer = (temp << 16UL) | integer; temp = buffer[1]; integer = (temp << 8UL) | integer; temp = buffer[0]; integer = (temp) | integer; return integer; } void write32bitsToBuffer(uint8_t *buffer, uint32_t result) { buffer[0] = (uint8_t)(integer & 0xFF); buffer[1] = (uint8_t)((integer>>8UL) & 0xFF); buffer[2] = (uint8_t)((integer>>16UL) & 0xFF); buffer[3] = (uint8_t)((integer>>24UL) & 0xFF); } void write16bitsToBuffer(uint8_t * buffer, uint16_t integer) { buffer[0] = (uint8_t)(integer); buffer[1] = (integer>>8UL); } uint16_t read16bitsFromBuffer(const uint8_t * buffer) { uint16_t integer = (buffer[1]<<8UL)| (buffer[0]); return integer; }<commit_msg>Fix name<commit_after>/* The MIT License (MIT) Copyright (c) 2014 Baptiste Burles, Kliplab 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 "../klipframework.h" static uint32_t m_z = 12434 ; static uint32_t m_w = 33254; void setRandomSeed(uint32_t s) { m_z = s; } uint32_t getRandom(void) { m_z = 36969 * (m_z & 65535) + (m_z >>16); m_w = 18000 * (m_w & 65535) + (m_w >>16); return ((m_z <<16) + m_w); } int32_t getRandomBetween(int32_t lowBoundary, int32_t highBoundary) { return (getRandom() % (highBoundary - lowBoundary + 1) + lowBoundary); } uint32_t read32bitsFromBuffer(uint8_t *buffer) { uint32_t integer; uint32_t temp; temp = buffer[3]; integer = temp << 24UL; temp = buffer[2]; integer = (temp << 16UL) | integer; temp = buffer[1]; integer = (temp << 8UL) | integer; temp = buffer[0]; integer = (temp) | integer; return integer; } void write32bitsToBuffer(uint8_t *buffer, uint32_t integer) { buffer[0] = (uint8_t)(integer & 0xFF); buffer[1] = (uint8_t)((integer>>8UL) & 0xFF); buffer[2] = (uint8_t)((integer>>16UL) & 0xFF); buffer[3] = (uint8_t)((integer>>24UL) & 0xFF); } void write16bitsToBuffer(uint8_t * buffer, uint16_t integer) { buffer[0] = (uint8_t)(integer); buffer[1] = (integer>>8UL); } uint16_t read16bitsFromBuffer(const uint8_t * buffer) { uint16_t integer = (buffer[1]<<8UL)| (buffer[0]); return integer; }<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 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 Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "ClusterTraverser.h" #include "Basics/StaticStrings.h" #include "Basics/VelocyPackHelper.h" #include "Cluster/ClusterMethods.h" #include <velocypack/Iterator.h> #include <velocypack/velocypack-aliases.h> using namespace arangodb; using ClusterTraverser = arangodb::traverser::ClusterTraverser; ClusterTraverser::ClusterTraverser( arangodb::traverser::TraverserOptions* opts, ManagedDocumentResult* mmdr, std::unordered_map<ServerID, traverser::TraverserEngineID> const* engines, std::string const& dbname, Transaction* trx) : Traverser(opts, trx, mmdr), _dbname(dbname), _engines(engines) { _opts->linkTraverser(this); } void ClusterTraverser::setStartVertex(std::string const& id) { _verticesToFetch.clear(); _startIdBuilder->clear(); _startIdBuilder->add(VPackValue(id)); VPackSlice idSlice = _startIdBuilder->slice(); auto it = _vertices.find(idSlice); if (it == _vertices.end()) { size_t firstSlash = id.find("/"); if (firstSlash == std::string::npos || id.find("/", firstSlash + 1) != std::string::npos) { // We can stop here. The start vertex is not a valid _id ++_filteredPaths; _done = true; return; } } if (!vertexMatchesConditions(idSlice, 0)) { // Start vertex invalid _done = true; return; } _vertexGetter->reset(idSlice); if (_opts->useBreadthFirst) { _enumerator.reset( new arangodb::traverser::BreadthFirstEnumerator(this, idSlice, _opts)); } else { _enumerator.reset( new arangodb::traverser::DepthFirstEnumerator(this, idSlice, _opts)); } _done = false; } bool ClusterTraverser::getVertex(VPackSlice edge, std::vector<VPackSlice>& result) { bool res = _vertexGetter->getVertex(edge, result); if (res) { VPackSlice other = result.back(); if (_vertices.find(other) == _vertices.end()) { // Vertex not yet cached. Prepare it. _verticesToFetch.emplace(other); } } return res; } bool ClusterTraverser::getSingleVertex(VPackSlice edge, VPackSlice comp, size_t depth, VPackSlice& result) { bool res = _vertexGetter->getSingleVertex(edge, comp, depth, result); if (res) { if (_vertices.find(result) == _vertices.end()) { // Vertex not yet cached. Prepare it. _verticesToFetch.emplace(result); } } return res; } void ClusterTraverser::fetchVertices() { _readDocuments += _verticesToFetch.size(); TransactionBuilderLeaser lease(_trx); fetchVerticesFromEngines(_dbname, _engines, _verticesToFetch, _vertices, *(lease.get())); _verticesToFetch.clear(); } aql::AqlValue ClusterTraverser::fetchVertexData(VPackSlice idString) { TRI_ASSERT(idString.isString()); auto cached = _vertices.find(idString); if (cached == _vertices.end()) { // Vertex not yet cached. Prepare for load. _verticesToFetch.emplace(idString); fetchVertices(); cached = _vertices.find(idString); } // Now all vertices are cached!! TRI_ASSERT(cached != _vertices.end()); return aql::AqlValue((*cached).second->data()); } aql::AqlValue ClusterTraverser::fetchEdgeData(VPackSlice edge) { return aql::AqlValue(edge); } ////////////////////////////////////////////////////////////////////////////// /// @brief Function to add the real data of a vertex into a velocypack builder ////////////////////////////////////////////////////////////////////////////// void ClusterTraverser::addVertexToVelocyPack(VPackSlice id, VPackBuilder& result) { TRI_ASSERT(id.isString()); auto cached = _vertices.find(id); if (cached == _vertices.end()) { // Vertex not yet cached. Prepare for load. _verticesToFetch.emplace(id); fetchVertices(); cached = _vertices.find(id); } // Now all vertices are cached!! TRI_ASSERT(cached != _vertices.end()); result.add(VPackSlice((*cached).second->data())); } ////////////////////////////////////////////////////////////////////////////// /// @brief Function to add the real data of an edge into a velocypack builder ////////////////////////////////////////////////////////////////////////////// void ClusterTraverser::addEdgeToVelocyPack(arangodb::velocypack::Slice edge, arangodb::velocypack::Builder& result) { result.add(edge); } <commit_msg>fix compile error<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 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 Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "ClusterTraverser.h" #include "Basics/StaticStrings.h" #include "Basics/VelocyPackHelper.h" #include "Cluster/ClusterMethods.h" #include <velocypack/Iterator.h> #include <velocypack/velocypack-aliases.h> using namespace arangodb; using ClusterTraverser = arangodb::traverser::ClusterTraverser; ClusterTraverser::ClusterTraverser( arangodb::traverser::TraverserOptions* opts, ManagedDocumentResult* mmdr, std::unordered_map<ServerID, traverser::TraverserEngineID> const* engines, std::string const& dbname, Transaction* trx) : Traverser(opts, trx, mmdr), _dbname(dbname), _engines(engines) { _opts->linkTraverser(this); } void ClusterTraverser::setStartVertex(std::string const& id) { _verticesToFetch.clear(); _startIdBuilder->clear(); _startIdBuilder->add(VPackValue(id)); VPackSlice idSlice = _startIdBuilder->slice(); auto it = _vertices.find(idSlice); if (it == _vertices.end()) { size_t firstSlash = id.find("/"); if (firstSlash == std::string::npos || id.find("/", firstSlash + 1) != std::string::npos) { // We can stop here. The start vertex is not a valid _id ++_filteredPaths; _done = true; return; } } if (!vertexMatchesConditions(idSlice, 0)) { // Start vertex invalid _done = true; return; } _vertexGetter->reset(idSlice); if (_opts->useBreadthFirst) { _enumerator.reset( new arangodb::traverser::BreadthFirstEnumerator(this, idSlice, _opts)); } else { _enumerator.reset( new arangodb::traverser::DepthFirstEnumerator(this, idSlice, _opts)); } _done = false; } bool ClusterTraverser::getVertex(VPackSlice edge, std::vector<VPackSlice>& result) { bool res = _vertexGetter->getVertex(edge, result); if (res) { VPackSlice other = result.back(); if (_vertices.find(other) == _vertices.end()) { // Vertex not yet cached. Prepare it. _verticesToFetch.emplace(other); } } return res; } bool ClusterTraverser::getSingleVertex(VPackSlice edge, VPackSlice comp, uint64_t depth, VPackSlice& result) { bool res = _vertexGetter->getSingleVertex(edge, comp, depth, result); if (res) { if (_vertices.find(result) == _vertices.end()) { // Vertex not yet cached. Prepare it. _verticesToFetch.emplace(result); } } return res; } void ClusterTraverser::fetchVertices() { _readDocuments += _verticesToFetch.size(); TransactionBuilderLeaser lease(_trx); fetchVerticesFromEngines(_dbname, _engines, _verticesToFetch, _vertices, *(lease.get())); _verticesToFetch.clear(); } aql::AqlValue ClusterTraverser::fetchVertexData(VPackSlice idString) { TRI_ASSERT(idString.isString()); auto cached = _vertices.find(idString); if (cached == _vertices.end()) { // Vertex not yet cached. Prepare for load. _verticesToFetch.emplace(idString); fetchVertices(); cached = _vertices.find(idString); } // Now all vertices are cached!! TRI_ASSERT(cached != _vertices.end()); return aql::AqlValue((*cached).second->data()); } aql::AqlValue ClusterTraverser::fetchEdgeData(VPackSlice edge) { return aql::AqlValue(edge); } ////////////////////////////////////////////////////////////////////////////// /// @brief Function to add the real data of a vertex into a velocypack builder ////////////////////////////////////////////////////////////////////////////// void ClusterTraverser::addVertexToVelocyPack(VPackSlice id, VPackBuilder& result) { TRI_ASSERT(id.isString()); auto cached = _vertices.find(id); if (cached == _vertices.end()) { // Vertex not yet cached. Prepare for load. _verticesToFetch.emplace(id); fetchVertices(); cached = _vertices.find(id); } // Now all vertices are cached!! TRI_ASSERT(cached != _vertices.end()); result.add(VPackSlice((*cached).second->data())); } ////////////////////////////////////////////////////////////////////////////// /// @brief Function to add the real data of an edge into a velocypack builder ////////////////////////////////////////////////////////////////////////////// void ClusterTraverser::addEdgeToVelocyPack(arangodb::velocypack::Slice edge, arangodb::velocypack::Builder& result) { result.add(edge); } <|endoftext|>
<commit_before>//! \file ********************************************************************** //! \brief Source Action de traduction ver une notification. //! //! - Compilateur : GCC,MinGW //! //! \author Antoine Maleyrie //! \version 1.0 //! \date 17.03.2013 //! //! *************************************************************************** //App #include "action/actTranslationToNotification.hpp" #include "manager/manNotification.hpp" #include "manager/manGeneral.hpp" #include "manager/manTranslator.hpp" #include "dataText.hpp" #include "defs.hpp" //WxWidgets #include <wx/intl.h> #include <wx/sizer.h> // ***************************************************************************** // Class ActTranslationToNotification // ***************************************************************************** ActTranslationToNotification::ActTranslationToNotification() { _lgto = ManGeneral::get().getSystemLanguage(); if( _lgto == wxLANGUAGE_ENGLISH) _lgsrc = wxLANGUAGE_FRENCH; else _lgsrc = wxLANGUAGE_ENGLISH; } ActTranslationToNotification::~ActTranslationToNotification() { } IMPLEMENT_ACTION(ActTranslationToNotification, _("Translation to Notification"), _("Translation a text from clipboard into notification.")); WinAction* ActTranslationToNotification::newEditWindow(wxWindow* parent) { return new WinActTranslationToNotification(parent, this); } wxString ActTranslationToNotification::getStringPreferences()const { return wxLocale::GetLanguageName(_lgsrc) + ' ' + _("to") + ' ' + wxLocale::GetLanguageName(_lgto); } //! \todo ajouter le compter de traduction void ActTranslationToNotification::execute() { //On récupère le texte de la presse papier a traduire. wxString clipboard = ManGeneral::get().getClipboard(); //La presse papier est t'elle vide ? if(clipboard.IsEmpty()) { //Pas de texte à traduire ManNotification::get().notify(_("Nothing at translate"), _("Your clipboard is empty."), wxICON_INFORMATION); return; } //On récupère le texte traduit DataText translations; ManTranslator::get().getTranslations(&translations, clipboard, _lgsrc, _lgto); //On vérifie si une traduction existe. if(translations.getMainTranslation().IsEmpty()) { ManNotification::get().notify(_("No translation"), _("Sorry, there is no translation for the text: \""+clipboard+"\""), wxICON_INFORMATION); return; } //On mes en forme la traduction dans un wxString wxString translationsNotify; translationsNotify << "\n==&gt; <big>" << translations.getMainTranslation() << "</big>"; auto trls = translations.getTranslations(); for(auto &it: trls) { translationsNotify << "\n\n<i>" << it.first << ":</i>"; for(auto &itt: it.second) { translationsNotify << "\n\t" << itt; } } //On affiche la traduction ManNotification::get().notify( wxString::Format(_("Clipboard translation to %s:"), wxLocale::GetLanguageName(_lgto)), translationsNotify, wxICON_NONE, true); } void ActTranslationToNotification::getLanguages(wxLanguage* lgsrc, wxLanguage* lgto)const { *lgsrc = _lgsrc; *lgto = _lgto; } void ActTranslationToNotification::setLanguages(wxLanguage lgsrc, wxLanguage lgto) { _lgsrc = lgsrc; _lgto = lgto; } void ActTranslationToNotification::actLoad(wxFileConfig& fileConfig) { _lgto = ManGeneral::get().getSystemLanguage(); if( _lgto == wxLANGUAGE_ENGLISH) _lgsrc = wxLANGUAGE_FRENCH; else _lgsrc = wxLANGUAGE_ENGLISH; //On récupère les préférence. _lgsrc = (wxLanguage)fileConfig.ReadLong("lgsrc", (long)_lgsrc); _lgto = (wxLanguage)fileConfig.ReadLong("lgto", (long)_lgto); } void ActTranslationToNotification::actSave(wxFileConfig& fileConfig)const { fileConfig.Write("lgsrc", (long)_lgsrc); fileConfig.Write("lgto", (long)_lgto); } // ***************************************************************************** // Class WinActTranslationToNotification // ***************************************************************************** WinActTranslationToNotification::WinActTranslationToNotification(wxWindow* parent, ActTranslationToNotification const* act) : WinAction(parent, act) { //Créations du CtrlPickLanguages. wxLanguage lgsrc; wxLanguage lgto; static_cast<ActTranslationToNotification*>(_act)->getLanguages(&lgsrc, &lgto); _ctrlPickLanguages = new CtrlPickLanguages(this, lgsrc, lgto); GetSizer()->Add(_ctrlPickLanguages, 0, wxEXPAND|wxLEFT|wxRIGHT|wxBOTTOM, SIZE_BORDER); } WinActTranslationToNotification::~WinActTranslationToNotification() { } void WinActTranslationToNotification::refreshActionFromGui() { wxLanguage lgsrc; wxLanguage lgto; _ctrlPickLanguages->getLanguages(&lgsrc, &lgto); static_cast<ActTranslationToNotification*>(_act)->setLanguages(lgsrc, lgto); } <commit_msg>update actLoad and actSave in ActTranslationToNotification<commit_after>//! \file ********************************************************************** //! \brief Source Action de traduction ver une notification. //! //! - Compilateur : GCC,MinGW //! //! \author Antoine Maleyrie //! \version 1.0 //! \date 17.03.2013 //! //! *************************************************************************** //App #include "action/actTranslationToNotification.hpp" #include "manager/manNotification.hpp" #include "manager/manGeneral.hpp" #include "manager/manTranslator.hpp" #include "dataText.hpp" #include "defs.hpp" //WxWidgets #include <wx/intl.h> #include <wx/sizer.h> // ***************************************************************************** // Class ActTranslationToNotification // ***************************************************************************** ActTranslationToNotification::ActTranslationToNotification() { _lgto = ManGeneral::get().getSystemLanguage(); if( _lgto == wxLANGUAGE_ENGLISH) _lgsrc = wxLANGUAGE_FRENCH; else _lgsrc = wxLANGUAGE_ENGLISH; } ActTranslationToNotification::~ActTranslationToNotification() { } IMPLEMENT_ACTION(ActTranslationToNotification, _("Translation to Notification"), _("Translation a text from clipboard into notification.")); WinAction* ActTranslationToNotification::newEditWindow(wxWindow* parent) { return new WinActTranslationToNotification(parent, this); } wxString ActTranslationToNotification::getStringPreferences()const { return wxLocale::GetLanguageName(_lgsrc) + ' ' + _("to") + ' ' + wxLocale::GetLanguageName(_lgto); } //! \todo ajouter le compter de traduction void ActTranslationToNotification::execute() { //On récupère le texte de la presse papier a traduire. wxString clipboard = ManGeneral::get().getClipboard(); //La presse papier est t'elle vide ? if(clipboard.IsEmpty()) { //Pas de texte à traduire ManNotification::get().notify(_("Nothing at translate"), _("Your clipboard is empty."), wxICON_INFORMATION); return; } //On récupère le texte traduit DataText translations; ManTranslator::get().getTranslations(&translations, clipboard, _lgsrc, _lgto); //On vérifie si une traduction existe. if(translations.getMainTranslation().IsEmpty()) { ManNotification::get().notify(_("No translation"), _("Sorry, there is no translation for the text!"), wxICON_INFORMATION); return; } //On mes en forme la traduction dans un wxString wxString translationsNotify; translationsNotify << "\n==&gt; <big>" << translations.getMainTranslation() << "</big>"; auto trls = translations.getTranslations(); for(auto &it: trls) { translationsNotify << "\n\n<i>" << it.first << ":</i>"; for(auto &itt: it.second) { translationsNotify << "\n\t" << itt; } } //On affiche la traduction ManNotification::get().notify( wxString::Format(_("Clipboard translation to %s:"), wxLocale::GetLanguageName(_lgto)), translationsNotify, wxICON_NONE, true); } void ActTranslationToNotification::getLanguages(wxLanguage* lgsrc, wxLanguage* lgto)const { *lgsrc = _lgsrc; *lgto = _lgto; } void ActTranslationToNotification::setLanguages(wxLanguage lgsrc, wxLanguage lgto) { _lgsrc = lgsrc; _lgto = lgto; } void ActTranslationToNotification::actLoad(wxFileConfig& fileConfig) { _lgto = ManGeneral::get().getSystemLanguage(); if( _lgto == wxLANGUAGE_ENGLISH) _lgsrc = wxLANGUAGE_FRENCH; else _lgsrc = wxLANGUAGE_ENGLISH; //On récupère les préférences. wxString lg; lg = fileConfig.Read("lgsrc", wxLocale::GetLanguageName(_lgsrc)); _lgsrc = (wxLanguage)wxLocale::FindLanguageInfo(lg)->Language; lg = fileConfig.Read("lgto", wxLocale::GetLanguageName(_lgto)); _lgto = (wxLanguage)wxLocale::FindLanguageInfo(lg)->Language; } void ActTranslationToNotification::actSave(wxFileConfig& fileConfig)const { fileConfig.Write("lgsrc", wxLocale::GetLanguageName(_lgsrc)); fileConfig.Write("lgto", wxLocale::GetLanguageName(_lgto)); } // ***************************************************************************** // Class WinActTranslationToNotification // ***************************************************************************** WinActTranslationToNotification::WinActTranslationToNotification(wxWindow* parent, ActTranslationToNotification const* act) : WinAction(parent, act) { //Créations du CtrlPickLanguages. wxLanguage lgsrc; wxLanguage lgto; static_cast<ActTranslationToNotification*>(_act)->getLanguages(&lgsrc, &lgto); _ctrlPickLanguages = new CtrlPickLanguages(this, lgsrc, lgto); GetSizer()->Add(_ctrlPickLanguages, 0, wxEXPAND|wxLEFT|wxRIGHT|wxBOTTOM, SIZE_BORDER); } WinActTranslationToNotification::~WinActTranslationToNotification() { } void WinActTranslationToNotification::refreshActionFromGui() { wxLanguage lgsrc; wxLanguage lgto; _ctrlPickLanguages->getLanguages(&lgsrc, &lgto); static_cast<ActTranslationToNotification*>(_act)->setLanguages(lgsrc, lgto); } <|endoftext|>
<commit_before> #pragma once /** * Graph.hpp * Purpose: An class for the representation of attributed graphs and digraphs. * * @author Kevin A. Naudé * @version 1.1 */ #include <algorithm> #include <assert.h> #include <string> #include <limits> #include <vector> #include <unordered_map> #include <memory> #include <BitStructures.hpp> #include <AttributeModel.hpp> namespace kn { class Graph { public: typedef std::size_t VertexID; typedef std::size_t EdgeID; typedef std::size_t AttrID; struct Edge { EdgeID id; VertexID u; VertexID v; AttrID attrID; bool undirected; }; struct Vertex { VertexID id; std::size_t outDegree; std::size_t inDegree; AttrID attrID; }; struct Pair { VertexID u; VertexID v; Pair() {} Pair(VertexID u, VertexID v) { this->u = u; this->v = v; } }; class VertexIterator; class EdgeIterator; class Walker; private: struct EdgeInfo : Edge { EdgeInfo* prevToDestination; EdgeInfo* nextToDestination; EdgeInfo* prevFromSource; EdgeInfo* nextFromSource; }; struct VertexInfo : Vertex { EdgeInfo* destinationEdges; EdgeInfo* sourceEdges; }; private: const AttributeModel* vertexAttributes; const AttributeModel* edgeAttributes; std::vector<VertexInfo> vertices; std::unordered_map<VertexID, std::size_t> vertexIDtoIndex; std::unordered_map<EdgeID, VertexID> edgeIDtoSourceID; VertexID nextVertexID; EdgeID nextEdgeID; void deleteEdge(EdgeInfo* e); void removeEdgeHelper(VertexID sourceID, VertexID destinationID); void insertEdge(EdgeID id, VertexID sourceID, VertexID destinationID, AttrID attrID, bool undirected); void vertexAdjacency(VertexID id, IntegerSet& row); public: Graph(); Graph(const AttributeModel* vertexAttributeModel, const AttributeModel* edgeAttributeModel); Graph(const Graph& other, bool complement); virtual ~Graph(); Graph(Graph&& other); Graph& operator=(Graph&& other); const AttributeModel* getVertexAttributeModel() const { return vertexAttributes; } const AttributeModel* getEdgeAttributeModel() const { return edgeAttributes; } std::unique_ptr<IntegerSet> vertexAdjacency(VertexID id) { std::unique_ptr<IntegerSet> adj(new IntegerSet(vertices.size())); vertexAdjacency(id, *adj); return adj; } std::unique_ptr<std::vector<IntegerSet>> adjacency(); std::size_t countVertices() const { return vertices.size(); } std::size_t countEdges() const { return edgeIDtoSourceID.size(); } VertexIterator vertexIterator() const { return VertexIterator(this); } EdgeIterator exitingEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* u = &vertices[index]; return EdgeIterator(u->sourceEdges, true); } EdgeIterator enteringEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* v = &vertices[index]; return EdgeIterator(v->destinationEdges, false); } bool validVertexID(VertexID id) const { return (vertexIDtoIndex.find(id) != vertexIDtoIndex.end()); } VertexID getVertexID(std::size_t index) const { if (index < vertices.size()) { return vertices[index].id; } else { return 0; } } bool getVertex(VertexID id, Vertex& v) const { if (!validVertexID(id)) { // This line prevents a spurious compiler warning. v.id = v.outDegree = v.inDegree = v.attrID = 0; return false; } v = vertices[vertexIDtoIndex.at(id)]; return true; } bool getEdge(EdgeID id, Edge& e) const; bool getEdge(VertexID sourceID, VertexID destinationID, Edge& e) const; VertexID addVertex(AttrID attrID) { VertexID id = nextVertexID++; std::size_t index = vertices.size(); VertexInfo v; v.id = id; v.outDegree = 0; v.inDegree = 0; v.sourceEdges = nullptr; v.destinationEdges = nullptr; v.attrID = attrID; vertices.push_back(v); vertexIDtoIndex.insert(std::make_pair(id, index)); return id; } bool removeVertex(VertexID id); bool removeEdge(EdgeID id) { Edge e; if (getEdge(id, e)) return removeEdge(e.u, e.v); else return false; } bool removeEdge(VertexID sourceID, VertexID destinationID); bool hasArc(VertexID sourceID, VertexID destinationID) const; bool hasEdge(VertexID sourceID, VertexID destinationID) const; EdgeID addArc(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; insertEdge(id, sourceID, destinationID, attrID, false); edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } EdgeID addEdge(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; if (sourceID > destinationID) { // reordering the end points is not strictly required. std::swap(sourceID, destinationID); } insertEdge(id, sourceID, destinationID, attrID, true); if (sourceID != destinationID) { insertEdge(id, destinationID, sourceID, attrID, true); } edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } std::vector<VertexID> listOfVertices() { std::vector<VertexID> result(vertices.size()); for (auto it = vertices.begin(); it != vertices.end(); ++it) { result.push_back(it->id); } return result; } std::vector<Pair> listOfEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u <= v) && hasEdge(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if (hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u < v) && !hasArc(u, v) && !hasArc(v, u)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u != v) && !hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } public: class VertexIterator { private: friend class Graph; const Graph* graph; std::size_t index; std::size_t count; VertexIterator(const Graph* graph) { this->graph = graph; index = 0; count = graph->countVertices(); } public: bool hasNext() { return index < count; } bool next(Vertex& v) { if (index < count) { graph->getVertex(graph->getVertexID(index), v); index++; return true; } else return false; } bool current(Vertex& v) const { return graph->getVertex(graph->getVertexID(index), v); } }; class EdgeIterator { private: friend class Graph; friend class Walker; const EdgeInfo* ei; bool exitingEdges; EdgeIterator(const EdgeInfo* ei, bool exitingEdges) { this->ei = ei; this->exitingEdges = exitingEdges; } public: bool hasNext() { return (ei != nullptr); } bool next(Edge& e) { if (ei) { e = *ei; if (exitingEdges) ei = ei->nextFromSource; else ei = ei->nextToDestination; return true; } else return false; } bool current(Edge& e) const { if (ei) { e = *ei; return true; } else return false; } }; class Walker { private: friend class Graph; const Graph* graph; VertexID position; Walker(const Graph* graph, VertexID position) { this->graph = graph; this->position = position; } public: bool teleport(VertexID id) { if (graph->validVertexID(id)) { position = id; return true; } else return false; } EdgeIterator exitingEdges() const { return graph->exitingEdgeIterator(position); } EdgeIterator enteringEdges() const { return graph->enteringEdgeIterator(position); } VertexID moveForwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.v; return position; } else return 0; } VertexID moveBackwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.u; return position; } else return 0; } VertexID moveForwardAlong(EdgeID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.v; return position; } } return 0; } VertexID moveBackwardAlong(EdgeID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.u; return position; } } return 0; } EdgeID moveForwardTo(VertexID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.v == id) { position = id; return e.id; } } return 0; } EdgeID moveBackwardTo(VertexID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.u == id) { position = id; return e.id; } } return 0; } }; }; } <commit_msg>Graph: added getVertexByIndex<commit_after> #pragma once /** * Graph.hpp * Purpose: An class for the representation of attributed graphs and digraphs. * * @author Kevin A. Naudé * @version 1.1 */ #include <algorithm> #include <assert.h> #include <string> #include <limits> #include <vector> #include <unordered_map> #include <memory> #include <BitStructures.hpp> #include <AttributeModel.hpp> namespace kn { class Graph { public: typedef std::size_t VertexID; typedef std::size_t EdgeID; typedef std::size_t AttrID; struct Edge { EdgeID id; VertexID u; VertexID v; AttrID attrID; bool undirected; }; struct Vertex { VertexID id; std::size_t outDegree; std::size_t inDegree; AttrID attrID; }; struct Pair { VertexID u; VertexID v; Pair() {} Pair(VertexID u, VertexID v) { this->u = u; this->v = v; } }; class VertexIterator; class EdgeIterator; class Walker; private: struct EdgeInfo : Edge { EdgeInfo* prevToDestination; EdgeInfo* nextToDestination; EdgeInfo* prevFromSource; EdgeInfo* nextFromSource; }; struct VertexInfo : Vertex { EdgeInfo* destinationEdges; EdgeInfo* sourceEdges; }; private: const AttributeModel* vertexAttributes; const AttributeModel* edgeAttributes; std::vector<VertexInfo> vertices; std::unordered_map<VertexID, std::size_t> vertexIDtoIndex; std::unordered_map<EdgeID, VertexID> edgeIDtoSourceID; VertexID nextVertexID; EdgeID nextEdgeID; void deleteEdge(EdgeInfo* e); void removeEdgeHelper(VertexID sourceID, VertexID destinationID); void insertEdge(EdgeID id, VertexID sourceID, VertexID destinationID, AttrID attrID, bool undirected); void vertexAdjacency(VertexID id, IntegerSet& row); public: Graph(); Graph(const AttributeModel* vertexAttributeModel, const AttributeModel* edgeAttributeModel); Graph(const Graph& other, bool complement); virtual ~Graph(); Graph(Graph&& other); Graph& operator=(Graph&& other); const AttributeModel* getVertexAttributeModel() const { return vertexAttributes; } const AttributeModel* getEdgeAttributeModel() const { return edgeAttributes; } std::unique_ptr<IntegerSet> vertexAdjacency(VertexID id) { std::unique_ptr<IntegerSet> adj(new IntegerSet(vertices.size())); vertexAdjacency(id, *adj); return adj; } std::unique_ptr<std::vector<IntegerSet>> adjacency(); std::size_t countVertices() const { return vertices.size(); } std::size_t countEdges() const { return edgeIDtoSourceID.size(); } VertexIterator vertexIterator() const { return VertexIterator(this); } EdgeIterator exitingEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* u = &vertices[index]; return EdgeIterator(u->sourceEdges, true); } EdgeIterator enteringEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* v = &vertices[index]; return EdgeIterator(v->destinationEdges, false); } bool validVertexID(VertexID id) const { return (vertexIDtoIndex.find(id) != vertexIDtoIndex.end()); } VertexID getVertexID(std::size_t index) const { if (index < vertices.size()) { return vertices[index].id; } else { return 0; } } bool getVertex(VertexID id, Vertex& v) const { if (!validVertexID(id)) { // This line prevents a spurious compiler warning. v.id = v.outDegree = v.inDegree = v.attrID = 0; return false; } v = vertices[vertexIDtoIndex.at(id)]; return true; } bool getVertexByIndex(std::size_t index, Vertex& v) const { if (index >= vertices.size()) { // This line prevents a spurious compiler warning. v.id = v.outDegree = v.inDegree = v.attrID = 0; return false; } v = vertices[index]; return true; } bool getEdge(EdgeID id, Edge& e) const; bool getEdge(VertexID sourceID, VertexID destinationID, Edge& e) const; VertexID addVertex(AttrID attrID) { VertexID id = nextVertexID++; std::size_t index = vertices.size(); VertexInfo v; v.id = id; v.outDegree = 0; v.inDegree = 0; v.sourceEdges = nullptr; v.destinationEdges = nullptr; v.attrID = attrID; vertices.push_back(v); vertexIDtoIndex.insert(std::make_pair(id, index)); return id; } bool removeVertex(VertexID id); bool removeEdge(EdgeID id) { Edge e; if (getEdge(id, e)) return removeEdge(e.u, e.v); else return false; } bool removeEdge(VertexID sourceID, VertexID destinationID); bool hasArc(VertexID sourceID, VertexID destinationID) const; bool hasEdge(VertexID sourceID, VertexID destinationID) const; EdgeID addArc(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; insertEdge(id, sourceID, destinationID, attrID, false); edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } EdgeID addEdge(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; if (sourceID > destinationID) { // reordering the end points is not strictly required. std::swap(sourceID, destinationID); } insertEdge(id, sourceID, destinationID, attrID, true); if (sourceID != destinationID) { insertEdge(id, destinationID, sourceID, attrID, true); } edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } std::vector<VertexID> listOfVertices() { std::vector<VertexID> result(vertices.size()); for (auto it = vertices.begin(); it != vertices.end(); ++it) { result.push_back(it->id); } return result; } std::vector<Pair> listOfEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u <= v) && hasEdge(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if (hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u < v) && !hasArc(u, v) && !hasArc(v, u)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u != v) && !hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } public: class VertexIterator { private: friend class Graph; const Graph* graph; std::size_t index; std::size_t count; VertexIterator(const Graph* graph) { this->graph = graph; index = 0; count = graph->countVertices(); } public: bool hasNext() { return index < count; } bool next(Vertex& v) { if (index < count) { graph->getVertex(graph->getVertexID(index), v); index++; return true; } else return false; } bool current(Vertex& v) const { return graph->getVertex(graph->getVertexID(index), v); } }; class EdgeIterator { private: friend class Graph; friend class Walker; const EdgeInfo* ei; bool exitingEdges; EdgeIterator(const EdgeInfo* ei, bool exitingEdges) { this->ei = ei; this->exitingEdges = exitingEdges; } public: bool hasNext() { return (ei != nullptr); } bool next(Edge& e) { if (ei) { e = *ei; if (exitingEdges) ei = ei->nextFromSource; else ei = ei->nextToDestination; return true; } else return false; } bool current(Edge& e) const { if (ei) { e = *ei; return true; } else return false; } }; class Walker { private: friend class Graph; const Graph* graph; VertexID position; Walker(const Graph* graph, VertexID position) { this->graph = graph; this->position = position; } public: bool teleport(VertexID id) { if (graph->validVertexID(id)) { position = id; return true; } else return false; } EdgeIterator exitingEdges() const { return graph->exitingEdgeIterator(position); } EdgeIterator enteringEdges() const { return graph->enteringEdgeIterator(position); } VertexID moveForwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.v; return position; } else return 0; } VertexID moveBackwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.u; return position; } else return 0; } VertexID moveForwardAlong(EdgeID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.v; return position; } } return 0; } VertexID moveBackwardAlong(EdgeID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.u; return position; } } return 0; } EdgeID moveForwardTo(VertexID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.v == id) { position = id; return e.id; } } return 0; } EdgeID moveBackwardTo(VertexID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.u == id) { position = id; return e.id; } } return 0; } }; }; } <|endoftext|>
<commit_before>#include "type.h" #include "pt_data.h" #include <iostream> #include <boost/assign.hpp> #include "utils/functions.h" namespace navitia { namespace type { bool ValidityPattern::is_valid(int duration) const { if(duration < 0){ std::cerr << "La date est avant le début de période(" << beginning_date << ")" << std::endl; return false; } else if(duration > 366){ std::cerr << "La date dépasse la fin de période " << duration << " " << std::endl; return false; } return true; } int ValidityPattern::slide(boost::gregorian::date day) const { return (day - beginning_date).days(); } void ValidityPattern::add(boost::gregorian::date day){ long duration = slide(day); add(duration); } void ValidityPattern::add(int duration){ if(is_valid(duration)) days[duration] = true; } void ValidityPattern::remove(boost::gregorian::date date){ long duration = slide(date); remove(duration); } void ValidityPattern::remove(int day){ if(is_valid(day)) days[day] = false; } std::string ValidityPattern::str() const { return days.to_string(); } bool ValidityPattern::check(boost::gregorian::date day) const { long duration = slide(day); return ValidityPattern::check(duration); } bool ValidityPattern::check(unsigned int day) const { // BOOST_ASSERT(is_valid(day)); return days[day]; } bool ValidityPattern::check2(unsigned int day) const { // BOOST_ASSERT(is_valid(day)); if(day == 0) return days[day] || days[day+1]; else return days[day-1] || days[day] || days[day+1]; } bool ValidityPattern::uncheck2(unsigned int day) const { // BOOST_ASSERT(is_valid(day)); if(day == 0) return !days[day] && !days[day+1]; else return !days[day-1] && !days[day] && !days[day+1]; } double GeographicalCoord::distance_to(const GeographicalCoord &other) const{ static const double EARTH_RADIUS_IN_METERS = 6372797.560856; double longitudeArc = (this->lon() - other.lon()) * DEG_TO_RAD; double latitudeArc = (this->lat() - other.lat()) * DEG_TO_RAD; double latitudeH = sin(latitudeArc * 0.5); latitudeH *= latitudeH; double lontitudeH = sin(longitudeArc * 0.5); lontitudeH *= lontitudeH; double tmp = cos(this->lat()*DEG_TO_RAD) * cos(other.lat()*DEG_TO_RAD); return EARTH_RADIUS_IN_METERS * 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH)); } bool operator==(const GeographicalCoord & a, const GeographicalCoord & b){ return a.distance_to(b) < 0.1; // soit 0.1m } std::pair<GeographicalCoord, float> GeographicalCoord::project(GeographicalCoord segment_start, GeographicalCoord segment_end) const{ std::pair<GeographicalCoord, float> result; double dlon = segment_end._lon - segment_start._lon; double dlat = segment_end._lat - segment_start._lat; double length_sqr = dlon * dlon + dlat * dlat; double u; // On gère le cas où le segment est particulièrement court, et donc ça peut poser des problèmes (à cause de la division par length²) if(length_sqr < 1e-11){ // moins de un mètre, on projette sur une extrémité if(this->distance_to(segment_start) < this->distance_to(segment_end)) u = 0; else u = 1; } else { u = ((this->_lon - segment_start._lon)*dlon + (this->_lat - segment_start._lat)*dlat )/ length_sqr; } // Les deux cas où le projeté tombe en dehors if(u < 0) result = std::make_pair(segment_start, this->distance_to(segment_start)); else if(u > 1) result = std::make_pair(segment_end, this->distance_to(segment_end)); else { result.first._lon = segment_start._lon + u * (segment_end._lon - segment_start._lon); result.first._lat = segment_start._lat + u * (segment_end._lat - segment_start._lat); result.second = this->distance_to(result.first); } return result; } std::ostream & operator<<(std::ostream & os, const GeographicalCoord & coord){ os << coord.lon() << ";" << coord.lat(); return os; } static_data * static_data::instance = 0; static_data * static_data::get() { if (instance == 0) { static_data* temp = new static_data(); boost::assign::insert(temp->types_string) (Type_e::eValidityPattern, "validity_pattern") (Type_e::eLine, "line") (Type_e::eJourneyPattern, "journey_pattern") (Type_e::eVehicleJourney, "vehicle_journey") (Type_e::eStopPoint, "stop_point") (Type_e::eStopArea, "stop_area") (Type_e::eStopTime, "stop_time") (Type_e::eNetwork, "network") (Type_e::ePhysicalMode, "mode") (Type_e::eCommercialMode, "commercial_mode") (Type_e::eCity, "city") (Type_e::eConnection, "connection") (Type_e::eJourneyPatternPoint, "journey_pattern_point") (Type_e::eDistrict, "district") (Type_e::eDepartment, "department") (Type_e::eCompany, "company") (Type_e::eVehicle, "vehicle") (Type_e::eCountry, "country") (Type_e::eWay, "way") (Type_e::eCoord, "coord") (Type_e::eAddress, "address") (Type_e::eRoute, "route"); instance = temp; } return instance; } //std::string static_data::getListNameByType(Type_e type){ // return instance->types_string.left.at(type) + "_list"; //} Type_e static_data::typeByCaption(const std::string & type_str) { return instance->types_string.right.at(type_str); } std::string static_data::captionByType(Type_e type){ return instance->types_string.left.at(type); } std::vector<idx_t> Country::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eDistrict: return district_list; break; default: break; } return result; } std::vector<idx_t> City::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopArea: return stop_area_list; break; case Type_e::eDepartment: result.push_back(department_idx); break; default: break; } return result; } std::vector<idx_t> StopArea::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopPoint: return this->stop_point_list; break; case Type_e::eCity: result.push_back(city_idx); break; default: break; } return result; } std::vector<idx_t> Network::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: return line_list; break; default: break; } return result; } std::vector<idx_t> Company::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: return line_list; break; default: break; } return result; } std::vector<idx_t> CommercialMode::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: return line_list; break; case Type_e::ePhysicalMode: return physical_mode_list; break; default: break; } return result; } std::vector<idx_t> PhysicalMode::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eCommercialMode: result.push_back(commercial_mode_idx); break; default: break; } return result; } std::vector<idx_t> Line::get(Type_e type, const PT_Data&) const { std::vector<idx_t> result; switch(type) { case Type_e::eCommercialMode: result.push_back(commercial_mode_idx); break; case Type_e::ePhysicalMode: return physical_mode_list; break; case Type_e::eCompany: return company_list; break; case Type_e::eNetwork: result.push_back(network_idx); break; case Type_e::eRoute: return route_list; break; default: break; } return result; } std::vector<idx_t> Route::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: result.push_back(line_idx); break; case Type_e::eJourneyPattern: return journey_pattern_list; break; default: break; } return result; } std::vector<idx_t> JourneyPattern::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eRoute: result.push_back(route_idx); break; case Type_e::eCommercialMode: result.push_back(commercial_mode_idx); break; case Type_e::eJourneyPatternPoint: return journey_pattern_point_list; break; case Type_e::eVehicleJourney: return vehicle_journey_list; break; default: break; } return result; } std::vector<idx_t> VehicleJourney::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eJourneyPattern: result.push_back(journey_pattern_idx); break; case Type_e::eCompany: result.push_back(company_idx); break; case Type_e::ePhysicalMode: result.push_back(physical_mode_idx); break; //case Type_e::eVehicle: result.push_back(vehicle_idx); break; case Type_e::eValidityPattern: result.push_back(validity_pattern_idx); break; default: break; } return result; } std::vector<idx_t> JourneyPatternPoint::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eJourneyPattern: result.push_back(journey_pattern_idx); break; case Type_e::eStopPoint: result.push_back(stop_point_idx); break; default: break; } return result; } std::vector<idx_t> StopPoint::get(Type_e type, const PT_Data & data) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopArea: result.push_back(stop_area_idx); break; case Type_e::eCity: result.push_back(city_idx); break; case Type_e::ePhysicalMode: result.push_back(physical_mode_idx); break; case Type_e::eNetwork: result.push_back(network_idx); break; case Type_e::eJourneyPatternPoint: return journey_pattern_point_list; break; case Type_e::eConnection: for(const Connection & conn : data.stop_point_connections[idx]) { result.push_back(conn.idx); } break; default: break; } return result; } std::vector<idx_t> Connection::get(Type_e type, const PT_Data & ) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopPoint: result.push_back(this->departure_stop_point_idx); result.push_back(this->destination_stop_point_idx); break; default: break; } return result; } EntryPoint::EntryPoint(const std::string &uri) : uri(uri) { size_t pos = uri.find(":"); if(pos == std::string::npos) type = Type_e::eUnknown; else { type = static_data::get()->typeByCaption(uri.substr(0,pos)); } // Gestion des adresses if (type == Type_e::eAddress){ std::vector<std::string> vect; vect = split_string(uri, ":"); if(vect.size() == 3){ this->uri = vect[0] + ":" + vect[1]; this->house_number = str_to_int(vect[2]); } } if(type == Type_e::eCoord){ size_t pos2 = uri.find(":", pos+1); try{ if(pos2 != std::string::npos) { this->coordinates.set_lon(boost::lexical_cast<double>(uri.substr(pos+1, pos2 - pos - 1))); this->coordinates.set_lat(boost::lexical_cast<double>(uri.substr(pos2+1))); } }catch(boost::bad_lexical_cast){ this->coordinates.set_lon(0); this->coordinates.set_lat(0); } } } }} //namespace navitia::type <commit_msg>Type : Il restait un mode<commit_after>#include "type.h" #include "pt_data.h" #include <iostream> #include <boost/assign.hpp> #include "utils/functions.h" namespace navitia { namespace type { bool ValidityPattern::is_valid(int duration) const { if(duration < 0){ std::cerr << "La date est avant le début de période(" << beginning_date << ")" << std::endl; return false; } else if(duration > 366){ std::cerr << "La date dépasse la fin de période " << duration << " " << std::endl; return false; } return true; } int ValidityPattern::slide(boost::gregorian::date day) const { return (day - beginning_date).days(); } void ValidityPattern::add(boost::gregorian::date day){ long duration = slide(day); add(duration); } void ValidityPattern::add(int duration){ if(is_valid(duration)) days[duration] = true; } void ValidityPattern::remove(boost::gregorian::date date){ long duration = slide(date); remove(duration); } void ValidityPattern::remove(int day){ if(is_valid(day)) days[day] = false; } std::string ValidityPattern::str() const { return days.to_string(); } bool ValidityPattern::check(boost::gregorian::date day) const { long duration = slide(day); return ValidityPattern::check(duration); } bool ValidityPattern::check(unsigned int day) const { // BOOST_ASSERT(is_valid(day)); return days[day]; } bool ValidityPattern::check2(unsigned int day) const { // BOOST_ASSERT(is_valid(day)); if(day == 0) return days[day] || days[day+1]; else return days[day-1] || days[day] || days[day+1]; } bool ValidityPattern::uncheck2(unsigned int day) const { // BOOST_ASSERT(is_valid(day)); if(day == 0) return !days[day] && !days[day+1]; else return !days[day-1] && !days[day] && !days[day+1]; } double GeographicalCoord::distance_to(const GeographicalCoord &other) const{ static const double EARTH_RADIUS_IN_METERS = 6372797.560856; double longitudeArc = (this->lon() - other.lon()) * DEG_TO_RAD; double latitudeArc = (this->lat() - other.lat()) * DEG_TO_RAD; double latitudeH = sin(latitudeArc * 0.5); latitudeH *= latitudeH; double lontitudeH = sin(longitudeArc * 0.5); lontitudeH *= lontitudeH; double tmp = cos(this->lat()*DEG_TO_RAD) * cos(other.lat()*DEG_TO_RAD); return EARTH_RADIUS_IN_METERS * 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH)); } bool operator==(const GeographicalCoord & a, const GeographicalCoord & b){ return a.distance_to(b) < 0.1; // soit 0.1m } std::pair<GeographicalCoord, float> GeographicalCoord::project(GeographicalCoord segment_start, GeographicalCoord segment_end) const{ std::pair<GeographicalCoord, float> result; double dlon = segment_end._lon - segment_start._lon; double dlat = segment_end._lat - segment_start._lat; double length_sqr = dlon * dlon + dlat * dlat; double u; // On gère le cas où le segment est particulièrement court, et donc ça peut poser des problèmes (à cause de la division par length²) if(length_sqr < 1e-11){ // moins de un mètre, on projette sur une extrémité if(this->distance_to(segment_start) < this->distance_to(segment_end)) u = 0; else u = 1; } else { u = ((this->_lon - segment_start._lon)*dlon + (this->_lat - segment_start._lat)*dlat )/ length_sqr; } // Les deux cas où le projeté tombe en dehors if(u < 0) result = std::make_pair(segment_start, this->distance_to(segment_start)); else if(u > 1) result = std::make_pair(segment_end, this->distance_to(segment_end)); else { result.first._lon = segment_start._lon + u * (segment_end._lon - segment_start._lon); result.first._lat = segment_start._lat + u * (segment_end._lat - segment_start._lat); result.second = this->distance_to(result.first); } return result; } std::ostream & operator<<(std::ostream & os, const GeographicalCoord & coord){ os << coord.lon() << ";" << coord.lat(); return os; } static_data * static_data::instance = 0; static_data * static_data::get() { if (instance == 0) { static_data* temp = new static_data(); boost::assign::insert(temp->types_string) (Type_e::eValidityPattern, "validity_pattern") (Type_e::eLine, "line") (Type_e::eJourneyPattern, "journey_pattern") (Type_e::eVehicleJourney, "vehicle_journey") (Type_e::eStopPoint, "stop_point") (Type_e::eStopArea, "stop_area") (Type_e::eStopTime, "stop_time") (Type_e::eNetwork, "network") (Type_e::ePhysicalMode, "physical_mode") (Type_e::eCommercialMode, "commercial_mode") (Type_e::eCity, "city") (Type_e::eConnection, "connection") (Type_e::eJourneyPatternPoint, "journey_pattern_point") (Type_e::eDistrict, "district") (Type_e::eDepartment, "department") (Type_e::eCompany, "company") (Type_e::eVehicle, "vehicle") (Type_e::eCountry, "country") (Type_e::eWay, "way") (Type_e::eCoord, "coord") (Type_e::eAddress, "address") (Type_e::eRoute, "route"); instance = temp; } return instance; } //std::string static_data::getListNameByType(Type_e type){ // return instance->types_string.left.at(type) + "_list"; //} Type_e static_data::typeByCaption(const std::string & type_str) { return instance->types_string.right.at(type_str); } std::string static_data::captionByType(Type_e type){ return instance->types_string.left.at(type); } std::vector<idx_t> Country::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eDistrict: return district_list; break; default: break; } return result; } std::vector<idx_t> City::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopArea: return stop_area_list; break; case Type_e::eDepartment: result.push_back(department_idx); break; default: break; } return result; } std::vector<idx_t> StopArea::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopPoint: return this->stop_point_list; break; case Type_e::eCity: result.push_back(city_idx); break; default: break; } return result; } std::vector<idx_t> Network::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: return line_list; break; default: break; } return result; } std::vector<idx_t> Company::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: return line_list; break; default: break; } return result; } std::vector<idx_t> CommercialMode::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: return line_list; break; case Type_e::ePhysicalMode: return physical_mode_list; break; default: break; } return result; } std::vector<idx_t> PhysicalMode::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eCommercialMode: result.push_back(commercial_mode_idx); break; default: break; } return result; } std::vector<idx_t> Line::get(Type_e type, const PT_Data&) const { std::vector<idx_t> result; switch(type) { case Type_e::eCommercialMode: result.push_back(commercial_mode_idx); break; case Type_e::ePhysicalMode: return physical_mode_list; break; case Type_e::eCompany: return company_list; break; case Type_e::eNetwork: result.push_back(network_idx); break; case Type_e::eRoute: return route_list; break; default: break; } return result; } std::vector<idx_t> Route::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eLine: result.push_back(line_idx); break; case Type_e::eJourneyPattern: return journey_pattern_list; break; default: break; } return result; } std::vector<idx_t> JourneyPattern::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eRoute: result.push_back(route_idx); break; case Type_e::eCommercialMode: result.push_back(commercial_mode_idx); break; case Type_e::eJourneyPatternPoint: return journey_pattern_point_list; break; case Type_e::eVehicleJourney: return vehicle_journey_list; break; default: break; } return result; } std::vector<idx_t> VehicleJourney::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eJourneyPattern: result.push_back(journey_pattern_idx); break; case Type_e::eCompany: result.push_back(company_idx); break; case Type_e::ePhysicalMode: result.push_back(physical_mode_idx); break; //case Type_e::eVehicle: result.push_back(vehicle_idx); break; case Type_e::eValidityPattern: result.push_back(validity_pattern_idx); break; default: break; } return result; } std::vector<idx_t> JourneyPatternPoint::get(Type_e type, const PT_Data &) const { std::vector<idx_t> result; switch(type) { case Type_e::eJourneyPattern: result.push_back(journey_pattern_idx); break; case Type_e::eStopPoint: result.push_back(stop_point_idx); break; default: break; } return result; } std::vector<idx_t> StopPoint::get(Type_e type, const PT_Data & data) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopArea: result.push_back(stop_area_idx); break; case Type_e::eCity: result.push_back(city_idx); break; case Type_e::ePhysicalMode: result.push_back(physical_mode_idx); break; case Type_e::eNetwork: result.push_back(network_idx); break; case Type_e::eJourneyPatternPoint: return journey_pattern_point_list; break; case Type_e::eConnection: for(const Connection & conn : data.stop_point_connections[idx]) { result.push_back(conn.idx); } break; default: break; } return result; } std::vector<idx_t> Connection::get(Type_e type, const PT_Data & ) const { std::vector<idx_t> result; switch(type) { case Type_e::eStopPoint: result.push_back(this->departure_stop_point_idx); result.push_back(this->destination_stop_point_idx); break; default: break; } return result; } EntryPoint::EntryPoint(const std::string &uri) : uri(uri) { size_t pos = uri.find(":"); if(pos == std::string::npos) type = Type_e::eUnknown; else { type = static_data::get()->typeByCaption(uri.substr(0,pos)); } // Gestion des adresses if (type == Type_e::eAddress){ std::vector<std::string> vect; vect = split_string(uri, ":"); if(vect.size() == 3){ this->uri = vect[0] + ":" + vect[1]; this->house_number = str_to_int(vect[2]); } } if(type == Type_e::eCoord){ size_t pos2 = uri.find(":", pos+1); try{ if(pos2 != std::string::npos) { this->coordinates.set_lon(boost::lexical_cast<double>(uri.substr(pos+1, pos2 - pos - 1))); this->coordinates.set_lat(boost::lexical_cast<double>(uri.substr(pos2+1))); } }catch(boost::bad_lexical_cast){ this->coordinates.set_lon(0); this->coordinates.set_lat(0); } } } }} //namespace navitia::type <|endoftext|>
<commit_before>// // Created by jamie on 7/16/17. // #ifndef ARRAY_ARRAY_HPP #define ARRAY_ARRAY_HPP #include <type_traits> #include <vector> #include <numeric> #include <memory> #include <sstream> #include <deque> #include <algorithm> #include <random> namespace nd { enum class value_t : uint8_t { null, scalar, array, }; template<class T> class array { using this_type = array<T>; using reference = array &; using const_reference = const array &; using shape_t = std::deque<unsigned long>; using strides_t = std::vector<unsigned long>; using vector_t = std::vector<T>; ////////////////////// // friend operators // ////////////////////// friend std::ostream &operator<<(std::ostream &os, const array<T> &ar) { return os << ar.dump(); } public: union array_value { T scalar; vector_t *values; array_value() = default; array_value(T sc) : scalar(sc) {} array_value(const vector_t &vec) { values = __create_vector(vec); } }; ////////////////// // constructors // ////////////////// array(const this_type &other, unsigned long offset = 0) : m_type(other.m_type), m_shape(other.m_shape), m_strides(other.m_strides), m_base(nullptr), m_offset(offset) { if (m_type == value_t::array) m_value = *other.m_value.values; else m_value = other.m_value.scalar; } array(T &&val, this_type *base_from = nullptr, unsigned long offset = 0) : m_base(base_from), m_type(value_t::scalar), m_offset(offset) { static_assert(std::is_arithmetic<T>::value, "incompatible element type"); m_value.scalar = std::forward<T>(val); m_shape = {1}; } array(std::initializer_list<array> list) : m_type(value_t::array), m_base(nullptr) { // type becomes array, so make vector active in the union m_value.values = __create_vector(vector_t()); m_shape.emplace_front(list.size()); for (auto &val : list) { if (val.m_type == value_t::scalar) { // construct individual elements form list m_value.values->push_back(val.m_value.scalar); __set_strides(m_shape); } else { // add values to the actual object m_value.values->insert(std::end(*m_value.values), std::begin(val.data()), std::end(val.data())); m_shape = val.shape(); m_shape.emplace_front(list.size()); __set_strides(m_shape); } } } array(vector_t data, const shape_t &shape, this_type *base_from = nullptr, unsigned long offset = 0) : m_shape(shape), m_base(base_from), m_offset(offset) { m_type = value_t::array; m_value.values = __create_vector(data.begin(), data.end()); __set_strides(shape); } array(const shape_t &shape, T init, bool random) : m_shape(shape), m_type(value_t::array) { auto size = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<unsigned long>()); m_value.values = __create_vector(vector_t(size, init)); if(random) { std::random_device rd; std::mt19937 rng(rd()); std::uniform_real_distribution<double> uni(-1, 1); for(auto &val : *m_value.values) { val = uni(rng); } } __set_strides(m_shape); } ~array() { if (m_type == value_t::array) { delete m_value.values; } } reference &operator=(array other) { swap(other); return *this; } ///////////////////// // object accesors // ///////////////////// std::string dump() const { std::stringstream result; if (m_type == value_t::scalar) { result << m_value.scalar; } else if (m_shape.size() == 1) { if (m_base == nullptr) result << "[ "; else result << " [ "; for (const auto &val : *m_value.values) { result << " " << val << " "; } result << " ]"; } else if(m_shape.size() == 2) { for (int i = 0; i < rows(); ++i) { result << at(i).dump() << "\n"; } } else { result << "[\n"; for (int i = 0; i < rows(); ++i) { result << at(i).dump() << "\n"; } result << "]"; } return result.str(); } const vector_t &data() const { if (m_type != value_t::array) throw std::runtime_error("current value is not an array"); return *m_value.values; } T &item(const shape_t &indexes) const { if (indexes.size() != m_shape.size()) throw std::invalid_argument("requested shape size is not equal with the current shape size"); if (m_type == value_t::scalar) throw std::invalid_argument("type is already is a scalar"); // calculate offset int offset = {}; for(int i = 0; i < m_shape.size(); ++i) { offset += indexes[i] * m_strides[i]; } if (offset > m_value.values->size()) throw std::range_error("requested index is out of range(" + std::to_string(m_value.values->size()) + ")"); return m_value.values->at(offset); } bool is_scalar() const { return m_type == value_t::scalar; } bool is_array() const { return m_type == value_t::array; } unsigned long rows() const { return m_shape.at(0); } unsigned long columns() const { if (m_shape.size() == 2) return m_shape.at(1); /// TBD return 0; } const shape_t &shape() const { return m_shape; } unsigned long offset() const { return m_offset; } unsigned long size() { return m_value.values->size(); } unsigned long ndim() const { return m_shape.size(); } value_t type() const { return m_type; } const this_type *base() const { return m_base; } this_type at(unsigned long index) const { if (index > m_shape.at(0) - 1 || m_type == value_t::scalar) throw std::range_error("no value at index " + std::to_string(index)); this_type *from_base = m_base; if (m_base == nullptr) { from_base = const_cast<this_type *>(this); } // is a 1 dim array, get scalar if (m_shape.size() == 1) { return this_type(std::move(m_value.values->at(index)), from_base, m_offset + index); } auto first = m_value.values->begin() + (index * m_strides.at(0)); auto second = m_value.values->begin() + ((index + 1) * m_strides.at(0)); vector_t new_data(first, second); return this_type(new_data, std::deque<unsigned long>(m_shape.begin() + 1, m_shape.end()), from_base, std::distance(m_value.values->begin(), first) + m_offset); } this_type operator[](unsigned long index) const { return at(index); } //////////////// // modifiers // //////////////// void set_data(T val, unsigned long offset = 0) { if (m_type == value_t::scalar) m_value.scalar = val; else m_value.values->at(offset) = val; } void swap(reference other) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); std::swap(m_shape, other.m_shape); std::swap(m_strides, other.m_strides); } void set_shape(const shape_t &shape) { auto pd = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<unsigned long>()); if (pd != m_value.values->size()) throw std::invalid_argument("total size of new array must be unchanged when setting a new shape"); else m_shape = shape; __set_strides(m_shape); } void unary_expr(T(*callback)(T)) { if (m_type == value_t::array) { for (auto &val : *m_value.values) { val = callback(val); } } else { m_value.scalar = callback(m_value.scalar); } } const this_type &operator=(T val) { if (m_type != value_t::scalar) throw std::invalid_argument("can't assign number, current type is array"); if (m_base == nullptr) { m_value.scalar = val; return *this; } else { m_base->set_data(val, m_offset); return *m_base; } } private: value_t m_type = value_t::null; array_value m_value = {}; shape_t m_shape; strides_t m_strides; this_type *m_base; unsigned long m_offset = {}; // private setters void __set_strides(const shape_t &shape) { m_strides = std::vector<unsigned long>(m_shape.size()); m_strides.back() = 1; for (int i = (int) (m_shape.size() - 2); i >= 0; --i) { m_strides.at(i) = (unsigned long) std::accumulate(shape.begin() + i + 1, shape.end(), 1, std::multiplies<unsigned long>()); } } static vector_t *__create_vector(const vector_t &vec) { return new vector_t(vec.begin(), vec.end()); } static vector_t * __create_vector(const typename vector_t::iterator &first, const typename vector_t::iterator &second) { return new vector_t(first, second); } }; } #endif //ARRAY_ARRAY_HPP <commit_msg>Update array.hpp<commit_after>MIT License Copyright (c) 2017 Jamie Cheng 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 ARRAY_ARRAY_HPP #define ARRAY_ARRAY_HPP #include <type_traits> #include <vector> #include <numeric> #include <memory> #include <sstream> #include <deque> #include <algorithm> #include <random> namespace nd { enum class value_t : uint8_t { null, scalar, array, }; template<class T> class array { using this_type = array<T>; using reference = array &; using const_reference = const array &; using shape_t = std::deque<unsigned long>; using strides_t = std::vector<unsigned long>; using vector_t = std::vector<T>; ////////////////////// // friend operators // ////////////////////// friend std::ostream &operator<<(std::ostream &os, const array<T> &ar) { return os << ar.dump(); } public: union array_value { T scalar; vector_t *values; array_value() = default; array_value(T sc) : scalar(sc) {} array_value(const vector_t &vec) { values = __create_vector(vec); } }; ////////////////// // constructors // ////////////////// array(const this_type &other, unsigned long offset = 0) : m_type(other.m_type), m_shape(other.m_shape), m_strides(other.m_strides), m_base(nullptr), m_offset(offset) { if (m_type == value_t::array) m_value = *other.m_value.values; else m_value = other.m_value.scalar; } array(T &&val, this_type *base_from = nullptr, unsigned long offset = 0) : m_base(base_from), m_type(value_t::scalar), m_offset(offset) { static_assert(std::is_arithmetic<T>::value, "incompatible element type"); m_value.scalar = std::forward<T>(val); m_shape = {1}; } array(std::initializer_list<array> list) : m_type(value_t::array), m_base(nullptr) { // type becomes array, so make vector active in the union m_value.values = __create_vector(vector_t()); m_shape.emplace_front(list.size()); for (auto &val : list) { if (val.m_type == value_t::scalar) { // construct individual elements form list m_value.values->push_back(val.m_value.scalar); __set_strides(m_shape); } else { // add values to the actual object m_value.values->insert(std::end(*m_value.values), std::begin(val.data()), std::end(val.data())); m_shape = val.shape(); m_shape.emplace_front(list.size()); __set_strides(m_shape); } } } array(vector_t data, const shape_t &shape, this_type *base_from = nullptr, unsigned long offset = 0) : m_shape(shape), m_base(base_from), m_offset(offset) { m_type = value_t::array; m_value.values = __create_vector(data.begin(), data.end()); __set_strides(shape); } array(const shape_t &shape, T init, bool random) : m_shape(shape), m_type(value_t::array) { auto size = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<unsigned long>()); m_value.values = __create_vector(vector_t(size, init)); if(random) { std::random_device rd; std::mt19937 rng(rd()); std::uniform_real_distribution<double> uni(-1, 1); for(auto &val : *m_value.values) { val = uni(rng); } } __set_strides(m_shape); } ~array() { if (m_type == value_t::array) { delete m_value.values; } } reference &operator=(array other) { swap(other); return *this; } ///////////////////// // object accesors // ///////////////////// std::string dump() const { std::stringstream result; if (m_type == value_t::scalar) { result << m_value.scalar; } else if (m_shape.size() == 1) { if (m_base == nullptr) result << "[ "; else result << " [ "; for (const auto &val : *m_value.values) { result << " " << val << " "; } result << " ]"; } else if(m_shape.size() == 2) { for (int i = 0; i < rows(); ++i) { result << at(i).dump() << "\n"; } } else { result << "[\n"; for (int i = 0; i < rows(); ++i) { result << at(i).dump() << "\n"; } result << "]"; } return result.str(); } const vector_t &data() const { if (m_type != value_t::array) throw std::runtime_error("current value is not an array"); return *m_value.values; } T &item(const shape_t &indexes) const { if (indexes.size() != m_shape.size()) throw std::invalid_argument("requested shape size is not equal with the current shape size"); if (m_type == value_t::scalar) throw std::invalid_argument("type is already is a scalar"); // calculate offset int offset = {}; for(int i = 0; i < m_shape.size(); ++i) { offset += indexes[i] * m_strides[i]; } if (offset > m_value.values->size()) throw std::range_error("requested index is out of range(" + std::to_string(m_value.values->size()) + ")"); return m_value.values->at(offset); } bool is_scalar() const { return m_type == value_t::scalar; } bool is_array() const { return m_type == value_t::array; } unsigned long rows() const { return m_shape.at(0); } unsigned long columns() const { if (m_shape.size() == 2) return m_shape.at(1); /// TBD return 0; } const shape_t &shape() const { return m_shape; } unsigned long offset() const { return m_offset; } unsigned long size() { return m_value.values->size(); } unsigned long ndim() const { return m_shape.size(); } value_t type() const { return m_type; } const this_type *base() const { return m_base; } this_type at(unsigned long index) const { if (index > m_shape.at(0) - 1 || m_type == value_t::scalar) throw std::range_error("no value at index " + std::to_string(index)); this_type *from_base = m_base; if (m_base == nullptr) { from_base = const_cast<this_type *>(this); } // is a 1 dim array, get scalar if (m_shape.size() == 1) { return this_type(std::move(m_value.values->at(index)), from_base, m_offset + index); } auto first = m_value.values->begin() + (index * m_strides.at(0)); auto second = m_value.values->begin() + ((index + 1) * m_strides.at(0)); vector_t new_data(first, second); return this_type(new_data, std::deque<unsigned long>(m_shape.begin() + 1, m_shape.end()), from_base, std::distance(m_value.values->begin(), first) + m_offset); } this_type operator[](unsigned long index) const { return at(index); } //////////////// // modifiers // //////////////// void set_data(T val, unsigned long offset = 0) { if (m_type == value_t::scalar) m_value.scalar = val; else m_value.values->at(offset) = val; } void swap(reference other) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); std::swap(m_shape, other.m_shape); std::swap(m_strides, other.m_strides); } void set_shape(const shape_t &shape) { auto pd = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<unsigned long>()); if (pd != m_value.values->size()) throw std::invalid_argument("total size of new array must be unchanged when setting a new shape"); else m_shape = shape; __set_strides(m_shape); } void unary_expr(T(*callback)(T)) { if (m_type == value_t::array) { for (auto &val : *m_value.values) { val = callback(val); } } else { m_value.scalar = callback(m_value.scalar); } } const this_type &operator=(T val) { if (m_type != value_t::scalar) throw std::invalid_argument("can't assign number, current type is array"); if (m_base == nullptr) { m_value.scalar = val; return *this; } else { m_base->set_data(val, m_offset); return *m_base; } } private: value_t m_type = value_t::null; array_value m_value = {}; shape_t m_shape; strides_t m_strides; this_type *m_base; unsigned long m_offset = {}; // private setters void __set_strides(const shape_t &shape) { m_strides = std::vector<unsigned long>(m_shape.size()); m_strides.back() = 1; for (int i = (int) (m_shape.size() - 2); i >= 0; --i) { m_strides.at(i) = (unsigned long) std::accumulate(shape.begin() + i + 1, shape.end(), 1, std::multiplies<unsigned long>()); } } static vector_t *__create_vector(const vector_t &vec) { return new vector_t(vec.begin(), vec.end()); } static vector_t * __create_vector(const typename vector_t::iterator &first, const typename vector_t::iterator &second) { return new vector_t(first, second); } }; } #endif //ARRAY_ARRAY_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLIndexAlphabeticalSourceContext.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-07-26 08:15:26 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_XMLINDEXALPHABETICALSOURCECONTEXT_HXX_ #include "XMLIndexAlphabeticalSourceContext.hxx" #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_ #include "XMLIndexTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_ #include "XMLIndexTitleTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTOCSTYLESCONTEXT_HXX_ #include "XMLIndexTOCStylesContext.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_TEXTIMP_HXX_ #include <xmloff/txtimp.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif using ::rtl::OUString; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_ALPHABETICAL_INDEX_ENTRY_TEMPLATE; using ::xmloff::token::XML_OUTLINE_LEVEL; const sal_Char sAPI_MainEntryCharacterStyleName[] = "MainEntryCharacterStyleName"; const sal_Char sAPI_UseAlphabeticalSeparators[] = "UseAlphabeticalSeparators"; const sal_Char sAPI_UseCombinedEntries[] = "UseCombinedEntries"; const sal_Char sAPI_IsCaseSensitive[] = "IsCaseSensitive"; const sal_Char sAPI_UseKeyAsEntry[] = "UseKeyAsEntry"; const sal_Char sAPI_UseUpperCase[] = "UseUpperCase"; const sal_Char sAPI_UseDash[] = "UseDash"; const sal_Char sAPI_UsePP[] = "UsePP"; const sal_Char sAPI_SortAlgorithm[] = "SortAlgorithm"; const sal_Char sAPI_Locale[] = "Locale"; TYPEINIT1( XMLIndexAlphabeticalSourceContext, XMLIndexSourceBaseContext ); XMLIndexAlphabeticalSourceContext::XMLIndexAlphabeticalSourceContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, Reference<XPropertySet> & rPropSet) : XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName, rPropSet, sal_False) , sMainEntryCharacterStyleName(RTL_CONSTASCII_USTRINGPARAM(sAPI_MainEntryCharacterStyleName)) , sUseAlphabeticalSeparators(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseAlphabeticalSeparators)) , sUseCombinedEntries(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseCombinedEntries)) , sIsCaseSensitive(RTL_CONSTASCII_USTRINGPARAM(sAPI_IsCaseSensitive)) , sUseKeyAsEntry(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseKeyAsEntry)) , sUseUpperCase(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseUpperCase)) , sUseDash(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseDash)) , sUsePP(RTL_CONSTASCII_USTRINGPARAM(sAPI_UsePP)) , sIsCommaSeparated(RTL_CONSTASCII_USTRINGPARAM("IsCommaSeparated")) , sSortAlgorithm(RTL_CONSTASCII_USTRINGPARAM(sAPI_SortAlgorithm)) , sLocale(RTL_CONSTASCII_USTRINGPARAM(sAPI_Locale)) , bMainEntryStyleNameOK(sal_False) , bSeparators(sal_False) , bCombineEntries(sal_True) , bCaseSensitive(sal_True) , bEntry(sal_False) , bUpperCase(sal_False) , bCombineDash(sal_False) , bCombinePP(sal_True) , bCommaSeparated(sal_False) { } XMLIndexAlphabeticalSourceContext::~XMLIndexAlphabeticalSourceContext() { } void XMLIndexAlphabeticalSourceContext::ProcessAttribute( enum IndexSourceParamEnum eParam, const OUString& rValue) { sal_Bool bTmp; switch (eParam) { case XML_TOK_INDEXSOURCE_MAIN_ENTRY_STYLE: { sMainEntryStyleName = rValue; OUString sDisplayStyleName = GetImport().GetStyleDisplayName( XML_STYLE_FAMILY_TEXT_TEXT, sMainEntryStyleName ); const Reference < ::com::sun::star::container::XNameContainer >& rStyles = GetImport().GetTextImport()->GetTextStyles(); bMainEntryStyleNameOK = rStyles.is() && rStyles->hasByName( sDisplayStyleName ); } break; case XML_TOK_INDEXSOURCE_IGNORE_CASE: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCaseSensitive = !bTmp; } break; case XML_TOK_INDEXSOURCE_SEPARATORS: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bSeparators = bTmp; } break; case XML_TOK_INDEXSOURCE_COMBINE_ENTRIES: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCombineEntries = bTmp; } break; case XML_TOK_INDEXSOURCE_COMBINE_WITH_DASH: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCombineDash = bTmp; } break; case XML_TOK_INDEXSOURCE_KEYS_AS_ENTRIES: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bEntry = bTmp; } break; case XML_TOK_INDEXSOURCE_COMBINE_WITH_PP: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCombinePP = bTmp; } break; case XML_TOK_INDEXSOURCE_CAPITALIZE: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUpperCase = bTmp; } break; case XML_TOK_INDEXSOURCE_COMMA_SEPARATED: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCommaSeparated = bTmp; } break; case XML_TOK_INDEXSOURCE_SORT_ALGORITHM: sAlgorithm = rValue; break; case XML_TOK_INDEXSOURCE_LANGUAGE: aLocale.Language = rValue; break; case XML_TOK_INDEXSOURCE_COUNTRY: aLocale.Country = rValue; break; default: XMLIndexSourceBaseContext::ProcessAttribute(eParam, rValue); break; } } void XMLIndexAlphabeticalSourceContext::EndElement() { Any aAny; if (bMainEntryStyleNameOK) { aAny <<= GetImport().GetStyleDisplayName( XML_STYLE_FAMILY_TEXT_TEXT, sMainEntryStyleName ); rIndexPropertySet->setPropertyValue(sMainEntryCharacterStyleName,aAny); } aAny.setValue(&bSeparators, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseAlphabeticalSeparators, aAny); aAny.setValue(&bCombineEntries, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseCombinedEntries, aAny); aAny.setValue(&bCaseSensitive, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sIsCaseSensitive, aAny); aAny.setValue(&bEntry, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseKeyAsEntry, aAny); aAny.setValue(&bUpperCase, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseUpperCase, aAny); aAny.setValue(&bCombineDash, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseDash, aAny); aAny.setValue(&bCombinePP, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUsePP, aAny); aAny.setValue(&bCommaSeparated, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sIsCommaSeparated, aAny); if (sAlgorithm.getLength() > 0) { aAny <<= sAlgorithm; rIndexPropertySet->setPropertyValue(sSortAlgorithm, aAny); } if ( (aLocale.Language.getLength() > 0) && (aLocale.Country.getLength() > 0) ) { aAny <<= aLocale; rIndexPropertySet->setPropertyValue(sLocale, aAny); } XMLIndexSourceBaseContext::EndElement(); } SvXMLImportContext* XMLIndexAlphabeticalSourceContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { if ( (XML_NAMESPACE_TEXT == nPrefix) && IsXMLToken( rLocalName, XML_ALPHABETICAL_INDEX_ENTRY_TEMPLATE ) ) { return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName, aLevelNameAlphaMap, XML_OUTLINE_LEVEL, aLevelStylePropNameAlphaMap, aAllowedTokenTypesAlpha); } else { return XMLIndexSourceBaseContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } } <commit_msg>INTEGRATION: CWS changefileheader (1.10.138); FILE MERGED 2008/04/01 16:10:04 thb 1.10.138.3: #i85898# Stripping all external header guards 2008/04/01 13:05:23 thb 1.10.138.2: #i85898# Stripping all external header guards 2008/03/31 16:28:32 rt 1.10.138.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: XMLIndexAlphabeticalSourceContext.cxx,v $ * $Revision: 1.11 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include "XMLIndexAlphabeticalSourceContext.hxx" #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XIndexReplace.hpp> #include "XMLIndexTemplateContext.hxx" #include "XMLIndexTitleTemplateContext.hxx" #include "XMLIndexTOCStylesContext.hxx" #include <xmloff/xmlictxt.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/txtimp.hxx> #include "xmlnmspe.hxx" #include <xmloff/nmspmap.hxx> #include <xmloff/xmltoken.hxx> #include <xmloff/xmluconv.hxx> #include <tools/debug.hxx> #include <rtl/ustring.hxx> using ::rtl::OUString; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_ALPHABETICAL_INDEX_ENTRY_TEMPLATE; using ::xmloff::token::XML_OUTLINE_LEVEL; const sal_Char sAPI_MainEntryCharacterStyleName[] = "MainEntryCharacterStyleName"; const sal_Char sAPI_UseAlphabeticalSeparators[] = "UseAlphabeticalSeparators"; const sal_Char sAPI_UseCombinedEntries[] = "UseCombinedEntries"; const sal_Char sAPI_IsCaseSensitive[] = "IsCaseSensitive"; const sal_Char sAPI_UseKeyAsEntry[] = "UseKeyAsEntry"; const sal_Char sAPI_UseUpperCase[] = "UseUpperCase"; const sal_Char sAPI_UseDash[] = "UseDash"; const sal_Char sAPI_UsePP[] = "UsePP"; const sal_Char sAPI_SortAlgorithm[] = "SortAlgorithm"; const sal_Char sAPI_Locale[] = "Locale"; TYPEINIT1( XMLIndexAlphabeticalSourceContext, XMLIndexSourceBaseContext ); XMLIndexAlphabeticalSourceContext::XMLIndexAlphabeticalSourceContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, Reference<XPropertySet> & rPropSet) : XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName, rPropSet, sal_False) , sMainEntryCharacterStyleName(RTL_CONSTASCII_USTRINGPARAM(sAPI_MainEntryCharacterStyleName)) , sUseAlphabeticalSeparators(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseAlphabeticalSeparators)) , sUseCombinedEntries(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseCombinedEntries)) , sIsCaseSensitive(RTL_CONSTASCII_USTRINGPARAM(sAPI_IsCaseSensitive)) , sUseKeyAsEntry(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseKeyAsEntry)) , sUseUpperCase(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseUpperCase)) , sUseDash(RTL_CONSTASCII_USTRINGPARAM(sAPI_UseDash)) , sUsePP(RTL_CONSTASCII_USTRINGPARAM(sAPI_UsePP)) , sIsCommaSeparated(RTL_CONSTASCII_USTRINGPARAM("IsCommaSeparated")) , sSortAlgorithm(RTL_CONSTASCII_USTRINGPARAM(sAPI_SortAlgorithm)) , sLocale(RTL_CONSTASCII_USTRINGPARAM(sAPI_Locale)) , bMainEntryStyleNameOK(sal_False) , bSeparators(sal_False) , bCombineEntries(sal_True) , bCaseSensitive(sal_True) , bEntry(sal_False) , bUpperCase(sal_False) , bCombineDash(sal_False) , bCombinePP(sal_True) , bCommaSeparated(sal_False) { } XMLIndexAlphabeticalSourceContext::~XMLIndexAlphabeticalSourceContext() { } void XMLIndexAlphabeticalSourceContext::ProcessAttribute( enum IndexSourceParamEnum eParam, const OUString& rValue) { sal_Bool bTmp; switch (eParam) { case XML_TOK_INDEXSOURCE_MAIN_ENTRY_STYLE: { sMainEntryStyleName = rValue; OUString sDisplayStyleName = GetImport().GetStyleDisplayName( XML_STYLE_FAMILY_TEXT_TEXT, sMainEntryStyleName ); const Reference < ::com::sun::star::container::XNameContainer >& rStyles = GetImport().GetTextImport()->GetTextStyles(); bMainEntryStyleNameOK = rStyles.is() && rStyles->hasByName( sDisplayStyleName ); } break; case XML_TOK_INDEXSOURCE_IGNORE_CASE: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCaseSensitive = !bTmp; } break; case XML_TOK_INDEXSOURCE_SEPARATORS: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bSeparators = bTmp; } break; case XML_TOK_INDEXSOURCE_COMBINE_ENTRIES: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCombineEntries = bTmp; } break; case XML_TOK_INDEXSOURCE_COMBINE_WITH_DASH: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCombineDash = bTmp; } break; case XML_TOK_INDEXSOURCE_KEYS_AS_ENTRIES: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bEntry = bTmp; } break; case XML_TOK_INDEXSOURCE_COMBINE_WITH_PP: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCombinePP = bTmp; } break; case XML_TOK_INDEXSOURCE_CAPITALIZE: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUpperCase = bTmp; } break; case XML_TOK_INDEXSOURCE_COMMA_SEPARATED: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bCommaSeparated = bTmp; } break; case XML_TOK_INDEXSOURCE_SORT_ALGORITHM: sAlgorithm = rValue; break; case XML_TOK_INDEXSOURCE_LANGUAGE: aLocale.Language = rValue; break; case XML_TOK_INDEXSOURCE_COUNTRY: aLocale.Country = rValue; break; default: XMLIndexSourceBaseContext::ProcessAttribute(eParam, rValue); break; } } void XMLIndexAlphabeticalSourceContext::EndElement() { Any aAny; if (bMainEntryStyleNameOK) { aAny <<= GetImport().GetStyleDisplayName( XML_STYLE_FAMILY_TEXT_TEXT, sMainEntryStyleName ); rIndexPropertySet->setPropertyValue(sMainEntryCharacterStyleName,aAny); } aAny.setValue(&bSeparators, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseAlphabeticalSeparators, aAny); aAny.setValue(&bCombineEntries, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseCombinedEntries, aAny); aAny.setValue(&bCaseSensitive, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sIsCaseSensitive, aAny); aAny.setValue(&bEntry, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseKeyAsEntry, aAny); aAny.setValue(&bUpperCase, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseUpperCase, aAny); aAny.setValue(&bCombineDash, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUseDash, aAny); aAny.setValue(&bCombinePP, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sUsePP, aAny); aAny.setValue(&bCommaSeparated, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sIsCommaSeparated, aAny); if (sAlgorithm.getLength() > 0) { aAny <<= sAlgorithm; rIndexPropertySet->setPropertyValue(sSortAlgorithm, aAny); } if ( (aLocale.Language.getLength() > 0) && (aLocale.Country.getLength() > 0) ) { aAny <<= aLocale; rIndexPropertySet->setPropertyValue(sLocale, aAny); } XMLIndexSourceBaseContext::EndElement(); } SvXMLImportContext* XMLIndexAlphabeticalSourceContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { if ( (XML_NAMESPACE_TEXT == nPrefix) && IsXMLToken( rLocalName, XML_ALPHABETICAL_INDEX_ENTRY_TEMPLATE ) ) { return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName, aLevelNameAlphaMap, XML_OUTLINE_LEVEL, aLevelStylePropNameAlphaMap, aAllowedTokenTypesAlpha); } else { return XMLIndexSourceBaseContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } } <|endoftext|>
<commit_before>/***************objectmarker.cpp****************** Object marker for creating a list of ROIs to use for (e.g.) OpenCV cascade training. Requires OpenCV, and various common C/C++ libraries. author: [email protected] originally based on objectmarker.cpp by: [email protected] */ #include <opencv/cv.h> #include <opencv/cvaux.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdio.h> #include <sys/uio.h> #include <string> #include <fstream> #include <sstream> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> using namespace cv; using namespace std; Mat image; Mat image2; Mat image3; int max_height = 800; float scale_factor = 1; int roi_x0=0; int roi_y0=0; int roi_x1=0; int roi_y1=0; int numOfRec=0; int startDraw = 0; int aspect_x = 1; int aspect_y = 1; int mod_x = 0; int mod_y = 0; string window_name=""; void on_mouse(int event,int x,int y,int flag, void *param) { if ( event == CV_EVENT_LBUTTONDOWN ) { if ( !startDraw ) { roi_x0=x; roi_y0=y; startDraw = 1; } else { roi_x1=x; roi_y1=y; // enforce ROI aspect ratio if ( ( (roi_x0 > x) && (roi_y0 > y) ) || ( (roi_x0 < x) && (roi_y0 < y) ) ) roi_x1 = roi_x0 + ( aspect_x * ( roi_y1 - roi_y0 ) / aspect_y ); else roi_x1 = roi_x0 + ( aspect_x * ( roi_y0 - roi_y1 ) / aspect_y ); // redraw ROI selection in green when finished image2 = image3.clone(); rectangle( image2, cvPoint( roi_x0, roi_y0 ), cvPoint( roi_x1, roi_y1 ), CV_RGB(50,255,50), 1 ); imshow( window_name, image2 ); startDraw = 0; } } if ( event == CV_EVENT_MOUSEMOVE && startDraw ) { mod_x = x; mod_y = y; // enforce ROI aspect ratio if ( ( (roi_x0 > x) && (roi_y0 > y) ) || ( (roi_x0 < x) && (roi_y0 < y) ) ) mod_x = roi_x0 + ( aspect_x * ( mod_y - roi_y0 ) / aspect_y ); else mod_x = roi_x0 + ( aspect_x * ( roi_y0 - mod_y ) / aspect_y ); //redraw ROI selection image2 = image3.clone(); rectangle(image2,cvPoint( roi_x0, roi_y0 ),cvPoint( mod_x, mod_y ),CV_RGB(255,0,100),1); imshow(window_name,image2); } } int main(int argc, char** argv) { char iKey=0; string strPrefix; string strPostfix; string fullPath; string destPath; string input_directory = "."; string pos_directory = "marked"; string neg_directory = "negative"; string positive_file = "pos.txt"; string negative_file = "neg.txt"; struct stat filestat; int c; while (optind < argc) { if ((c = getopt(argc, argv, "m:u:p:n:h:x:y:")) != -1) switch (c) { case 'm': pos_directory = optarg; break; case 'u': neg_directory = optarg; break; case 'p': positive_file = optarg; break; case 'n': negative_file = optarg; break; case 'h': max_height = std::stoi(optarg); break; case 'x': aspect_x = std::stoi(optarg); break; case 'y': aspect_y = std::stoi(optarg); break; case '?': if (optopt == 'd' || optopt == 'p' || optopt == 'n') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } else { input_directory = argv[optind]; optind++; } } pos_directory = input_directory + "/" + pos_directory; neg_directory = input_directory + "/" + neg_directory; positive_file = pos_directory + "/" + positive_file; negative_file = neg_directory + "/" + negative_file; /* Create output directories if necessary */ DIR *dir_d = opendir( pos_directory.c_str()); if ( dir_d == NULL ) { mkdir( pos_directory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_d); } DIR *dir_e = opendir( neg_directory.c_str()); if ( dir_e == NULL ) { mkdir( neg_directory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_e); } // Open input directory DIR *dir_p = opendir( input_directory.c_str() ); struct dirent *dir_entry_p; if(dir_p == NULL) { fprintf(stderr, "Failed to open directory %s\n", input_directory.c_str()); return -1; } // GUI window_name = "ROI Marking"; namedWindow(window_name,1); setMouseCallback(window_name,on_mouse, NULL); // init output streams ofstream positives(positive_file.c_str(), std::ofstream::out | std::ofstream::app); ofstream negatives(negative_file.c_str(), std::ofstream::out | std::ofstream::app); // Iterate over directory while((dir_entry_p = readdir(dir_p)) != NULL) { // Skip directories string relPath = input_directory + "/" + dir_entry_p->d_name; if ( stat( relPath.c_str(), &filestat ) == -1 ) continue; if (S_ISDIR( filestat.st_mode )) continue; strPostfix=""; numOfRec=0; if(strcmp(dir_entry_p->d_name, "")) fprintf(stderr, "Examining file %s\n", dir_entry_p->d_name); strPrefix = dir_entry_p->d_name; fullPath = input_directory + "/" + strPrefix; printf("Loading image %s\n", strPrefix.c_str()); image = imread(fullPath.c_str(),1); if(! image.data ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; continue; } do { // Use scratch version of image for display, scaling down if necessary. Size sz = image.size(); if ( sz.height > max_height ) { if (sz.width > sz.height) { scale_factor = (float)max_height / (float)sz.width; } else { scale_factor = (float)max_height / (float)sz.height; } resize(image, image3, Size(), scale_factor, scale_factor, INTER_AREA); } else { image3 = image.clone(); } imshow(window_name,image3); // Start taking input iKey=cvWaitKey(0); switch(iKey) { case 27: image.release(); image2.release(); image3.release(); destroyWindow(window_name); closedir(dir_p); return 0; case 32: numOfRec++; #ifdef DEBUG printf(" %d. rect x=%d\ty=%d\tx2h=%d\ty2=%d\n",numOfRec,roi_x0,roi_y0,roi_x1,roi_y1); #endif strPostfix += " " + to_string( int( min(roi_x0,roi_x1) / scale_factor ) ) + " " + to_string( int( min(roi_y0,roi_y1) / scale_factor ) ) + " " + to_string( int( ( abs(roi_x1 - roi_x0) ) / scale_factor ) ) + " " + to_string( int( ( abs(roi_y1 - roi_y0) ) / scale_factor ) ); break; } } while(iKey!=97); if (iKey==97) { if (numOfRec > 0) { positives << strPrefix << " "<< numOfRec << strPostfix <<"\n"; destPath = pos_directory + "/" + strPrefix; } else { negatives << strPrefix << "\n"; destPath = neg_directory + "/" + strPrefix; } } rename( fullPath.c_str(), destPath.c_str() ); } image.release(); image2.release(); image3.release(); destroyWindow(window_name); closedir(dir_p); return 0; } <commit_msg>Fix scaling factor bug.<commit_after>/***************objectmarker.cpp****************** Object marker for creating a list of ROIs to use for (e.g.) OpenCV cascade training. Requires OpenCV, and various common C/C++ libraries. author: [email protected] originally based on objectmarker.cpp by: [email protected] */ #include <opencv/cv.h> #include <opencv/cvaux.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdio.h> #include <sys/uio.h> #include <string> #include <fstream> #include <sstream> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> using namespace cv; using namespace std; Mat image; Mat image2; Mat image3; int max_height = 800; float scale_factor = 1; int roi_x0=0; int roi_y0=0; int roi_x1=0; int roi_y1=0; int numOfRec=0; int startDraw = 0; int aspect_x = 1; int aspect_y = 1; int mod_x = 0; int mod_y = 0; string window_name=""; void on_mouse(int event,int x,int y,int flag, void *param) { if ( event == CV_EVENT_LBUTTONDOWN ) { if ( !startDraw ) { roi_x0=x; roi_y0=y; startDraw = 1; } else { roi_x1=x; roi_y1=y; // enforce ROI aspect ratio if ( ( (roi_x0 > x) && (roi_y0 > y) ) || ( (roi_x0 < x) && (roi_y0 < y) ) ) roi_x1 = roi_x0 + ( aspect_x * ( roi_y1 - roi_y0 ) / aspect_y ); else roi_x1 = roi_x0 + ( aspect_x * ( roi_y0 - roi_y1 ) / aspect_y ); // redraw ROI selection in green when finished image2 = image3.clone(); rectangle( image2, cvPoint( roi_x0, roi_y0 ), cvPoint( roi_x1, roi_y1 ), CV_RGB(50,255,50), 1 ); imshow( window_name, image2 ); startDraw = 0; } } if ( event == CV_EVENT_MOUSEMOVE && startDraw ) { mod_x = x; mod_y = y; // enforce ROI aspect ratio if ( ( (roi_x0 > x) && (roi_y0 > y) ) || ( (roi_x0 < x) && (roi_y0 < y) ) ) mod_x = roi_x0 + ( aspect_x * ( mod_y - roi_y0 ) / aspect_y ); else mod_x = roi_x0 + ( aspect_x * ( roi_y0 - mod_y ) / aspect_y ); //redraw ROI selection image2 = image3.clone(); rectangle(image2,cvPoint( roi_x0, roi_y0 ),cvPoint( mod_x, mod_y ),CV_RGB(255,0,100),1); imshow(window_name,image2); } } int main(int argc, char** argv) { char iKey=0; string strPrefix; string strPostfix; string fullPath; string destPath; string input_directory = "."; string pos_directory = "marked"; string neg_directory = "negative"; string positive_file = "pos.txt"; string negative_file = "neg.txt"; struct stat filestat; int c; while (optind < argc) { if ((c = getopt(argc, argv, "m:u:p:n:h:x:y:")) != -1) switch (c) { case 'm': pos_directory = optarg; break; case 'u': neg_directory = optarg; break; case 'p': positive_file = optarg; break; case 'n': negative_file = optarg; break; case 'h': max_height = std::stoi(optarg); break; case 'x': aspect_x = std::stoi(optarg); break; case 'y': aspect_y = std::stoi(optarg); break; case '?': if (optopt == 'd' || optopt == 'p' || optopt == 'n') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } else { input_directory = argv[optind]; optind++; } } pos_directory = input_directory + "/" + pos_directory; neg_directory = input_directory + "/" + neg_directory; positive_file = pos_directory + "/" + positive_file; negative_file = neg_directory + "/" + negative_file; /* Create output directories if necessary */ DIR *dir_d = opendir( pos_directory.c_str()); if ( dir_d == NULL ) { mkdir( pos_directory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_d); } DIR *dir_e = opendir( neg_directory.c_str()); if ( dir_e == NULL ) { mkdir( neg_directory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_e); } // Open input directory DIR *dir_p = opendir( input_directory.c_str() ); struct dirent *dir_entry_p; if(dir_p == NULL) { fprintf(stderr, "Failed to open directory %s\n", input_directory.c_str()); return -1; } // GUI window_name = "ROI Marking"; namedWindow(window_name,1); setMouseCallback(window_name,on_mouse, NULL); // init output streams ofstream positives(positive_file.c_str(), std::ofstream::out | std::ofstream::app); ofstream negatives(negative_file.c_str(), std::ofstream::out | std::ofstream::app); // Iterate over directory while((dir_entry_p = readdir(dir_p)) != NULL) { // Skip directories string relPath = input_directory + "/" + dir_entry_p->d_name; if ( stat( relPath.c_str(), &filestat ) == -1 ) continue; if (S_ISDIR( filestat.st_mode )) continue; strPostfix = ""; numOfRec = 0; scale_factor = 1; if(strcmp(dir_entry_p->d_name, "")) fprintf(stderr, "Examining file %s\n", dir_entry_p->d_name); strPrefix = dir_entry_p->d_name; fullPath = input_directory + "/" + strPrefix; printf("Loading image %s\n", strPrefix.c_str()); image = imread(fullPath.c_str(),1); if(! image.data ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; continue; } do { // Use scratch version of image for display, scaling down if necessary. Size sz = image.size(); if ( sz.height > max_height ) { if (sz.width > sz.height) { scale_factor = (float)max_height / (float)sz.width; } else { scale_factor = (float)max_height / (float)sz.height; } resize(image, image3, Size(), scale_factor, scale_factor, INTER_AREA); } else { image3 = image.clone(); } imshow(window_name,image3); // Start taking input iKey=cvWaitKey(0); switch(iKey) { case 27: image.release(); image2.release(); image3.release(); destroyWindow(window_name); closedir(dir_p); return 0; case 32: numOfRec++; #ifdef DEBUG printf(" %d. rect x=%d\ty=%d\tx2h=%d\ty2=%d\n",numOfRec,roi_x0,roi_y0,roi_x1,roi_y1); #endif strPostfix += " " + to_string( int( min(roi_x0,roi_x1) / scale_factor ) ) + " " + to_string( int( min(roi_y0,roi_y1) / scale_factor ) ) + " " + to_string( int( ( abs(roi_x1 - roi_x0) ) / scale_factor ) ) + " " + to_string( int( ( abs(roi_y1 - roi_y0) ) / scale_factor ) ); break; } } while(iKey!=97); if (iKey==97) { if (numOfRec > 0) { positives << strPrefix << " "<< numOfRec << strPostfix <<"\n"; destPath = pos_directory + "/" + strPrefix; } else { negatives << strPrefix << "\n"; destPath = neg_directory + "/" + strPrefix; } } rename( fullPath.c_str(), destPath.c_str() ); } image.release(); image2.release(); image3.release(); destroyWindow(window_name); closedir(dir_p); return 0; } <|endoftext|>
<commit_before>#include "GPU.hpp" #include <list> constexpr word_t GPU::Colors[4]; GPU::GPU(MMU& mmu) : _mmu(&mmu), _screen(new color_t[ScreenWidth * ScreenHeight]) { } GPU::GPU(const GPU& gpu) : _screen(new color_t[ScreenWidth * ScreenHeight]) { *this = gpu; } void GPU::reset() { std::memset(_screen.get(), 0xFF, ScreenWidth * ScreenHeight * sizeof(color_t)); get_line() = get_scroll_x() = get_scroll_y() = get_bgp() = get_lcdstat() = _cycles = 0; get_lcdc() = 0x91; get_lcdstat() = Mode::OAM; _cycles = 0; _completed_frame = false; } void GPU::step(size_t cycles, bool render) { assert(_mmu != nullptr && _screen != nullptr); static bool s_cleared_screen = false; _completed_frame = false; word_t l = get_line(); if(!enabled()) { if(!s_cleared_screen) { _cycles = 0; get_line() = 0; std::memset(_screen.get(), 0xFF, ScreenWidth * ScreenHeight * sizeof(color_t)); _completed_frame = true; s_cleared_screen = true; } return; } else if(s_cleared_screen) { _cycles = 0; get_line() = 0; s_cleared_screen = false; } _cycles += cycles; update_mode(render && enabled()); lyc(get_line() != l); } void GPU::update_mode(bool render) { switch(get_lcdstat() & LCDMode) { case Mode::HBlank: if(_cycles >= 204) { _cycles -= 204; ++get_line(); if(get_line() < ScreenHeight) { get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); } else { get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::VBlank; exec_stat_interrupt(Mode01); } } break; case Mode::VBlank: { static bool fired_interrupt = false; if(!fired_interrupt) { _mmu->rw_reg(MMU::IF) |= MMU::VBlank; fired_interrupt = true; } if(_cycles >= 456) { _cycles -= 456; ++get_line(); if(get_line() == 153) { get_line() = 0; // 456 cycles at line 0 (instead of 153) } else if(get_line() == 1) { _completed_frame = true; get_line() = 0; _window_y = 0; get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); fired_interrupt = false; } } break; } case Mode::OAM: if(_cycles >= 80) { _cycles -= 80; get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::VRAM; } break; case Mode::VRAM: if(_cycles >= 172) { _cycles -= 172; if(render) render_line(); get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::HBlank; _mmu->check_hdma(); exec_stat_interrupt(Mode00); } break; } } struct Sprite { word_t idx; int x; int y; Sprite(word_t _idx = 0, int _x = 0, int _y = 0) : idx(_idx), x(_x), y(_y) {} inline bool operator<(const Sprite& s) const { return x < s.x || idx < s.idx; } }; void GPU::render_line() { const word_t line = get_line(); const word_t LCDC = get_lcdc(); assert(line < ScreenHeight); // BG Transparency word_t line_color_idx[ScreenWidth]; // CGB Only - Per tile BG priority bool line_bg_priorities[ScreenWidth]; int wx = _mmu->read(MMU::WX) - 7; // Can be < 0 word_t wy = _mmu->read(MMU::WY); bool draw_window = (LCDC & WindowDisplay) && wx < 160 && line >= wy; // BG Disabled, draw blank in non CGB mode word_t start_col = 0; if(!_mmu->cgb_mode() && !(LCDC & BGDisplay)) { for(word_t i = 0; i < (draw_window ? wx : ScreenWidth); ++i) { _screen[to1D(i, line)] = 255; line_color_idx[i] = 0; line_bg_priorities[i] = false; } start_col = wx; // Skip to window drawing } // Render Background Or Window if((LCDC & BGDisplay) || draw_window) { // Selects the Tile Map & Tile Data Set addr_t mapoffs = (LCDC & BGTileMapDisplaySelect) ? 0x9C00 : 0x9800; addr_t base_tile_data = (LCDC & BGWindowsTileDataSelect) ? 0x8000 : 0x9000; word_t scroll_x = get_scroll_x(); word_t scroll_y = get_scroll_y(); mapoffs += 0x20 * (((line + scroll_y) & 0xFF) >> 3); word_t lineoffs = (scroll_x >> 3); word_t x = scroll_x & 7; word_t y = (scroll_y + line) & 7; // Tile Index word_t tile; word_t tile_l; word_t tile_h; word_t tile_data0 = 0, tile_data1 = 0; color_t colors_cache[4]; if(!_mmu->cgb_mode()) { for(int i = 0; i < 4; ++i) colors_cache[i] = get_bg_color(i); } // CGB Only word_t map_attributes = 0; word_t vram_bank = 0; bool xflip = false; bool yflip = false; for(word_t i = start_col; i < ScreenWidth; ++i) { // Switch to window rendering if(draw_window && i >= wx) { mapoffs = (LCDC & WindowsTileMapDisplaySelect) ? 0x9C00 : 0x9800; mapoffs += 0x20 * (_window_y >> 3); lineoffs = 0; // X & Y in window space. x = 8; // Force Tile Fetch y = _window_y & 7; ++_window_y; draw_window = false; // No need to do it again. } if(x == 8 || i == start_col) // Loading Tile Data (Next Tile) { if(_mmu->cgb_mode()) { map_attributes = _mmu->read_vram(1, mapoffs + lineoffs); for(int i = 0; i < 4; ++i) colors_cache[i] = _mmu->get_bg_color(map_attributes & BackgroundPalette, i); vram_bank = (map_attributes & TileVRAMBank) ? 1 : 0; xflip = (map_attributes & HorizontalFlip); yflip = (map_attributes & VerticalFlip); } x = x & 7; tile = _mmu->read_vram(0, mapoffs + lineoffs); int idx = tile; // If the second Tile Set is used, the tile index is signed. if(!(LCDC & BGWindowsTileDataSelect) && (tile & 0x80)) idx = -((~tile + 1) & 0xFF); int Y = yflip ? 7 - y : y; tile_l = _mmu->read_vram(vram_bank, base_tile_data + 16 * idx + Y * 2); tile_h = _mmu->read_vram(vram_bank, base_tile_data + 16 * idx + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); lineoffs = (lineoffs + 1) & 31; } word_t color_x = xflip ? (7 - x) : x; word_t shift = ((7 - color_x) & 3) << 1; word_t color = ((color_x > 3 ? tile_data1 : tile_data0) >> shift) & 0b11; line_color_idx[i] = color; line_bg_priorities[i] = (map_attributes & BGtoOAMPriority); _screen[to1D(i, line)] = colors_cache[color]; ++x; } } // Render Sprites if(get_lcdc() & OBJDisplay) { word_t Tile, Opt; word_t tile_l = 0; word_t tile_h = 0; word_t tile_data0 = 0, tile_data1 = 0; word_t sprite_limit = 10; // 8*16 Sprites ? word_t size = (get_lcdc() & OBJSize) ? 16 : 8; std::list<Sprite> sprites; for(word_t s = 0; s < 40; s++) { auto y = _mmu->read(0xFE00 + s * 4) - 16; // Visible on this scanline? // (Not testing x: On real hardware, 'out of bounds' sprites still counts towards // the 10 sprites per scanline limit) if(y <= line && (y + size) > line) sprites.emplace_back( s, _mmu->read(0xFE00 + s * 4 + 1) - 8, y ); } // If CGB mode, prioriy is only idx, i.e. sprites are already sorted. if(!_mmu->cgb_mode()) sprites.sort(); if(sprites.size() > sprite_limit) sprites.resize(sprite_limit); // Draw the sprites in reverse priority order. sprites.reverse(); bool bg_window_no_priority = _mmu->cgb_mode() && !(LCDC & BGDisplay); // (CGB Only: BG loses all priority) for(const auto& s : sprites) { // Visible on _screen? if(s.x > -8 && s.x < ScreenWidth) { Tile = _mmu->read(0xFE00 + s.idx * 4 + 2); Opt = _mmu->read(0xFE00 + s.idx * 4 + 3); if(s.y - line < 8 && get_lcdc() & OBJSize && !(Opt & YFlip)) Tile &= 0xFE; if(s.y - line >= 8 && (Opt & YFlip)) Tile &= 0xFE; if(size == 16) Tile &= ~1; // Bit 0 is ignored for 8x16 sprites const word_t palette = _mmu->read((Opt & Palette) ? MMU::OBP1 : MMU::OBP0); // non CGB Only // Only Tile Set #0 ? int Y = (Opt & YFlip) ? (size - 1) - (line - s.y) : line - s.y; const word_t vram_bank = (_mmu->cgb_mode() && (Opt & OBJTileVRAMBank)) ? 1 : 0; tile_l = _mmu->read_vram(vram_bank, 0x8000 + 16 * Tile + Y * 2); tile_h = _mmu->read_vram(vram_bank, 0x8000 + 16 * Tile + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); word_t right_limit = (s.x > ScreenWidth - 8 ? ScreenWidth - s.x : 8); for(word_t x = (s.x >= 0 ? 0 : -s.x); x < right_limit; x++) { word_t color_x = (Opt & XFlip) ? x : (7 - x); word_t shift = (color_x & 3) << 1; word_t color = ((color_x > 3 ? tile_data0 : tile_data1) >> shift) & 3; bool over_bg = (!line_bg_priorities[s.x + x] && // (CGB Only - BG Attributes) !(Opt & Priority)) || line_color_idx[s.x + x] == 0; // Priority over background or transparency if(color != 0 && // Transparency (bg_window_no_priority || over_bg)) // Priority { _screen[to1D(s.x + x, line)] = _mmu->cgb_mode() ? _mmu->get_sprite_color((Opt & PaletteNumber), color) : color_t{Colors[(palette >> (color << 1)) & 3]}; } } } } } } <commit_msg>Ignore bit 0 of tile index for 8x16 sprites<commit_after>#include "GPU.hpp" #include <list> constexpr word_t GPU::Colors[4]; GPU::GPU(MMU& mmu) : _mmu(&mmu), _screen(new color_t[ScreenWidth * ScreenHeight]) { } GPU::GPU(const GPU& gpu) : _screen(new color_t[ScreenWidth * ScreenHeight]) { *this = gpu; } void GPU::reset() { std::memset(_screen.get(), 0xFF, ScreenWidth * ScreenHeight * sizeof(color_t)); get_line() = get_scroll_x() = get_scroll_y() = get_bgp() = get_lcdstat() = _cycles = 0; get_lcdc() = 0x91; get_lcdstat() = Mode::OAM; _cycles = 0; _completed_frame = false; } void GPU::step(size_t cycles, bool render) { assert(_mmu != nullptr && _screen != nullptr); static bool s_cleared_screen = false; _completed_frame = false; word_t l = get_line(); if(!enabled()) { if(!s_cleared_screen) { _cycles = 0; get_line() = 0; std::memset(_screen.get(), 0xFF, ScreenWidth * ScreenHeight * sizeof(color_t)); _completed_frame = true; s_cleared_screen = true; } return; } else if(s_cleared_screen) { _cycles = 0; get_line() = 0; s_cleared_screen = false; } _cycles += cycles; update_mode(render && enabled()); lyc(get_line() != l); } void GPU::update_mode(bool render) { switch(get_lcdstat() & LCDMode) { case Mode::HBlank: if(_cycles >= 204) { _cycles -= 204; ++get_line(); if(get_line() < ScreenHeight) { get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); } else { get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::VBlank; exec_stat_interrupt(Mode01); } } break; case Mode::VBlank: { static bool fired_interrupt = false; if(!fired_interrupt) { _mmu->rw_reg(MMU::IF) |= MMU::VBlank; fired_interrupt = true; } if(_cycles >= 456) { _cycles -= 456; ++get_line(); if(get_line() == 153) { get_line() = 0; // 456 cycles at line 0 (instead of 153) } else if(get_line() == 1) { _completed_frame = true; get_line() = 0; _window_y = 0; get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); fired_interrupt = false; } } break; } case Mode::OAM: if(_cycles >= 80) { _cycles -= 80; get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::VRAM; } break; case Mode::VRAM: if(_cycles >= 172) { _cycles -= 172; if(render) render_line(); get_lcdstat() = (get_lcdstat() & ~LCDMode) | Mode::HBlank; _mmu->check_hdma(); exec_stat_interrupt(Mode00); } break; } } struct Sprite { word_t idx; int x; int y; Sprite(word_t _idx = 0, int _x = 0, int _y = 0) : idx(_idx), x(_x), y(_y) {} inline bool operator<(const Sprite& s) const { return x < s.x || idx < s.idx; } }; void GPU::render_line() { const word_t line = get_line(); const word_t LCDC = get_lcdc(); assert(line < ScreenHeight); // BG Transparency word_t line_color_idx[ScreenWidth]; // CGB Only - Per tile BG priority bool line_bg_priorities[ScreenWidth]; int wx = _mmu->read(MMU::WX) - 7; // Can be < 0 word_t wy = _mmu->read(MMU::WY); bool draw_window = (LCDC & WindowDisplay) && wx < 160 && line >= wy; // BG Disabled, draw blank in non CGB mode word_t start_col = 0; if(!_mmu->cgb_mode() && !(LCDC & BGDisplay)) { for(word_t i = 0; i < (draw_window ? wx : ScreenWidth); ++i) { _screen[to1D(i, line)] = 255; line_color_idx[i] = 0; line_bg_priorities[i] = false; } start_col = wx; // Skip to window drawing } // Render Background Or Window if((LCDC & BGDisplay) || draw_window) { // Selects the Tile Map & Tile Data Set addr_t mapoffs = (LCDC & BGTileMapDisplaySelect) ? 0x9C00 : 0x9800; addr_t base_tile_data = (LCDC & BGWindowsTileDataSelect) ? 0x8000 : 0x9000; word_t scroll_x = get_scroll_x(); word_t scroll_y = get_scroll_y(); mapoffs += 0x20 * (((line + scroll_y) & 0xFF) >> 3); word_t lineoffs = (scroll_x >> 3); word_t x = scroll_x & 7; word_t y = (scroll_y + line) & 7; // Tile Index word_t tile; word_t tile_l; word_t tile_h; word_t tile_data0 = 0, tile_data1 = 0; color_t colors_cache[4]; if(!_mmu->cgb_mode()) { for(int i = 0; i < 4; ++i) colors_cache[i] = get_bg_color(i); } // CGB Only word_t map_attributes = 0; word_t vram_bank = 0; bool xflip = false; bool yflip = false; for(word_t i = start_col; i < ScreenWidth; ++i) { // Switch to window rendering if(draw_window && i >= wx) { mapoffs = (LCDC & WindowsTileMapDisplaySelect) ? 0x9C00 : 0x9800; mapoffs += 0x20 * (_window_y >> 3); lineoffs = 0; // X & Y in window space. x = 8; // Force Tile Fetch y = _window_y & 7; ++_window_y; draw_window = false; // No need to do it again. } if(x == 8 || i == start_col) // Loading Tile Data (Next Tile) { if(_mmu->cgb_mode()) { map_attributes = _mmu->read_vram(1, mapoffs + lineoffs); for(int i = 0; i < 4; ++i) colors_cache[i] = _mmu->get_bg_color(map_attributes & BackgroundPalette, i); vram_bank = (map_attributes & TileVRAMBank) ? 1 : 0; xflip = (map_attributes & HorizontalFlip); yflip = (map_attributes & VerticalFlip); } x = x & 7; tile = _mmu->read_vram(0, mapoffs + lineoffs); int idx = tile; // If the second Tile Set is used, the tile index is signed. if(!(LCDC & BGWindowsTileDataSelect) && (tile & 0x80)) idx = -((~tile + 1) & 0xFF); int Y = yflip ? 7 - y : y; tile_l = _mmu->read_vram(vram_bank, base_tile_data + 16 * idx + Y * 2); tile_h = _mmu->read_vram(vram_bank, base_tile_data + 16 * idx + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); lineoffs = (lineoffs + 1) & 31; } word_t color_x = xflip ? (7 - x) : x; word_t shift = ((7 - color_x) & 3) << 1; word_t color = ((color_x > 3 ? tile_data1 : tile_data0) >> shift) & 0b11; line_color_idx[i] = color; line_bg_priorities[i] = (map_attributes & BGtoOAMPriority); _screen[to1D(i, line)] = colors_cache[color]; ++x; } } // Render Sprites if(get_lcdc() & OBJDisplay) { word_t Tile, Opt; word_t tile_l = 0; word_t tile_h = 0; word_t tile_data0 = 0, tile_data1 = 0; word_t sprite_limit = 10; // 8*16 Sprites ? word_t size = (get_lcdc() & OBJSize) ? 16 : 8; std::list<Sprite> sprites; for(word_t s = 0; s < 40; s++) { auto y = _mmu->read(0xFE00 + s * 4) - 16; // Visible on this scanline? // (Not testing x: On real hardware, 'out of bounds' sprites still counts towards // the 10 sprites per scanline limit) if(y <= line && (y + size) > line) sprites.emplace_back( s, _mmu->read(0xFE00 + s * 4 + 1) - 8, y ); } // If CGB mode, prioriy is only idx, i.e. sprites are already sorted. if(!_mmu->cgb_mode()) sprites.sort(); if(sprites.size() > sprite_limit) sprites.resize(sprite_limit); // Draw the sprites in reverse priority order. sprites.reverse(); bool bg_window_no_priority = _mmu->cgb_mode() && !(LCDC & BGDisplay); // (CGB Only: BG loses all priority) for(const auto& s : sprites) { // Visible on _screen? if(s.x > -8 && s.x < ScreenWidth) { Tile = _mmu->read(0xFE00 + s.idx * 4 + 2); Opt = _mmu->read(0xFE00 + s.idx * 4 + 3); if(get_lcdc() & OBJSize) Tile &= 0xFE; // Bit 0 is ignored for 8x16 sprites if(s.y - line >= 8 && (Opt & YFlip)) Tile &= 0xFE; const word_t palette = _mmu->read((Opt & Palette) ? MMU::OBP1 : MMU::OBP0); // non CGB Only // Only Tile Set #0 ? int Y = (Opt & YFlip) ? (size - 1) - (line - s.y) : line - s.y; const word_t vram_bank = (_mmu->cgb_mode() && (Opt & OBJTileVRAMBank)) ? 1 : 0; tile_l = _mmu->read_vram(vram_bank, 0x8000 + 16 * Tile + Y * 2); tile_h = _mmu->read_vram(vram_bank, 0x8000 + 16 * Tile + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); word_t right_limit = (s.x > ScreenWidth - 8 ? ScreenWidth - s.x : 8); for(word_t x = (s.x >= 0 ? 0 : -s.x); x < right_limit; x++) { word_t color_x = (Opt & XFlip) ? x : (7 - x); word_t shift = (color_x & 3) << 1; word_t color = ((color_x > 3 ? tile_data0 : tile_data1) >> shift) & 3; bool over_bg = (!line_bg_priorities[s.x + x] && // (CGB Only - BG Attributes) !(Opt & Priority)) || line_color_idx[s.x + x] == 0; // Priority over background or transparency if(color != 0 && // Transparency (bg_window_no_priority || over_bg)) // Priority { _screen[to1D(s.x + x, line)] = _mmu->cgb_mode() ? _mmu->get_sprite_color((Opt & PaletteNumber), color) : color_t{Colors[(palette >> (color << 1)) & 3]}; } } } } } } <|endoftext|>
<commit_before>#include <iostream> #include <boost/format.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "GeoDrillConfig.h" #include "file_utils.h" namespace po = boost::program_options; int main(int argc, const char* argv[]){ po::options_description description("GeoDrill Usage"); description.add_options() ("help,h", "Display this help message") /* ("compression,c", po::value<int>()->default_value(5)->implicit_value(10),"Compression level") */ ("input-dir", po::value<std::vector<std::string>>(), "Input directory") ("list,l", po::bool_switch()->default_value(false), "List files") ("version,v", "Display the version number"); po::positional_options_description p; p.add("input-dir", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(description).positional(p).run(), vm); po::notify(vm); if(vm.count("help")){ std::cout << description; return 0; } if(vm.count("version")){ std::cout << (boost::format("GeoDrill Version %i.%i.%i") % GeoDrill_VERSION_MAJOR % GeoDrill_VERSION_MINOR % GeoDrill_VERSION_PATCH) << std::endl; return 0; } if(vm.count("compression")){ std::cout << "Compression level " << vm["compression"].as<int>() << std::endl; } int success; if(vm.count("input-dir")) { std::vector<std::string> dirs = vm["input-dir"].as<std::vector<std::string>>(); std::vector<std::string> input_rasters; for (std::string dir : dirs) { list_files(dir, input_rasters); } for (std::string raster_file : input_rasters) { if (vm.count("list") && vm["list"].as<bool>()) { std::cout << " " << raster_file << std::endl; } } } return 0; }<commit_msg>Use readRaster() in CLI<commit_after>#include <iostream> #include <boost/format.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "GeoDrillConfig.h" #include "file_utils.h" #include "io.h" namespace po = boost::program_options; int main(int argc, const char* argv[]){ po::options_description description("GeoDrill Usage"); description.add_options() ("help,h", "Display this help message") /* ("compression,c", po::value<int>()->default_value(5)->implicit_value(10),"Compression level") */ ("input-dir", po::value<std::vector<std::string>>(), "Input directory") ("list,l", po::bool_switch()->default_value(false), "List files") ("version,v", "Display the version number"); po::positional_options_description p; p.add("input-dir", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(description).positional(p).run(), vm); po::notify(vm); if(vm.count("help")){ std::cout << description; return 0; } if(vm.count("version")){ std::cout << (boost::format("GeoDrill Version %i.%i.%i") % GeoDrill_VERSION_MAJOR % GeoDrill_VERSION_MINOR % GeoDrill_VERSION_PATCH) << std::endl; return 0; } if(vm.count("compression")){ std::cout << "Compression level " << vm["compression"].as<int>() << std::endl; } int success; if(vm.count("input-dir")) { std::vector<std::string> dirs = vm["input-dir"].as<std::vector<std::string>>(); std::vector<std::string> input_rasters; for (std::string dir : dirs) { list_files(dir, input_rasters); } for (std::string raster_file : input_rasters) { if (vm.count("list") && vm["list"].as<bool>()) { std::cout << " " << raster_file << std::endl; } success = readRaster(raster_file.c_str()); } } return 0; }<|endoftext|>
<commit_before>#include "command.h" #include "../CommandHandler.h" #include "../OptionParser.h" /* full name of the command */ CMDNAME("setrec"); /* description of the command */ CMDDESCR("enable/disabe recurring messages"); /* command usage synopsis */ CMDUSAGE("$setrec on|off"); /* setrec: enable and disable recurring messages */ std::string CommandHandler::setrec(char *out, struct command *c) { if (!P_ALMOD(c->privileges)) { PERM_DENIED(out, c->nick, c->argv[0]); return ""; } std::string outp, set; int opt; OptionParser op(c->fullCmd, ""); static struct OptionParser::option long_opts[] = { { "help", NO_ARG, 'h' }, { 0, 0, 0 } }; while ((opt = op.getopt_long(long_opts)) != EOF) { switch (opt) { case 'h': return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR); case '?': return std::string(op.opterr()); default: return ""; } } outp = "@" + std::string(c->nick) + ", "; if (op.optind() == c->fullCmd.length() || ((set = c->fullCmd.substr(op.optind())) != "on" && set != "off")) return USAGEMSG(CMDNAME, CMDUSAGE); if (set == "on") { m_evtp->activateMessages(); outp += "recurring messages enabled."; } else { m_evtp->deactivateMessages(); outp += "recurring messages disabled."; } return outp; } <commit_msg>setrec: update format<commit_after>#include <string.h> #include "command.h" #include "../CommandHandler.h" #include "../option.h" /* full name of the command */ _CMDNAME("setrec"); /* description of the command */ _CMDDESCR("enable/disabe recurring messages"); /* command usage synopsis */ _CMDUSAGE("$setrec on|off"); /* setrec: enable and disable recurring messages */ std::string CommandHandler::setrec(char *out, struct command *c) { int opt; static struct option long_opts[] = { { "help", NO_ARG, 'h' }, { 0, 0, 0 } }; if (!P_ALMOD(c->privileges)) { PERM_DENIED(out, c->nick, c->argv[0]); return ""; } opt_init(); while ((opt = getopt_long(c->argc, c->argv, "", long_opts)) != EOF) { switch (opt) { case 'h': _HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR); return ""; case '?': _sprintf(out, MAX_MSG, "%s", opterr()); return ""; default: return ""; } } if (optind != c->argc - 1) { _USAGEMSG(out, _CMDNAME, _CMDUSAGE); } else if (strcmp(c->argv[optind], "on") == 0) { m_evtp->activateMessages(); _sprintf(out, MAX_MSG, "@%s, recurring mesasges enabled.", c->nick); } else if (strcmp(c->argv[optind], "off") == 0) { m_evtp->deactivateMessages(); _sprintf(out, MAX_MSG, "@%s, recurring mesasges disabled.", c->nick); } else { _USAGEMSG(out, _CMDNAME, _CMDUSAGE); } return ""; } <|endoftext|>
<commit_before>#include "Filesystem.hpp" #include "Build.hpp" #include "Rule.hpp" #include "ShellCommand.hpp" #include "error.hpp" //#include <boost/algorithm/string/split.hpp> //#include <boost/algorithm/string/classification.hpp> #include <boost/tokenizer.hpp> #include <boost/filesystem.hpp> #include <boost/scope_exit.hpp> #include <boost/system/system_error.hpp> #include <boost/algorithm/string/predicate.hpp> #include <cstdlib> #ifdef _WIN32 # include <windows.h> #else # include <glob.h> #endif namespace fs = boost::filesystem; namespace configure { Filesystem::Filesystem(Build& build) : _build(build) {} Filesystem::~Filesystem() {} std::vector<NodePtr> Filesystem::glob(path_t const& dir, std::string const& pattern) { std::vector<NodePtr> res; fs::path base_dir = dir.is_absolute() ? dir : _build.project_directory() / dir; std::string full_pattern = (base_dir / pattern).string(); #ifdef _WIN32 WIN32_FIND_DATA find_data; auto handle = ::FindFirstFile(full_pattern.c_str(), &find_data); if (handle == INVALID_HANDLE_VALUE) { auto err = ::GetLastError(); if (err == ERROR_FILE_NOT_FOUND && fs::is_directory(base_dir)) return res; CONFIGURE_THROW( error::InvalidPath("Invalid glob pattern") << error::path(base_dir / pattern) << error::nested( std::make_exception_ptr( boost::system::system_error( err, boost::system::system_category(), "FindFirstFile()" ) ) ) ); } BOOST_SCOPE_EXIT((&handle)){ ::FindClose(handle); } BOOST_SCOPE_EXIT_END std::vector<char> buffer; do { if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; # ifdef UNICODE int size = ::WideCharToMultiByte( CP_UTF8, 0, find_data.cFileName, -1, NULL, 0, NULL, NULL ); if (size > 0) { buffer.resize(size); ::WideCharToMultiByte( CP_UTF8, 0, find_data.cFileName, -1, static_cast<BYTE*>(&buffer[0]), buffer.size(), NULL, NULL ); res.push_back( _build.source_node(base_dir / std::string(&buffer[0], size)) ); } else throw std::runtime_error("Couldn't encode a filename to UTF8"); # else // !UNICODE res.push_back( _build.source_node(base_dir / &find_data.cFileName[0]) ); # endif } while (::FindNextFile(handle, &find_data)); #else // !_WIN32 glob_t glob_state; int const ret = ::glob( full_pattern.c_str(), GLOB_NOSORT, nullptr, &glob_state ); struct glob_guard { glob_t* state; glob_guard(glob_t* state) : state(state) {} ~glob_guard() { ::globfree(state); } } guard(&glob_state); if (ret != 0) { if (ret == GLOB_NOMATCH) return res; if (ret == GLOB_NOSPACE) throw std::bad_alloc(); if (ret == GLOB_ABORTED) throw std::runtime_error("Read error"); throw std::runtime_error("Unknown glob error"); } int idx = 0; while (char const* path = glob_state.gl_pathv[idx]) { res.push_back(_build.source_node(path)); idx += 1; } #endif return res; } std::vector<NodePtr> Filesystem::glob(std::string const& pattern) { return this->glob(_build.project_directory(), pattern); } std::vector<NodePtr> Filesystem::rglob(path_t const& dir, std::string const& pattern) { std::vector<NodePtr> res = this->glob(dir, pattern); fs::recursive_directory_iterator it(dir), end; for (; it != end; ++it) { if (fs::is_directory(it->status())) { auto dir_res = this->glob(*it, pattern); res.insert(res.end(), dir_res.begin(), dir_res.end()); } } return res; } std::vector<NodePtr> Filesystem::list_directory(path_t const& dir) { if (!dir.is_absolute()) return this->list_directory(_build.project_directory() / dir); std::vector<NodePtr> res; fs::directory_iterator it(dir), end; for (; it != end; ++it) { if (fs::is_directory(it->status())) res.push_back(_build.directory_node(*it)); else res.push_back(_build.file_node(*it)); } return res; } #ifdef _WIN32 # define PATH_SEP ";" #else # define PATH_SEP ":" #endif boost::optional<fs::path> Filesystem::which(std::string const& program_name) { fs::path program(program_name); if (program.is_absolute() && fs::is_regular_file(program)) return program; char const* PATH = ::getenv("PATH"); if (PATH == nullptr) return boost::none; std::vector<std::string> out; boost::char_separator<char> sep(PATH_SEP); std::string path(PATH); boost::tokenizer<boost::char_separator<char>> tokenizer(path, sep); for (auto&& el: tokenizer) { fs::path full = fs::path(el) / program; //while (fs::is_symlink(full)) //{ // full = fs::read_symlink(full); // if (!full.is_absolute()) // full = fs::path(el) / full; //} if (fs::is_regular_file(full)) return full; } #ifdef _WIN32 if (!boost::iends_with(program, ".exe")) return this->which(program.string() + ".exe"); #endif return boost::none; } NodePtr& Filesystem::copy(path_t src, path_t dst) { return this->copy(_build.source_node(std::move(src)), std::move(dst)); } NodePtr& Filesystem::copy(NodePtr& src_node, path_t dst) { auto& dst_node = _build.target_node(std::move(dst)); ShellCommand cmd; cmd.append( _build.option<fs::path>("CP", "Copy program", "cp"), src_node, dst_node ); _build.add_rule( Rule() .add_source(src_node) .add_target(dst_node) .add_shell_command(std::move(cmd)) ); return dst_node; } } <commit_msg>Convert back to string when checking extension.<commit_after>#include "Filesystem.hpp" #include "Build.hpp" #include "Rule.hpp" #include "ShellCommand.hpp" #include "error.hpp" //#include <boost/algorithm/string/split.hpp> //#include <boost/algorithm/string/classification.hpp> #include <boost/tokenizer.hpp> #include <boost/filesystem.hpp> #include <boost/scope_exit.hpp> #include <boost/system/system_error.hpp> #include <boost/algorithm/string/predicate.hpp> #include <cstdlib> #ifdef _WIN32 # include <windows.h> #else # include <glob.h> #endif namespace fs = boost::filesystem; namespace configure { Filesystem::Filesystem(Build& build) : _build(build) {} Filesystem::~Filesystem() {} std::vector<NodePtr> Filesystem::glob(path_t const& dir, std::string const& pattern) { std::vector<NodePtr> res; fs::path base_dir = dir.is_absolute() ? dir : _build.project_directory() / dir; std::string full_pattern = (base_dir / pattern).string(); #ifdef _WIN32 WIN32_FIND_DATA find_data; auto handle = ::FindFirstFile(full_pattern.c_str(), &find_data); if (handle == INVALID_HANDLE_VALUE) { auto err = ::GetLastError(); if (err == ERROR_FILE_NOT_FOUND && fs::is_directory(base_dir)) return res; CONFIGURE_THROW( error::InvalidPath("Invalid glob pattern") << error::path(base_dir / pattern) << error::nested( std::make_exception_ptr( boost::system::system_error( err, boost::system::system_category(), "FindFirstFile()" ) ) ) ); } BOOST_SCOPE_EXIT((&handle)){ ::FindClose(handle); } BOOST_SCOPE_EXIT_END std::vector<char> buffer; do { if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; # ifdef UNICODE int size = ::WideCharToMultiByte( CP_UTF8, 0, find_data.cFileName, -1, NULL, 0, NULL, NULL ); if (size > 0) { buffer.resize(size); ::WideCharToMultiByte( CP_UTF8, 0, find_data.cFileName, -1, static_cast<BYTE*>(&buffer[0]), buffer.size(), NULL, NULL ); res.push_back( _build.source_node(base_dir / std::string(&buffer[0], size)) ); } else throw std::runtime_error("Couldn't encode a filename to UTF8"); # else // !UNICODE res.push_back( _build.source_node(base_dir / &find_data.cFileName[0]) ); # endif } while (::FindNextFile(handle, &find_data)); #else // !_WIN32 glob_t glob_state; int const ret = ::glob( full_pattern.c_str(), GLOB_NOSORT, nullptr, &glob_state ); struct glob_guard { glob_t* state; glob_guard(glob_t* state) : state(state) {} ~glob_guard() { ::globfree(state); } } guard(&glob_state); if (ret != 0) { if (ret == GLOB_NOMATCH) return res; if (ret == GLOB_NOSPACE) throw std::bad_alloc(); if (ret == GLOB_ABORTED) throw std::runtime_error("Read error"); throw std::runtime_error("Unknown glob error"); } int idx = 0; while (char const* path = glob_state.gl_pathv[idx]) { res.push_back(_build.source_node(path)); idx += 1; } #endif return res; } std::vector<NodePtr> Filesystem::glob(std::string const& pattern) { return this->glob(_build.project_directory(), pattern); } std::vector<NodePtr> Filesystem::rglob(path_t const& dir, std::string const& pattern) { std::vector<NodePtr> res = this->glob(dir, pattern); fs::recursive_directory_iterator it(dir), end; for (; it != end; ++it) { if (fs::is_directory(it->status())) { auto dir_res = this->glob(*it, pattern); res.insert(res.end(), dir_res.begin(), dir_res.end()); } } return res; } std::vector<NodePtr> Filesystem::list_directory(path_t const& dir) { if (!dir.is_absolute()) return this->list_directory(_build.project_directory() / dir); std::vector<NodePtr> res; fs::directory_iterator it(dir), end; for (; it != end; ++it) { if (fs::is_directory(it->status())) res.push_back(_build.directory_node(*it)); else res.push_back(_build.file_node(*it)); } return res; } #ifdef _WIN32 # define PATH_SEP ";" #else # define PATH_SEP ":" #endif boost::optional<fs::path> Filesystem::which(std::string const& program_name) { fs::path program(program_name); if (program.is_absolute() && fs::is_regular_file(program)) return program; char const* PATH = ::getenv("PATH"); if (PATH == nullptr) return boost::none; std::vector<std::string> out; boost::char_separator<char> sep(PATH_SEP); std::string path(PATH); boost::tokenizer<boost::char_separator<char>> tokenizer(path, sep); for (auto&& el: tokenizer) { fs::path full = fs::path(el) / program; //while (fs::is_symlink(full)) //{ // full = fs::read_symlink(full); // if (!full.is_absolute()) // full = fs::path(el) / full; //} if (fs::is_regular_file(full)) return full; } #ifdef _WIN32 if (!boost::iends_with(program.string(), ".exe")) return this->which(program.string() + ".exe"); #endif return boost::none; } NodePtr& Filesystem::copy(path_t src, path_t dst) { return this->copy(_build.source_node(std::move(src)), std::move(dst)); } NodePtr& Filesystem::copy(NodePtr& src_node, path_t dst) { auto& dst_node = _build.target_node(std::move(dst)); ShellCommand cmd; cmd.append( _build.option<fs::path>("CP", "Copy program", "cp"), src_node, dst_node ); _build.add_rule( Rule() .add_source(src_node) .add_target(dst_node) .add_shell_command(std::move(cmd)) ); return dst_node; } } <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); ~stack()/*noexcept*/; stack(stack<T> const&)/*basic*/; stack& operator=(stack<T> const&)/*basic*/; size_t count()const /*noexcept*/; size_t array_size()const /*noexcept*/; void push(T const&)/*basic*/; void pop()/*strong*/; T top()const /*strong*/; void print(std::ostream&stream)const /*noexcept*/; void swap(stack<T>&)/*noexcept*/; bool empty()const /*noexcept*/; private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {} template <typename T> stack<T>::~stack()noexcept { delete[] array_; } template <typename T> stack<T>::stack(stack<T> const& other) { array_size_ = other.array_size_; count_ = other.count_; std::copy(other.array_, other.array_ + count_, array_); } template <typename T> stack<T>& stack<T>::operator=(stack<T> const & other)noexcept { if (&other != this) stack(other).swap(*this); return *this; } template <typename T> size_t stack<T>::array_size()const noexcept { return array_size_; } template <typename T> size_t stack<T>::count()const noexcept { return count_; } template <typename T> void stack<T>::push(T const & value) { if (empty()) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } array_[count_++] = value; } template <typename T> void stack<T>::pop() { if (empty()) throw std::logic_error("Stack is empty"); else { T * new_array = new T[array_size_](); --count_; std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } } template <typename T> T stack<T>::top()const noexcept { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print(std::ostream&stream)const noexcept { for (unsigned int i = 0; i < count_; ++i) stream << array_[i] << " "; stream << std::endl; } template <typename T> void stack<T>::swap(stack<T>& other)noexcept { std::swap(array_, other.array_); std::swap(array_size_, other.array_size_); std::swap(count_, other.count_); } template <typename T> bool stack<T>::empty()const noexcept { return (count_ == 0); } <commit_msg>Update stack.hpp<commit_after>#include <iostream> #include <algorithm> #include <stdexcept> template <typename T> class stack { public: stack(); ~stack()/*noexcept*/; stack(stack<T> const&)/*basic*/; stack& operator=(stack<T> const&)/*basic*/; size_t count()const /*noexcept*/; size_t array_size()const /*noexcept*/; void push(T const&)/*basic*/; void pop()/*strong*/; T top()const /*strong*/; void print(std::ostream&stream)const /*noexcept*/; void swap(stack<T>&)/*noexcept*/; bool empty()const /*noexcept*/; private: T * array_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : array_{ nullptr }, array_size_{ 0 }, count_{ 0 } {} template <typename T> stack<T>::~stack() { delete[] array_; } template <typename T> stack<T>::stack(stack<T> const& other) { array_size_ = other.array_size_; count_ = other.count_; std::copy(other.array_, other.array_ + count_, array_); } template <typename T> stack<T>& stack<T>::operator=(stack<T> const & other) { if (&other != this) stack(other).swap(*this); return *this; } template <typename T> size_t stack<T>::array_size()const { return array_size_; } template <typename T> size_t stack<T>::count()const { return count_; } template <typename T> void stack<T>::push(T const & value) { if (empty()) { array_size_ = 1; array_ = new T[array_size_](); } else if (array_size_ == count_) { array_size_ *= 2; T * new_array = new T[array_size_](); std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } array_[count_++] = value; } template <typename T> void stack<T>::pop() { if (empty()) throw std::logic_error("Stack is empty"); else { T * new_array = new T[array_size_](); --count_; std::copy(array_, array_ + count_, new_array); delete[] array_; array_ = new_array; } } template <typename T> T stack<T>::top()const { if (empty()) throw std::logic_error("Stack is empty"); else return array_[count_ - 1]; } template <typename T> void stack<T>::print(std::ostream&stream)const { for (unsigned int i = 0; i < count_; ++i) stream << array_[i] << " "; stream << std::endl; } template <typename T> void stack<T>::swap(stack<T>& other) { std::swap(array_, other.array_); std::swap(array_size_, other.array_size_); std::swap(count_, other.count_); } template <typename T> bool stack<T>::empty()const { return (count_ == 0); } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2009, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "udp_waker.h" #include "condor_debug.h" #include "condor_fix_assert.h" #include "condor_io.h" #include "condor_constants.h" #include "condor_classad.h" #include "condor_attributes.h" #include "basename.h" /** Preprocessor definitions */ #define DESCRIPTION "wake or hibernate a machine" /** Constants */ /** Error codes */ enum { E_NONE = 0, /* no error */ E_NOMEM = -1, /* not enough memory */ E_FOPEN = -2, /* cannot open file */ E_FREAD = -3, /* read error on file */ E_OPTION = -4, /* unknown option */ E_OPTARG = -5, /* missing option argument */ E_ARGCNT = -6, /* too few/many arguments */ E_NOWAKE = -7, /* failed to wake machine */ E_NOREST = -8, /* failed to switch the machine's power state */ E_CLASSAD = -9, /* error in class-ad (errno = %d) */ E_UNKNOWN = -10 /* unknown error */ }; /** Error messages */ static const char *errmsgs[] = { /* E_NONE 0 */ "no error%s.\n", /* E_NOMEM -1 */ "not enough memory for %s.\n", /* E_FOPEN -2 */ "cannot open file %s: %s (errno = %d).\n", /* E_FREAD -3 */ "read error on file %s.\n", /* E_OPTION -4 */ "unknown option -%c.\n", /* E_OPTARG -5 */ "missing option argument.\n", /* E_ARGCNT -6 */ "wrong number of arguments.\n", /* E_NOWAKE -7 */ "failed to sent wake packet.\n", /* E_NOREST -8 */ "failed to switch the machine's power state.\n", /* E_CLASSAD -9 */ "error in class-ad (errno = %d).\n", /* E_UNKNOWN -10 */ "unknown error.\n" }; /** Typedefs */ /** Global Variables */ static FILE *in = NULL; /* input file */ static char *fn_in = NULL; /* name of input file */ static char *fn_out = NULL; /* name of output file */ static const char *name = NULL; /* program name */ static char *mac = NULL; /* hardware address */ static char *mask = "255.255.255.255"; /*subnet to broadcast on*/ static int port = 9; /* port number to use */ static bool stdio = false; /* if true, use stdin and stdout. */ static ClassAd *ad = NULL; /* machine class-ad */ static WakerBase *waker = NULL; /* waking mechanism */ /** Functions */ static void usage( void ) { fprintf ( stderr, "usage: %s [OPTIONS] [INPUT-CLASSAD-FILE] [OUTPUT]\n", name ); fprintf ( stderr, "%s - %s\n", name, DESCRIPTION ); fprintf ( stderr, "\n" ); fprintf ( stderr, "-h This message\n" ); fprintf ( stderr, "\n" ); fprintf ( stderr, "-d Enables debugging\n" ); fprintf ( stderr, "\n" ); fprintf ( stderr, "-i Use standard input and output\n" ); fprintf ( stderr, "-m Hardware address (MAC address)\n" ); fprintf ( stderr, "-p Port (default: %d)\n", port ); fprintf ( stderr, "-s Subnet mask (default: %s)\n", mask ); fprintf ( stderr, "\n" ); fprintf ( stderr, "With -i, read standard input.\n" ); exit ( 0 ); } static void enable_debug( void ) { Termlog = 1; dprintf_config ( "TOOL" ); } static void error( int code, ... ) { va_list args; const char *msg; assert ( name ); if ( code < E_UNKNOWN ) { code = E_UNKNOWN; } if ( code < 0 ) { msg = errmsgs[-code]; if ( !msg ) { msg = errmsgs[-E_UNKNOWN]; } fprintf ( stderr, "%s: ", name ); va_start ( args, code ); vfprintf ( stderr, msg, args ); va_end ( args ); } if ( in && ( in != stdin ) ) { fclose ( in ); } if ( waker ) { delete waker; waker = NULL; } if ( ad ) { delete ad; ad = NULL; } exit ( code ); } static void parse_command_line( int argc, char *argv[] ) { int i, j = 0; char *s; /* to traverse the options */ char **argument = NULL; /* option argument */ for ( i = 1; i < argc; i++ ) { s = argv[i]; if ( argument ) { *argument = s; argument = NULL; continue; } if ( ( '-' == *s ) && *++s ) { /* we're looking at an option */ while ( *s ) { /* determine which one it is */ switch ( *s++ ) { case 'd': enable_debug (); break; case 'h': usage (); break; case 'i': stdio = true; break; case 'm': argument = &mac; break; case 'p': port = (int) strtol ( s, &s, port ); break; case 's': argument = &mask; break; default : error ( E_OPTION, *--s ); break; } /* if there is an argument to this option, stash it */ if ( argument && *s ) { *argument = s; argument = NULL; break; } } } else { /* we're looking at a file name */ switch ( j++ ) { case 0: fn_in = s; break; case 1: fn_out = s; break; default: error ( E_ARGCNT ); break; } } } } static void serialize_input( void ) { char sinful[16 + 10]; int found_eof = 0, found_error = 0, empty = 0; /** Determine if we are using the command-line options, a file, or standard input as input */ if ( !stdio ) { /** Contrive a sinful string based on our IP address */ sprintf ( sinful, "<%s:1234>", my_ip_string () ); /** We were give all the raw data, so we're going to create a fake machine ad that we will use when invoking the waking mechanism */ ad = new ClassAd (); ad->SetMyTypeName ( STARTD_ADTYPE ); ad->SetTargetTypeName ( JOB_ADTYPE ); ad->Assign ( ATTR_HARDWARE_ADDRESS, mac ); ad->Assign ( ATTR_SUBNET_MASK, mask ); ad->Assign ( ATTR_PUBLIC_NETWORK_IP_ADDR, sinful ); ad->Assign ( ATTR_WOL_PORT, port ); } else { /** Open the machine ad file or read it from stdin */ if ( fn_in && *fn_in ) { in = safe_fopen_wrapper ( fn_in, "r" ); } else { in = stdin; fn_in = "<stdin>"; } if ( !in ) { error ( E_FOPEN, fn_in, strerror ( errno ), errno ); } /** Serialize the machine ad from a file */ ad = new ClassAd ( in, "?$#%^&*@", /* sufficiently random garbage? */ found_eof, found_error, empty ); if ( found_error ) { error ( E_CLASSAD, found_error ); } } } static void wake_machine( void ) { /** Create the waking mechanism. */ waker = WakerBase::createWaker ( ad ); if ( !waker ) { error( E_NOMEM, "waker object." ); } /** Attempt to wake the remote machine */ if ( !waker->doWake () ) { error ( E_NOWAKE ); } fprintf ( stderr, "Packet sent.\n" ); delete waker; } int main( int argc, char *argv[] ) { /** Retrieve the program's name */ name = condor_basename ( argv[0] ); if ( !name ) { name = argv[0]; } /** Parse the command line and populate the global state */ parse_command_line ( argc, argv ); /** Grab the user's input */ serialize_input (); if ( ad ) { wake_machine (); } return 0; } <commit_msg>Fixed a typo in an error message in condor_power.<commit_after>/*************************************************************** * * Copyright (C) 1990-2009, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "udp_waker.h" #include "condor_debug.h" #include "condor_fix_assert.h" #include "condor_io.h" #include "condor_constants.h" #include "condor_classad.h" #include "condor_attributes.h" #include "basename.h" /** Preprocessor definitions */ #define DESCRIPTION "wake or hibernate a machine" /** Constants */ /** Error codes */ enum { E_NONE = 0, /* no error */ E_NOMEM = -1, /* not enough memory */ E_FOPEN = -2, /* cannot open file */ E_FREAD = -3, /* read error on file */ E_OPTION = -4, /* unknown option */ E_OPTARG = -5, /* missing option argument */ E_ARGCNT = -6, /* too few/many arguments */ E_NOWAKE = -7, /* failed to wake machine */ E_NOREST = -8, /* failed to switch the machine's power state */ E_CLASSAD = -9, /* error in class-ad (errno = %d) */ E_UNKNOWN = -10 /* unknown error */ }; /** Error messages */ static const char *errmsgs[] = { /* E_NONE 0 */ "no error%s.\n", /* E_NOMEM -1 */ "not enough memory for %s.\n", /* E_FOPEN -2 */ "cannot open file %s: %s (errno = %d).\n", /* E_FREAD -3 */ "read error on file %s.\n", /* E_OPTION -4 */ "unknown option -%c.\n", /* E_OPTARG -5 */ "missing option argument.\n", /* E_ARGCNT -6 */ "wrong number of arguments.\n", /* E_NOWAKE -7 */ "failed to send wake packet.\n", /* E_NOREST -8 */ "failed to switch the machine's power state.\n", /* E_CLASSAD -9 */ "error in class-ad (errno = %d).\n", /* E_UNKNOWN -10 */ "unknown error.\n" }; /** Typedefs */ /** Global Variables */ static FILE *in = NULL; /* input file */ static char *fn_in = NULL; /* name of input file */ static char *fn_out = NULL; /* name of output file */ static const char *name = NULL; /* program name */ static char *mac = NULL; /* hardware address */ static char *mask = "255.255.255.255"; /*subnet to broadcast on*/ static int port = 9; /* port number to use */ static bool stdio = false; /* if true, use stdin and stdout. */ static ClassAd *ad = NULL; /* machine class-ad */ static WakerBase *waker = NULL; /* waking mechanism */ /** Functions */ static void usage( void ) { fprintf ( stderr, "usage: %s [OPTIONS] [INPUT-CLASSAD-FILE] [OUTPUT]\n", name ); fprintf ( stderr, "%s - %s\n", name, DESCRIPTION ); fprintf ( stderr, "\n" ); fprintf ( stderr, "-h This message\n" ); fprintf ( stderr, "\n" ); fprintf ( stderr, "-d Enables debugging\n" ); fprintf ( stderr, "\n" ); fprintf ( stderr, "-i Use standard input and output\n" ); fprintf ( stderr, "-m Hardware address (MAC address)\n" ); fprintf ( stderr, "-p Port (default: %d)\n", port ); fprintf ( stderr, "-s Subnet mask (default: %s)\n", mask ); fprintf ( stderr, "\n" ); fprintf ( stderr, "With -i, read standard input.\n" ); exit ( 0 ); } static void enable_debug( void ) { Termlog = 1; dprintf_config ( "TOOL" ); } static void error( int code, ... ) { va_list args; const char *msg; assert ( name ); if ( code < E_UNKNOWN ) { code = E_UNKNOWN; } if ( code < 0 ) { msg = errmsgs[-code]; if ( !msg ) { msg = errmsgs[-E_UNKNOWN]; } fprintf ( stderr, "%s: ", name ); va_start ( args, code ); vfprintf ( stderr, msg, args ); va_end ( args ); } if ( in && ( in != stdin ) ) { fclose ( in ); } if ( waker ) { delete waker; waker = NULL; } if ( ad ) { delete ad; ad = NULL; } exit ( code ); } static void parse_command_line( int argc, char *argv[] ) { int i, j = 0; char *s; /* to traverse the options */ char **argument = NULL; /* option argument */ for ( i = 1; i < argc; i++ ) { s = argv[i]; if ( argument ) { *argument = s; argument = NULL; continue; } if ( ( '-' == *s ) && *++s ) { /* we're looking at an option */ while ( *s ) { /* determine which one it is */ switch ( *s++ ) { case 'd': enable_debug (); break; case 'h': usage (); break; case 'i': stdio = true; break; case 'm': argument = &mac; break; case 'p': port = (int) strtol ( s, &s, port ); break; case 's': argument = &mask; break; default : error ( E_OPTION, *--s ); break; } /* if there is an argument to this option, stash it */ if ( argument && *s ) { *argument = s; argument = NULL; break; } } } else { /* we're looking at a file name */ switch ( j++ ) { case 0: fn_in = s; break; case 1: fn_out = s; break; default: error ( E_ARGCNT ); break; } } } } static void serialize_input( void ) { char sinful[16 + 10]; int found_eof = 0, found_error = 0, empty = 0; /** Determine if we are using the command-line options, a file, or standard input as input */ if ( !stdio ) { /** Contrive a sinful string based on our IP address */ sprintf ( sinful, "<%s:1234>", my_ip_string () ); /** We were give all the raw data, so we're going to create a fake machine ad that we will use when invoking the waking mechanism */ ad = new ClassAd (); ad->SetMyTypeName ( STARTD_ADTYPE ); ad->SetTargetTypeName ( JOB_ADTYPE ); ad->Assign ( ATTR_HARDWARE_ADDRESS, mac ); ad->Assign ( ATTR_SUBNET_MASK, mask ); ad->Assign ( ATTR_PUBLIC_NETWORK_IP_ADDR, sinful ); ad->Assign ( ATTR_WOL_PORT, port ); } else { /** Open the machine ad file or read it from stdin */ if ( fn_in && *fn_in ) { in = safe_fopen_wrapper ( fn_in, "r" ); } else { in = stdin; fn_in = "<stdin>"; } if ( !in ) { error ( E_FOPEN, fn_in, strerror ( errno ), errno ); } /** Serialize the machine ad from a file */ ad = new ClassAd ( in, "?$#%^&*@", /* sufficiently random garbage? */ found_eof, found_error, empty ); if ( found_error ) { error ( E_CLASSAD, found_error ); } } } static void wake_machine( void ) { /** Create the waking mechanism. */ waker = WakerBase::createWaker ( ad ); if ( !waker ) { error( E_NOMEM, "waker object." ); } /** Attempt to wake the remote machine */ if ( !waker->doWake () ) { error ( E_NOWAKE ); } fprintf ( stderr, "Packet sent.\n" ); delete waker; } int main( int argc, char *argv[] ) { /** Retrieve the program's name */ name = condor_basename ( argv[0] ); if ( !name ) { name = argv[0]; } /** Parse the command line and populate the global state */ parse_command_line ( argc, argv ); /** Grab the user's input */ serialize_input (); if ( ad ) { wake_machine (); } return 0; } <|endoftext|>
<commit_before>#pragma once #include "base/mappable.hpp" #include "geometry/barycentre_calculator.hpp" #include "geometry/point.hpp" #include "serialization/geometry.pb.h" namespace principia { namespace testing_utilities { template<typename T1Matcher, typename T2Matcher> class ComponentwiseMatcher2; } // namespace testing_utilities namespace geometry { template<typename T1, typename T2> class Pair; // A template to peel off the affine layer (i.e., the class Point) if any. template<typename T> class vector_of { public: using type = T; }; template<typename T1, typename T2> class vector_of<Pair<T1, T2>> { public: using type = Pair<typename vector_of<T1>::type, typename vector_of<T2>::type>; }; template<typename T> class vector_of<Point<T>> { public: using type = T; }; // A template to enable declarations on affine pairs (i.e., when one of the // components is a Point). template<typename T> class enable_if_affine {}; template<typename T1, typename T2> class enable_if_affine<Pair<Point<T1>, T2>> { public: using type = Pair<Point<T1>, T2>; }; template<typename T1, typename T2> class enable_if_affine<Pair<T1, Point<T2>>> { public: using type = Pair<T1, Point<T2>>; }; template<typename T1, typename T2> class enable_if_affine<Pair<Point<T1>, Point<T2>>> { public: using type = Pair<Point<T1>, Point<T2>>; }; // A template to enable declarations on vector pairs (i.e., when none of the // components is a Point). template<typename T, typename U = T> class enable_if_vector { public: using type = U; }; template<typename T1, typename T2> class enable_if_vector<Pair<Point<T1>, T2>> {}; template<typename T1, typename T2> class enable_if_vector<Pair<T1, Point<T2>>> {}; template<typename T1, typename T2> class enable_if_vector<Pair<Point<T1>, Point<T2>>> {}; // This class represents a pair of two values which can be members of an affine // space (i.e., Points) or of a vector space (such as double, Quantity, Vector, // Bivector or Trivector). Only the operations that make sense are defined, // depending on the nature of the parameters T1 and T2. template<typename T1, typename T2> class Pair { public: Pair(T1 const& t1, T2 const& t2); Pair operator+(typename vector_of<Pair>::type const& right) const; Pair operator-(typename vector_of<Pair>::type const& right) const; Pair& operator+=(typename vector_of<Pair>::type const& right); Pair& operator-=(typename vector_of<Pair>::type const& right); bool operator==(Pair const& right) const; bool operator!=(Pair const& right) const; void WriteToMessage(not_null<serialization::Pair*> const message) const; static Pair ReadFromMessage(serialization::Pair const& message); protected: // The subclasses can access the members directly to implement accessors. T1 t1_; T2 t2_; private: // This is needed so that different instantiations of Pair can access the // members. template<typename U1, typename U2> friend class Pair; // This is needed to specialize BarycentreCalculator. template<typename V, typename S> friend class BarycentreCalculator; // This is needed to make Pair mappable. template<typename Functor, typename T, typename> friend class base::Mappable; // This is needed for testing. template<typename T1Matcher, typename T2Matcher> friend class testing_utilities::ComponentwiseMatcher2; template<typename U1, typename U2> friend typename vector_of<Pair<U1, U2>>::type operator-( typename enable_if_affine<Pair<U1, U2>>::type const& left, Pair<U1, U2> const& right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type operator+( Pair<U1, U2> const& right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type operator-( Pair<U1, U2> const& right); template<typename Scalar, typename U1, typename U2> friend typename enable_if_vector< Pair<U1, U2>, Pair<decltype(std::declval<Scalar>() * std::declval<U1>()), decltype(std::declval<Scalar>() * std::declval<U2>())>>::type operator*(Scalar const left, Pair<U1, U2> const& right); template<typename Scalar, typename U1, typename U2> friend typename enable_if_vector< Pair<U1, U2>, Pair<decltype(std::declval<U1>() * std::declval<Scalar>()), decltype(std::declval<U2>() * std::declval<Scalar>())>>::type operator*(Pair<U1, U2> const& left, Scalar const right); template<typename Scalar, typename U1, typename U2> friend typename enable_if_vector< Pair<U1, U2>, Pair<decltype(std::declval<U1>() / std::declval<Scalar>()), decltype(std::declval<U2>() / std::declval<Scalar>())>>::type operator/(Pair<U1, U2> const& left, Scalar const right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type& operator*=( Pair<U1, U2>& left, // NOLINT(runtime/references) double const right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type& operator/=( Pair<U1, U2>& left, // NOLINT(runtime/references) double const right); template<typename U1, typename U2> friend std::ostream& operator<<(std::ostream& out, Pair<U1, U2> const& pair); }; // NOTE(phl): Would like to put the enable_if_affine<> on the return type, but // this confuses MSVC. template<typename T1, typename T2> typename vector_of<Pair<T1, T2>>::type operator-( typename enable_if_affine<Pair<T1, T2>>::type const& left, Pair<T1, T2> const& right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type operator+( Pair<T1, T2> const& right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type operator-( Pair<T1, T2> const& right); template<typename Scalar, typename T1, typename T2> typename enable_if_vector< Pair<T1, T2>, Pair<decltype(std::declval<Scalar>() * std::declval<T1>()), decltype(std::declval<Scalar>() * std::declval<T2>())>>::type operator*(Scalar const left, Pair<T1, T2> const& right); template<typename Scalar, typename T1, typename T2> typename enable_if_vector< Pair<T1, T2>, Pair<decltype(std::declval<T1>() * std::declval<Scalar>()), decltype(std::declval<T2>() * std::declval<Scalar>())>>::type operator*(Pair<T1, T2> const& left, Scalar const right); template<typename Scalar, typename T1, typename T2> typename enable_if_vector< Pair<T1, T2>, Pair<decltype(std::declval<T1>() / std::declval<Scalar>()), decltype(std::declval<T2>() / std::declval<Scalar>())>>::type operator/(Pair<T1, T2> const& left, Scalar const right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type& operator*=( Pair<T1, T2>& left, // NOLINT(runtime/references) double const right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type& operator/=( Pair<T1, T2>& left, // NOLINT(runtime/references) double const right); template<typename T1, typename T2> std::ostream& operator<<(std::ostream& out, Pair<T1, T2> const& pair); // Specialize BarycentreCalculator to make it applicable to Pairs. template<typename T1, typename T2, typename Weight> class BarycentreCalculator<Pair<T1, T2>, Weight> { public: BarycentreCalculator() = default; ~BarycentreCalculator() = default; void Add(Pair<T1, T2> const& pair, Weight const& weight); Pair<T1, T2> Get() const; private: bool empty_ = true; decltype(std::declval<typename vector_of<T1>::type>() * std::declval<Weight>()) t1_weighted_sum_; decltype(std::declval<typename vector_of<T2>::type>() * std::declval<Weight>()) t2_weighted_sum_; Weight weight_; // We need reference values to convert points into vectors, if needed. We // pick default-constructed objects as they don't introduce any inaccuracies // in the computations. static T1 const reference_t1_; static T2 const reference_t2_; }; } // namespace geometry // Reopen the base namespace to make Pairs of vectors mappable. namespace base { template<typename Functor, typename T1, typename T2> class Mappable<Functor, geometry::Pair<T1, T2>, typename geometry::enable_if_vector< geometry::Pair<T1, T2>, void>::type> { public: using type = geometry::Pair< decltype(std::declval<Functor>()(std::declval<T1>())), decltype(std::declval<Functor>()(std::declval<T2>()))>; static type Do(Functor const& functor, geometry::Pair<T1, T2> const& pair); }; } // namespace base } // namespace principia #include "geometry/pair_body.hpp" <commit_msg>Broken comment.<commit_after>#pragma once #include "base/mappable.hpp" #include "geometry/barycentre_calculator.hpp" #include "geometry/point.hpp" #include "serialization/geometry.pb.h" namespace principia { namespace testing_utilities { template<typename T1Matcher, typename T2Matcher> class ComponentwiseMatcher2; } // namespace testing_utilities namespace geometry { template<typename T1, typename T2> class Pair; // A template to peel off the affine layer (i.e., the class Point) if any. template<typename T> class vector_of { public: using type = T; }; template<typename T1, typename T2> class vector_of<Pair<T1, T2>> { public: using type = Pair<typename vector_of<T1>::type, typename vector_of<T2>::type>; }; template<typename T> class vector_of<Point<T>> { public: using type = T; }; // A template to enable declarations on affine pairs (i.e., when one of the // components is a Point). template<typename T> class enable_if_affine {}; template<typename T1, typename T2> class enable_if_affine<Pair<Point<T1>, T2>> { public: using type = Pair<Point<T1>, T2>; }; template<typename T1, typename T2> class enable_if_affine<Pair<T1, Point<T2>>> { public: using type = Pair<T1, Point<T2>>; }; template<typename T1, typename T2> class enable_if_affine<Pair<Point<T1>, Point<T2>>> { public: using type = Pair<Point<T1>, Point<T2>>; }; // A template to enable declarations on vector pairs (i.e., when none of the // components is a Point). template<typename T, typename U = T> class enable_if_vector { public: using type = U; }; template<typename T1, typename T2> class enable_if_vector<Pair<Point<T1>, T2>> {}; template<typename T1, typename T2> class enable_if_vector<Pair<T1, Point<T2>>> {}; template<typename T1, typename T2> class enable_if_vector<Pair<Point<T1>, Point<T2>>> {}; // This class represents a pair of two values which can be members of an affine // space (i.e., Points) or of a vector space (such as double, Quantity, Vector, // Bivector or Trivector). Only the operations that make sense are defined, // depending on the nature of the parameters T1 and T2. template<typename T1, typename T2> class Pair { public: Pair(T1 const& t1, T2 const& t2); Pair operator+(typename vector_of<Pair>::type const& right) const; Pair operator-(typename vector_of<Pair>::type const& right) const; Pair& operator+=(typename vector_of<Pair>::type const& right); Pair& operator-=(typename vector_of<Pair>::type const& right); bool operator==(Pair const& right) const; bool operator!=(Pair const& right) const; void WriteToMessage(not_null<serialization::Pair*> const message) const; static Pair ReadFromMessage(serialization::Pair const& message); protected: // The subclasses can access the members directly to implement accessors. T1 t1_; T2 t2_; private: // This is needed so that different instantiations of Pair can access the // members. template<typename U1, typename U2> friend class Pair; // This is needed to specialize BarycentreCalculator. template<typename V, typename S> friend class BarycentreCalculator; // This is needed to make Pair mappable. template<typename Functor, typename T, typename> friend class base::Mappable; // This is needed for testing. template<typename T1Matcher, typename T2Matcher> friend class testing_utilities::ComponentwiseMatcher2; template<typename U1, typename U2> friend typename vector_of<Pair<U1, U2>>::type operator-( typename enable_if_affine<Pair<U1, U2>>::type const& left, Pair<U1, U2> const& right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type operator+( Pair<U1, U2> const& right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type operator-( Pair<U1, U2> const& right); template<typename Scalar, typename U1, typename U2> friend typename enable_if_vector< Pair<U1, U2>, Pair<decltype(std::declval<Scalar>() * std::declval<U1>()), decltype(std::declval<Scalar>() * std::declval<U2>())>>::type operator*(Scalar const left, Pair<U1, U2> const& right); template<typename Scalar, typename U1, typename U2> friend typename enable_if_vector< Pair<U1, U2>, Pair<decltype(std::declval<U1>() * std::declval<Scalar>()), decltype(std::declval<U2>() * std::declval<Scalar>())>>::type operator*(Pair<U1, U2> const& left, Scalar const right); template<typename Scalar, typename U1, typename U2> friend typename enable_if_vector< Pair<U1, U2>, Pair<decltype(std::declval<U1>() / std::declval<Scalar>()), decltype(std::declval<U2>() / std::declval<Scalar>())>>::type operator/(Pair<U1, U2> const& left, Scalar const right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type& operator*=( Pair<U1, U2>& left, // NOLINT(runtime/references) double const right); template<typename U1, typename U2> friend typename enable_if_vector<Pair<U1, U2>>::type& operator/=( Pair<U1, U2>& left, // NOLINT(runtime/references) double const right); template<typename U1, typename U2> friend std::ostream& operator<<(std::ostream& out, Pair<U1, U2> const& pair); }; template<typename T1, typename T2> typename vector_of<Pair<T1, T2>>::type operator-( typename enable_if_affine<Pair<T1, T2>>::type const& left, Pair<T1, T2> const& right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type operator+( Pair<T1, T2> const& right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type operator-( Pair<T1, T2> const& right); template<typename Scalar, typename T1, typename T2> typename enable_if_vector< Pair<T1, T2>, Pair<decltype(std::declval<Scalar>() * std::declval<T1>()), decltype(std::declval<Scalar>() * std::declval<T2>())>>::type operator*(Scalar const left, Pair<T1, T2> const& right); template<typename Scalar, typename T1, typename T2> typename enable_if_vector< Pair<T1, T2>, Pair<decltype(std::declval<T1>() * std::declval<Scalar>()), decltype(std::declval<T2>() * std::declval<Scalar>())>>::type operator*(Pair<T1, T2> const& left, Scalar const right); template<typename Scalar, typename T1, typename T2> typename enable_if_vector< Pair<T1, T2>, Pair<decltype(std::declval<T1>() / std::declval<Scalar>()), decltype(std::declval<T2>() / std::declval<Scalar>())>>::type operator/(Pair<T1, T2> const& left, Scalar const right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type& operator*=( Pair<T1, T2>& left, // NOLINT(runtime/references) double const right); template<typename T1, typename T2> typename enable_if_vector<Pair<T1, T2>>::type& operator/=( Pair<T1, T2>& left, // NOLINT(runtime/references) double const right); template<typename T1, typename T2> std::ostream& operator<<(std::ostream& out, Pair<T1, T2> const& pair); // Specialize BarycentreCalculator to make it applicable to Pairs. template<typename T1, typename T2, typename Weight> class BarycentreCalculator<Pair<T1, T2>, Weight> { public: BarycentreCalculator() = default; ~BarycentreCalculator() = default; void Add(Pair<T1, T2> const& pair, Weight const& weight); Pair<T1, T2> Get() const; private: bool empty_ = true; decltype(std::declval<typename vector_of<T1>::type>() * std::declval<Weight>()) t1_weighted_sum_; decltype(std::declval<typename vector_of<T2>::type>() * std::declval<Weight>()) t2_weighted_sum_; Weight weight_; // We need reference values to convert points into vectors, if needed. We // pick default-constructed objects as they don't introduce any inaccuracies // in the computations. static T1 const reference_t1_; static T2 const reference_t2_; }; } // namespace geometry // Reopen the base namespace to make Pairs of vectors mappable. namespace base { template<typename Functor, typename T1, typename T2> class Mappable<Functor, geometry::Pair<T1, T2>, typename geometry::enable_if_vector< geometry::Pair<T1, T2>, void>::type> { public: using type = geometry::Pair< decltype(std::declval<Functor>()(std::declval<T1>())), decltype(std::declval<Functor>()(std::declval<T2>()))>; static type Do(Functor const& functor, geometry::Pair<T1, T2> const& pair); }; } // namespace base } // namespace principia #include "geometry/pair_body.hpp" <|endoftext|>
<commit_before>#include "Debugger.h" #include <iostream> #include <cctype> #include <functional> #include <algorithm> #include <sstream> #include <iomanip> using namespace Debug; Debugger::Debugger(Emulator *_emulator, uint8_t _opts) { emulator = _emulator; opts = _opts; } Debugger::~Debugger() {} void Debugger::Run() { emulator->cpu.running = false; while (true) { if (!emulator->cpu.running || opts & DBG_INTERACTIVE) { DebugCmd cmd = getCommand("(mfemu)"); switch (cmd.instr) { case CMD_RUN: std::cout << "Starting emulation..." << std::endl; emulator->cpu.running = true; break; case CMD_BREAK: { std::stringstream ss(cmd.args.front()); uint16_t arg; ss >> std::hex >> arg; setBreakpoint(arg); break; } case CMD_STEP: if (emulator->cpu.running) { SDL_RenderClear(emulator->renderer); emulator->cpu.Step(); } else { std::cerr << "CPU is not running: type `run` to start emulation." << std::endl; } break; case CMD_CONTINUE: if (emulator->cpu.running) { opts &= ~DBG_INTERACTIVE; } else { std::cerr << "CPU is not running: type `run` to start emulation." << std::endl; } break; case CMD_HELP: std::cout << "run Start emulation" << std::endl << "break <addr> Set breakpoint at <addr>" << std::endl << "step Fetch and execute a single instruction" << std::endl << "continue Resume execution" << std::endl << "help Print a help message" << std::endl << "quit Quit the debugger" << std::endl; break; case CMD_QUIT: std::cerr << "...quitting." << std::endl; return; default: std::cerr << "Invalid command" << std::endl; } } else { // Execute instructions until a breakpoint is found uint16_t PC = emulator->cpu.PC; if (breakPoints.find(PC) != breakPoints.end()) { opts |= DBG_INTERACTIVE; std::cout << "Breakpoint reached: " << std::hex << (int)PC << std::endl; continue; } uint16_t opcode = emulator->cpu.Read(PC); emulator->cpu.Execute(opcode); if (!(opts & DBG_NOGRAPHICS)) SDL_RenderClear(emulator->renderer); ++emulator->cpu.PC; } } } // Reads a command from stdin and returns a struct { cmd, args }. // Currently only takes 1 argument. DebugCmd Debugger::getCommand(const char* prompt) { static DebugCmd latest = { CMD_INVALID }; std::cout << prompt << " " << std::flush; std::string line; std::string instr; DebugCmd cmd; std::getline(std::cin, line); if ((std::cin.rdstate() & std::cin.eofbit) != 0) { cmd.instr = CMD_QUIT; return cmd; } // rtrim spaces line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end()); std::stringstream ss(line); if (line.length() < 1) { if (latest.instr != CMD_INVALID) { // repeat latest command return latest; } else { return getCommand(prompt); } } else { ss >> instr; } if (instr == "run") cmd.instr = CMD_RUN; else if (instr == "break") { cmd.instr = CMD_BREAK; std::string arg; ss >> arg; cmd.args.push_back(arg); } else if (instr == "quit" || instr == "exit") cmd.instr = CMD_QUIT; else if (instr == "step") cmd.instr = CMD_STEP; else if (instr == "cont" || instr == "continue") cmd.instr = CMD_CONTINUE; else if (instr == "help" || instr == "?") cmd.instr = CMD_HELP; else cmd.instr = CMD_INVALID; latest = cmd; return cmd; } void Debugger::setBreakpoint(uint16_t addr) { breakPoints.insert(addr); std::cout << "Set breakpoint to " << std::setfill('0') << std::setw(4) << std::hex << (int)addr << std::endl; } <commit_msg>Little type mistake<commit_after>#include "Debugger.h" #include <iostream> #include <cctype> #include <functional> #include <algorithm> #include <sstream> #include <iomanip> using namespace Debug; Debugger::Debugger(Emulator *_emulator, uint8_t _opts) { emulator = _emulator; opts = _opts; } Debugger::~Debugger() {} void Debugger::Run() { emulator->cpu.running = false; while (true) { if (!emulator->cpu.running || opts & DBG_INTERACTIVE) { DebugCmd cmd = getCommand("(mfemu)"); switch (cmd.instr) { case CMD_RUN: std::cout << "Starting emulation..." << std::endl; emulator->cpu.running = true; break; case CMD_BREAK: { std::stringstream ss(cmd.args.front()); uint16_t arg; ss >> std::hex >> arg; setBreakpoint(arg); break; } case CMD_STEP: if (emulator->cpu.running) { SDL_RenderClear(emulator->renderer); emulator->cpu.Step(); } else { std::cerr << "CPU is not running: type `run` to start emulation." << std::endl; } break; case CMD_CONTINUE: if (emulator->cpu.running) { opts &= ~DBG_INTERACTIVE; } else { std::cerr << "CPU is not running: type `run` to start emulation." << std::endl; } break; case CMD_HELP: std::cout << "run Start emulation" << std::endl << "break <addr> Set breakpoint at <addr>" << std::endl << "step Fetch and execute a single instruction" << std::endl << "continue Resume execution" << std::endl << "help Print a help message" << std::endl << "quit Quit the debugger" << std::endl; break; case CMD_QUIT: std::cerr << "...quitting." << std::endl; return; default: std::cerr << "Invalid command" << std::endl; } } else { // Execute instructions until a breakpoint is found uint16_t PC = emulator->cpu.PC; if (breakPoints.find(PC) != breakPoints.end()) { opts |= DBG_INTERACTIVE; std::cout << "Breakpoint reached: " << std::hex << (int)PC << std::endl; continue; } uint8_t opcode = emulator->cpu.Read(PC); emulator->cpu.Execute(opcode); if (!(opts & DBG_NOGRAPHICS)) SDL_RenderClear(emulator->renderer); ++emulator->cpu.PC; } } } // Reads a command from stdin and returns a struct { cmd, args }. // Currently only takes 1 argument. DebugCmd Debugger::getCommand(const char* prompt) { static DebugCmd latest = { CMD_INVALID }; std::cout << prompt << " " << std::flush; std::string line; std::string instr; DebugCmd cmd; std::getline(std::cin, line); if ((std::cin.rdstate() & std::cin.eofbit) != 0) { cmd.instr = CMD_QUIT; return cmd; } // rtrim spaces line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end()); std::stringstream ss(line); if (line.length() < 1) { if (latest.instr != CMD_INVALID) { // repeat latest command return latest; } else { return getCommand(prompt); } } else { ss >> instr; } if (instr == "run") cmd.instr = CMD_RUN; else if (instr == "break") { cmd.instr = CMD_BREAK; std::string arg; ss >> arg; cmd.args.push_back(arg); } else if (instr == "quit" || instr == "exit") cmd.instr = CMD_QUIT; else if (instr == "step") cmd.instr = CMD_STEP; else if (instr == "cont" || instr == "continue") cmd.instr = CMD_CONTINUE; else if (instr == "help" || instr == "?") cmd.instr = CMD_HELP; else cmd.instr = CMD_INVALID; latest = cmd; return cmd; } void Debugger::setBreakpoint(uint16_t addr) { breakPoints.insert(addr); std::cout << "Set breakpoint to " << std::setfill('0') << std::setw(4) << std::hex << (int)addr << std::endl; } <|endoftext|>
<commit_before>#include <QGraphicsView> #include "fish_annotator/common/annotation_scene.h" namespace fish_annotator { AnnotationScene::AnnotationScene(QObject *parent) : QGraphicsScene(parent) , mode_(kDoNothing) , type_(kBox) , start_pos_() , rect_item_(nullptr) , line_item_(nullptr) , dot_item_(nullptr) { } void AnnotationScene::setToolWidget(AnnotationWidget *widget) { QObject::connect(widget, &AnnotationWidget::setAnnotation, this, &AnnotationScene::setAnnotationType); } void AnnotationScene::setMode(Mode mode) { mode_ = mode; QGraphicsView::DragMode drag; if(mode == kDraw) { makeItemsControllable(false); drag = QGraphicsView::NoDrag; } else if(mode == kSelect) { makeItemsControllable(true); drag = QGraphicsView::RubberBandDrag; } auto view = views().at(0); if(view != nullptr) view->setDragMode(drag); } void AnnotationScene::setAnnotationType(AnnotationType type) { type_ = type; } namespace { // Define pen width in anonymous namespace. static const int pen_width = 7; } void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(mode_ == kDraw) { start_pos_ = event->scenePos(); switch(type_) { case kBox: rect_item_ = new QGraphicsRectItem( start_pos_.x(), start_pos_.y(), 0, 0); rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine)); addItem(rect_item_); break; case kLine: line_item_ = new QGraphicsLineItem(QLineF( start_pos_, start_pos_)); line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine)); addItem(line_item_); break; case kDot: dot_item_ = new QGraphicsEllipseItem( start_pos_.x() - pen_width, start_pos_.y() - pen_width, 2 * pen_width, 2 * pen_width); dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine)); addItem(dot_item_); break; } } QGraphicsScene::mousePressEvent(event); } void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if(mode_ == kDraw) { auto update_pos = event->scenePos(); switch(type_) { case kBox: if(rect_item_ != nullptr) { auto left = qMin(start_pos_.x(), update_pos.x()); auto top = qMin(start_pos_.y(), update_pos.y()); auto width = qAbs(start_pos_.x() - update_pos.x()); auto height = qAbs(start_pos_.y() - update_pos.y()); rect_item_->setRect(QRectF(left, top, width, height)); } break; case kLine: if(line_item_ != nullptr) { line_item_->setLine(QLineF(start_pos_, update_pos)); } break; case kDot: if(dot_item_ != nullptr) { dot_item_->setRect(QRectF( update_pos.x() - pen_width, update_pos.y() - pen_width, 2 * pen_width, 2 * pen_width)); } break; } } QGraphicsScene::mouseMoveEvent(event); } void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if(mode_ == kDraw) { switch(type_) { case kBox: if(rect_item_ != nullptr) { emit boxFinished(rect_item_->rect()); removeItem(rect_item_); rect_item_ = nullptr; } break; case kLine: if(line_item_ != nullptr) { emit lineFinished(line_item_->line()); removeItem(line_item_); line_item_ = nullptr; } break; case kDot: if(dot_item_ != nullptr) { emit dotFinished(QPointF( dot_item_->rect().topLeft().x() + pen_width, dot_item_->rect().topLeft().y() + pen_width)); removeItem(dot_item_); dot_item_ = nullptr; } break; } mode_ = kSelect; } QGraphicsScene::mouseReleaseEvent(event); } void AnnotationScene::makeItemsControllable(bool controllable) { foreach(QGraphicsItem *item, items()) { item->setFlag(QGraphicsItem::ItemIsSelectable, controllable); item->setFlag(QGraphicsItem::ItemIsMovable, controllable); } } #include "../../include/fish_annotator/common/moc_annotation_scene.cpp" } // namespace fish_annotator <commit_msg>Put bounds on annotations near the edge of scene rect. This closes #42.<commit_after>#include <QGraphicsView> #include "fish_annotator/common/annotation_scene.h" namespace fish_annotator { AnnotationScene::AnnotationScene(QObject *parent) : QGraphicsScene(parent) , mode_(kDoNothing) , type_(kBox) , start_pos_() , rect_item_(nullptr) , line_item_(nullptr) , dot_item_(nullptr) { } void AnnotationScene::setToolWidget(AnnotationWidget *widget) { QObject::connect(widget, &AnnotationWidget::setAnnotation, this, &AnnotationScene::setAnnotationType); } void AnnotationScene::setMode(Mode mode) { mode_ = mode; QGraphicsView::DragMode drag; if(mode == kDraw) { makeItemsControllable(false); drag = QGraphicsView::NoDrag; } else if(mode == kSelect) { makeItemsControllable(true); drag = QGraphicsView::RubberBandDrag; } auto view = views().at(0); if(view != nullptr) view->setDragMode(drag); } void AnnotationScene::setAnnotationType(AnnotationType type) { type_ = type; } namespace { // Define pen width in anonymous namespace. static const int pen_width = 7; } void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(mode_ == kDraw && sceneRect().contains(event->scenePos()) == true) { start_pos_ = event->scenePos(); switch(type_) { case kBox: rect_item_ = new QGraphicsRectItem( start_pos_.x(), start_pos_.y(), 0, 0); rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine)); addItem(rect_item_); break; case kLine: line_item_ = new QGraphicsLineItem(QLineF( start_pos_, start_pos_)); line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine)); addItem(line_item_); break; case kDot: dot_item_ = new QGraphicsEllipseItem( start_pos_.x() - pen_width, start_pos_.y() - pen_width, 2 * pen_width, 2 * pen_width); dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine)); addItem(dot_item_); break; } } QGraphicsScene::mousePressEvent(event); } void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if(mode_ == kDraw) { auto update_pos = event->scenePos(); qreal margin; switch(type_) { case kBox: margin = pen_width / 2.0; break; case kLine: margin = pen_width; break; case kDot: margin = 2.0 * pen_width; break; } update_pos.setX(qMin(update_pos.x(), sceneRect().right() - margin)); update_pos.setX(qMax(update_pos.x(), sceneRect().left() + margin)); update_pos.setY(qMin(update_pos.y(), sceneRect().bottom() - margin)); update_pos.setY(qMax(update_pos.y(), sceneRect().top() + margin)); switch(type_) { case kBox: if(rect_item_ != nullptr) { auto left = qMin(start_pos_.x(), update_pos.x()); auto top = qMin(start_pos_.y(), update_pos.y()); auto width = qAbs(start_pos_.x() - update_pos.x()); auto height = qAbs(start_pos_.y() - update_pos.y()); rect_item_->setRect(QRectF(left, top, width, height)); } break; case kLine: if(line_item_ != nullptr) { line_item_->setLine(QLineF(start_pos_, update_pos)); } break; case kDot: if(dot_item_ != nullptr) { dot_item_->setRect(QRectF( update_pos.x() - pen_width, update_pos.y() - pen_width, 2 * pen_width, 2 * pen_width)); } break; } } QGraphicsScene::mouseMoveEvent(event); } void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if(mode_ == kDraw) { switch(type_) { case kBox: if(rect_item_ != nullptr) { emit boxFinished(rect_item_->rect()); removeItem(rect_item_); rect_item_ = nullptr; } break; case kLine: if(line_item_ != nullptr) { emit lineFinished(line_item_->line()); removeItem(line_item_); line_item_ = nullptr; } break; case kDot: if(dot_item_ != nullptr) { emit dotFinished(QPointF( dot_item_->rect().topLeft().x() + pen_width, dot_item_->rect().topLeft().y() + pen_width)); removeItem(dot_item_); dot_item_ = nullptr; } break; } mode_ = kSelect; } QGraphicsScene::mouseReleaseEvent(event); } void AnnotationScene::makeItemsControllable(bool controllable) { foreach(QGraphicsItem *item, items()) { item->setFlag(QGraphicsItem::ItemIsSelectable, controllable); item->setFlag(QGraphicsItem::ItemIsMovable, controllable); } } #include "../../include/fish_annotator/common/moc_annotation_scene.cpp" } // namespace fish_annotator <|endoftext|>
<commit_before>/* * * MIT License * * Copyright (c) 2016-2017 The Cats Project * * 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 CATS_CORECAT_STREAM_BUFFEREDOUTPUTSTREAM_HPP #define CATS_CORECAT_STREAM_BUFFEREDOUTPUTSTREAM_HPP #include <algorithm> #include <vector> #include "OutputStream.hpp" namespace Cats { namespace Corecat { namespace Stream { template <typename T> class BufferedOutputStream : public OutputStream<T> { private: OutputStream<T>* os; std::vector<T> data; std::size_t size = 0; public: BufferedOutputStream(OutputStream<T>& os_) : os(&os_), data(4096) {} BufferedOutputStream(const BufferedOutputStream& src) = delete; BufferedOutputStream(BufferedOutputStream&& src) : os(src.os), data(std::move(src.data)) { src.os = nullptr; } ~BufferedOutputStream() override { flush(); } BufferedOutputStream& operator =(const BufferedOutputStream& src) = delete; BufferedOutputStream& operator =(BufferedOutputStream&& src) { /* TODO */ return *this; } std::size_t writeSome(const T* buffer, std::size_t count) override { if(size + count <= data.size()) std::copy(buffer, buffer + count, data.data() + size), size += count; else { if(size) os->writeAll(data.data(), size); if(data.size() <= count) std::copy(buffer, buffer + count, data.data()), size = count; else os->writeAll(buffer, count), size = 0; } return count; } void flush() override { if(size) os->write(data.data(), size), size = 0; os->flush(); } }; template <typename T> inline BufferedOutputStream<T> createBufferedOutputStream(OutputStream<T>& os) { return BufferedOutputStream<T>(os); } } } } #endif <commit_msg>Update BufferedOutputStream<commit_after>/* * * MIT License * * Copyright (c) 2016-2017 The Cats Project * * 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 CATS_CORECAT_STREAM_BUFFEREDOUTPUTSTREAM_HPP #define CATS_CORECAT_STREAM_BUFFEREDOUTPUTSTREAM_HPP #include <algorithm> #include <vector> #include "OutputStream.hpp" namespace Cats { namespace Corecat { namespace Stream { template <typename T> class BufferedOutputStream : public OutputStream<T> { private: OutputStream<T>* os; std::vector<T> data; std::size_t size = 0; public: BufferedOutputStream(OutputStream<T>& os_) : os(&os_), data(4096) {} BufferedOutputStream(const BufferedOutputStream& src) = delete; BufferedOutputStream(BufferedOutputStream&& src) : os(src.os), data(std::move(src.data)) { src.os = nullptr; } ~BufferedOutputStream() override { flush(); } BufferedOutputStream& operator =(const BufferedOutputStream& src) = delete; BufferedOutputStream& operator =(BufferedOutputStream&& src) { /* TODO */ return *this; } std::size_t writeSome(const T* buffer, std::size_t count) override { if(size + count <= data.size()) std::copy(buffer, buffer + count, data.data() + size), size += count; else { if(size) os->writeAll(data.data(), size); if(count < data.size()) std::copy(buffer, buffer + count, data.data()), size = count; else os->writeAll(buffer, count), size = 0; } return count; } void flush() override { if(size) os->writeAll(data.data(), size), size = 0; os->flush(); } }; template <typename T> inline BufferedOutputStream<T> createBufferedOutputStream(OutputStream<T>& os) { return BufferedOutputStream<T>(os); } } } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_INTERNAL_PRINT_UTILITY_HPP #define TAO_PEGTL_CONTRIB_INTERNAL_PRINT_UTILITY_HPP #include <cassert> #include <cstdio> #include <ostream> #include <string_view> #include "../../config.hpp" #include "../forward.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { inline void print_escape( std::ostream& os, const char32_t i ) { switch( i ) { case '"': os << "\\\""; return; case '\\': os << "\\\\"; return; case '\a': os << "\\a"; return; case '\b': os << "\\b"; return; case '\t': os << "\\t"; return; case '\n': os << "\\n"; return; case '\r': os << "\\r"; return; case '\v': os << "\\v"; return; default: break; } if( ( 32 <= i ) && ( i <= 126 ) ) { os << char( i ); return; } if( i < 0x10000 ) { char b[ 8 ]; const auto s = std::snprintf( b, sizeof( b ), "\\u%04x", i ); os.write( b, s ); return; } if ( i < 0x110000 ) { char b[ 10 ]; const auto s = std::snprintf( b, sizeof( b ), "\\U%06x", i ); os.write( b, s ); return; } assert( false ); // Or what? } inline void print_escape1( std::ostream& os, const char32_t i ) { switch( i ) { case '\'': os << "'\\''"; return; case '\\': os << "'\\\\'"; return; case '\a': os << "'\\a'"; return; case '\b': os << "'\\b'"; return; case '\t': os << "'\\t'"; return; case '\n': os << "'\\n'"; return; case '\r': os << "'\\r'"; return; case '\v': os << "'\\v'"; return; default: break; } if( ( 32 <= i ) && ( i <= 126 ) ) { os << '\'' << char( i ) << '\''; return; } if ( i < 0x110000 ) { char b[ 10 ]; const auto s = std::snprintf( b, sizeof( b ), "U+%X", i ); os.write( b, s ); return; } assert( false ); // Or what? } inline bool is_in_namespace( const std::string_view rule_name, const std::string_view name_space ) noexcept { // TODO: Check whether this needs tweaking for Windows and/or MSVC. return ( rule_name.size() > name_space.size() ) && ( rule_name.compare( 0, name_space.size(), name_space ) == 0 ); } template< typename Rule > void print_rules_rule( std::ostream& os, const std::string_view prefix ) { const std::string_view rule = demangle< Rule >(); if( is_in_namespace( rule, prefix ) ) { os << rule.substr( prefix.size() ); } else { print_rules_traits< typename Rule::rule_t >::print( os, prefix ); } } template< typename Rule, typename... Rules > void print_rules_rules( std::ostream& os, const std::string_view prefix, const char* a, const char* b = "( ", const char* c = ", ", const char* d = " )", const char* e = "" ) { (void)c; os << a << b; ( print_rules_rule< Rule >( os, prefix ), ..., ( os << c, print_rules_rule< Rules >( os, prefix ) ) ); os << d << e; } } // namespace internal } // namespace TAO_PEGTL_NAMESPACE #endif <commit_msg>Reformulate.<commit_after>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_INTERNAL_PRINT_UTILITY_HPP #define TAO_PEGTL_CONTRIB_INTERNAL_PRINT_UTILITY_HPP #include <cassert> #include <cstdio> #include <ostream> #include <string_view> #include "../../config.hpp" #include "../forward.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { inline void print_escape( std::ostream& os, const char32_t i ) { switch( i ) { case '"': os << "\\\""; return; case '\\': os << "\\\\"; return; case '\a': os << "\\a"; return; case '\b': os << "\\b"; return; case '\t': os << "\\t"; return; case '\n': os << "\\n"; return; case '\r': os << "\\r"; return; case '\v': os << "\\v"; return; default: break; } if( ( 32 <= i ) && ( i <= 126 ) ) { os << char( i ); return; } if( i < 0x10000 ) { char b[ 8 ]; const auto s = std::snprintf( b, sizeof( b ), "\\u%04x", i ); os.write( b, s ); return; } if ( i < 0x110000 ) { char b[ 10 ]; const auto s = std::snprintf( b, sizeof( b ), "\\U%06x", i ); os.write( b, s ); return; } assert( false ); // Or what? } inline void print_escape1( std::ostream& os, const char32_t i ) { switch( i ) { case '\'': os << "'\\''"; return; case '\\': os << "'\\\\'"; return; case '\a': os << "'\\a'"; return; case '\b': os << "'\\b'"; return; case '\t': os << "'\\t'"; return; case '\n': os << "'\\n'"; return; case '\r': os << "'\\r'"; return; case '\v': os << "'\\v'"; return; default: break; } if( ( 32 <= i ) && ( i <= 126 ) ) { os << '\'' << char( i ) << '\''; return; } if ( i < 0x110000 ) { char b[ 10 ]; const auto s = std::snprintf( b, sizeof( b ), "U+%X", i ); os.write( b, s ); return; } assert( false ); // Or what? } inline bool is_in_namespace( const std::string_view rule_name, const std::string_view name_space ) noexcept { // TODO: Check whether this needs tweaking for Windows and/or MSVC. return ( rule_name.size() > name_space.size() ) && ( rule_name.compare( 0, name_space.size(), name_space ) == 0 ); } template< typename Rule > void print_rules_rule( std::ostream& os, const std::string_view prefix ) { const std::string_view rule = demangle< Rule >(); if( is_in_namespace( rule, prefix ) ) { os << rule.substr( prefix.size() ); } else { print_rules_traits< typename Rule::rule_t >::print( os, prefix ); } } template< typename Rule, typename... Rules > void print_rules_rules( std::ostream& os, const std::string_view prefix, const char* a, const char* b = "( ", [[maybe_unused]] const char* c = ", ", const char* d = " )", const char* e = "" ) { os << a << b; ( print_rules_rule< Rule >( os, prefix ), ..., ( os << c, print_rules_rule< Rules >( os, prefix ) ) ); os << d << e; } } // namespace internal } // namespace TAO_PEGTL_NAMESPACE #endif <|endoftext|>
<commit_before>#include "pch.h" #include "DspChunk.h" namespace SaneAudioRenderer { static_assert((int32_t{-1} >> 31) == -1 && (int64_t{-1} >> 63) == -1, "Code relies on right signed shift UB"); namespace { template<DspFormat InputFormat, DspFormat OutputFormat> inline void ConvertSample(const typename DspFormatTraits<InputFormat>::SampleType& input, typename DspFormatTraits<OutputFormat>::SampleType& output); template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm8>(const int8_t& input, int8_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm16>(const int8_t& input, int16_t& output) { output = (int16_t)input << 8;; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm24>(const int8_t& input, int32_t& output) { output = (int32_t)input << 16; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm32>(const int8_t& input, int32_t& output) { output = (int32_t)input << 24; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Float>(const int8_t& input, float& output) { output = (float)input / -INT8_MIN; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Double>(const int8_t& input, double& output) { output = (double)input / -INT8_MIN; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm16>(const int16_t& input, int16_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm24>(const int16_t& input, int32_t& output) { output = (int32_t)input << 8; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm32>(const int16_t& input, int32_t& output) { output = (int32_t)input << 16; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Float>(const int16_t& input, float& output) { output = (float)input / -INT16_MIN; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Double>(const int16_t& input, double& output) { output = (double)input / -INT16_MIN; } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm16>(const int32_t& input, int16_t& output) { output = (int16_t)(input >> 8); } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm24>(const int32_t& input, int32_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm32>(const int32_t& input, int32_t& output) { output = input << 8; } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Float>(const int32_t& input, float& output) { output = (float)input / (-INT32_MIN >> 8); } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Double>(const int32_t& input, double& output) { output = (double)input / (-INT32_MIN >> 8); } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm16>(const int32_t& input, int16_t& output) { output = (int16_t)(input >> 16); } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm24>(const int32_t& input, int32_t& output) { output = input >> 8; } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm32>(const int32_t& input, int32_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Float>(const int32_t& input, float& output) { output = (float)input / -INT32_MIN; } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Double>(const int32_t& input, double& output) { output = (double)input / -INT32_MIN; } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Pcm16>(const float& input, int16_t& output) { output = (int16_t)(input * INT16_MAX); } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Pcm24>(const float& input, int32_t& output) { output = (int32_t)(input * (INT32_MAX >> 8)); } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Pcm32>(const float& input, int32_t& output) { output = (int32_t)(input * INT32_MAX); } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Float>(const float& input, float& output) { output = input; } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Double>(const float& input, double& output) { output = input; } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Pcm16>(const double& input, int16_t& output) { output = (int16_t)(input * INT16_MAX); } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Pcm24>(const double& input, int32_t& output) { output = (int32_t)(input * (INT32_MAX >> 8)); } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Pcm32>(const double& input, int32_t& output) { output = (int32_t)(input * INT32_MAX); } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Float>(const double& input, float& output) { output = (float)input; } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Double>(const double& input, double& output) { output = input; } template<DspFormat InputFormat, DspFormat OutputFormat> void ConvertSamples(const char* input, typename DspFormatTraits<OutputFormat>::SampleType* output, size_t samples) { const DspFormatTraits<InputFormat>::SampleType* inputData; inputData = (decltype(inputData))input; for (size_t i = 0; i < samples; i++) ConvertSample<InputFormat, OutputFormat>(inputData[i], output[i]); } template<DspFormat OutputFormat> void ConvertChunk(DspChunk& chunk) { const DspFormat inputFormat = chunk.GetFormat(); assert(!chunk.IsEmpty() && OutputFormat != inputFormat); DspChunk output(OutputFormat, chunk.GetChannelCount(), chunk.GetFrameCount(), chunk.GetRate()); auto outputData = (DspFormatTraits<OutputFormat>::SampleType*)output.GetData(); switch (inputFormat) { case DspFormat::Pcm8: ConvertSamples<DspFormat::Pcm8, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Pcm16: ConvertSamples<DspFormat::Pcm16, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Pcm24: ConvertSamples<DspFormat::Pcm24, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Pcm32: ConvertSamples<DspFormat::Pcm32, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Float: ConvertSamples<DspFormat::Float, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Double: ConvertSamples<DspFormat::Double, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; } chunk = std::move(output); } } void DspChunk::ToFormat(DspFormat format, DspChunk& chunk) { assert(format != DspFormat::Pcm8); if (chunk.IsEmpty() || format == chunk.GetFormat()) return; switch (format) { case DspFormat::Pcm16: ConvertChunk<DspFormat::Pcm16>(chunk); break; case DspFormat::Pcm24: ConvertChunk<DspFormat::Pcm24>(chunk); break; case DspFormat::Pcm32: ConvertChunk<DspFormat::Pcm32>(chunk); break; case DspFormat::Float: ConvertChunk<DspFormat::Float>(chunk); break; case DspFormat::Double: ConvertChunk<DspFormat::Double>(chunk); break; } } DspChunk::DspChunk() : m_format(DspFormat::Pcm16) , m_channels(1) , m_rate(1) , m_dataSize(0) , m_constData(nullptr) , m_delayedCopy(false) { } DspChunk::DspChunk(DspFormat format, uint32_t channels, size_t frames, uint32_t rate) : m_format(format) , m_channels(channels) , m_rate(rate) , m_dataSize(DspFormatSize(format) * channels * frames) , m_constData(nullptr) , m_delayedCopy(false) { Allocate(); } DspChunk::DspChunk(IMediaSample* pSample, const AM_SAMPLE2_PROPERTIES& sampleProps, const WAVEFORMATEX& sampleFormat) : m_mediaSample(pSample) , m_channels(sampleFormat.nChannels) , m_rate(sampleFormat.nSamplesPerSec) , m_dataSize(sampleProps.lActual) , m_constData((char*)sampleProps.pbBuffer) , m_delayedCopy(true) { assert(m_mediaSample); assert(m_constData); if (sampleFormat.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { m_format = (sampleFormat.wBitsPerSample == 32) ? DspFormat::Float : DspFormat::Double; } else if (sampleFormat.wFormatTag == WAVE_FORMAT_PCM) { m_format = (sampleFormat.wBitsPerSample == 8) ? DspFormat::Pcm8 : (sampleFormat.wBitsPerSample == 16) ? DspFormat::Pcm16 : (sampleFormat.wBitsPerSample == 24) ? DspFormat::Pcm24 : DspFormat::Pcm32; } else if (sampleFormat.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { const WAVEFORMATEXTENSIBLE& sampleFormatExtensible = (const WAVEFORMATEXTENSIBLE&)sampleFormat; if (sampleFormatExtensible.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) { m_format = (sampleFormat.wBitsPerSample == 32) ? DspFormat::Float : DspFormat::Double; } else if (sampleFormatExtensible.SubFormat == KSDATAFORMAT_SUBTYPE_PCM) { m_format = (sampleFormat.wBitsPerSample == 8) ? DspFormat::Pcm8 : (sampleFormat.wBitsPerSample == 16) ? DspFormat::Pcm16 : (sampleFormat.wBitsPerSample == 24) ? DspFormat::Pcm24 : DspFormat::Pcm32; } } // Unpack pcm24 samples right away. if (m_format == DspFormat::Pcm24) { m_dataSize = m_dataSize / 3 * 4; Allocate(); for (size_t i = 0, n = GetSampleCount(); i < n; i++) { int32_t x = *(uint16_t*)(m_constData + i * 3); int32_t h = *(uint8_t*)(m_constData + i * 3 + 2); x |= ((h << 24) >> 8); ((int32_t*)m_data.get())[i] = x; } m_delayedCopy = false; } } DspChunk::DspChunk(DspChunk&& other) : m_mediaSample(other.m_mediaSample) , m_format(other.m_format) , m_channels(other.m_channels) , m_rate(other.m_rate) , m_dataSize(other.m_dataSize) , m_constData(other.m_constData) , m_delayedCopy(other.m_delayedCopy) { other.m_mediaSample = nullptr; other.m_dataSize = 0; std::swap(m_data, other.m_data); } DspChunk& DspChunk::operator=(DspChunk&& other) { if (this != &other) { m_mediaSample = other.m_mediaSample; other.m_mediaSample = nullptr; m_format = other.m_format; m_channels = other.m_channels; m_rate = other.m_rate; m_dataSize = other.m_dataSize; other.m_dataSize = 0; m_constData = other.m_constData; m_delayedCopy = other.m_delayedCopy; m_data = nullptr; std::swap(m_data, other.m_data); } return *this; } char* DspChunk::GetData() { InvokeDelayedCopy(); return m_data.get(); } void DspChunk::Shrink(size_t toFrames) { if (toFrames < GetFrameCount()) { InvokeDelayedCopy(); m_dataSize = GetFormatSize() * GetChannelCount() * toFrames; } } void DspChunk::Allocate() { if (m_dataSize > 0) { m_data.reset((char*)_aligned_malloc(m_dataSize, 16)); if (!m_data.get()) throw std::bad_alloc(); } } void DspChunk::InvokeDelayedCopy() { if (m_delayedCopy) { Allocate(); assert(m_constData); memcpy(m_data.get(), m_constData, m_dataSize); m_delayedCopy = false; } } } <commit_msg>Fix phase shift in format conversion<commit_after>#include "pch.h" #include "DspChunk.h" namespace SaneAudioRenderer { static_assert((int32_t{-1} >> 31) == -1 && (int64_t{-1} >> 63) == -1, "Code relies on right signed shift UB"); namespace { template<DspFormat InputFormat, DspFormat OutputFormat> inline void ConvertSample(const typename DspFormatTraits<InputFormat>::SampleType& input, typename DspFormatTraits<OutputFormat>::SampleType& output); template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm8>(const int8_t& input, int8_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm16>(const int8_t& input, int16_t& output) { output = (int16_t)input << 8;; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm24>(const int8_t& input, int32_t& output) { output = (int32_t)input << 16; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Pcm32>(const int8_t& input, int32_t& output) { output = (int32_t)input << 24; } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Float>(const int8_t& input, float& output) { output = (float)input / ((int32_t)INT8_MAX + 1); } template<> inline void ConvertSample<DspFormat::Pcm8, DspFormat::Double>(const int8_t& input, double& output) { output = (double)input / ((int32_t)INT8_MAX + 1); } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm16>(const int16_t& input, int16_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm24>(const int16_t& input, int32_t& output) { output = (int32_t)input << 8; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Pcm32>(const int16_t& input, int32_t& output) { output = (int32_t)input << 16; } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Float>(const int16_t& input, float& output) { output = (float)input / ((int32_t)INT16_MAX + 1); } template<> inline void ConvertSample<DspFormat::Pcm16, DspFormat::Double>(const int16_t& input, double& output) { output = (double)input / ((int32_t)INT16_MAX + 1); } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm16>(const int32_t& input, int16_t& output) { output = (int16_t)(input >> 8); } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm24>(const int32_t& input, int32_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Pcm32>(const int32_t& input, int32_t& output) { output = input << 8; } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Float>(const int32_t& input, float& output) { output = (float)input / ((INT32_MAX >> 8) + 1); } template<> inline void ConvertSample<DspFormat::Pcm24, DspFormat::Double>(const int32_t& input, double& output) { output = (double)input / ((INT32_MAX >> 8) + 1); } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm16>(const int32_t& input, int16_t& output) { output = (int16_t)(input >> 16); } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm24>(const int32_t& input, int32_t& output) { output = input >> 8; } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Pcm32>(const int32_t& input, int32_t& output) { output = input; } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Float>(const int32_t& input, float& output) { output = (float)input / ((int64_t)INT32_MAX + 1); } template<> inline void ConvertSample<DspFormat::Pcm32, DspFormat::Double>(const int32_t& input, double& output) { output = (double)input / ((int64_t)INT32_MAX + 1); } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Pcm16>(const float& input, int16_t& output) { output = (int16_t)(input * INT16_MAX); } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Pcm24>(const float& input, int32_t& output) { output = (int32_t)(input * (INT32_MAX >> 8)); } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Pcm32>(const float& input, int32_t& output) { output = (int32_t)(input * INT32_MAX); } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Float>(const float& input, float& output) { output = input; } template<> inline void ConvertSample<DspFormat::Float, DspFormat::Double>(const float& input, double& output) { output = input; } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Pcm16>(const double& input, int16_t& output) { output = (int16_t)(input * INT16_MAX); } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Pcm24>(const double& input, int32_t& output) { output = (int32_t)(input * (INT32_MAX >> 8)); } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Pcm32>(const double& input, int32_t& output) { output = (int32_t)(input * INT32_MAX); } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Float>(const double& input, float& output) { output = (float)input; } template<> inline void ConvertSample<DspFormat::Double, DspFormat::Double>(const double& input, double& output) { output = input; } template<DspFormat InputFormat, DspFormat OutputFormat> void ConvertSamples(const char* input, typename DspFormatTraits<OutputFormat>::SampleType* output, size_t samples) { const DspFormatTraits<InputFormat>::SampleType* inputData; inputData = (decltype(inputData))input; for (size_t i = 0; i < samples; i++) ConvertSample<InputFormat, OutputFormat>(inputData[i], output[i]); } template<DspFormat OutputFormat> void ConvertChunk(DspChunk& chunk) { const DspFormat inputFormat = chunk.GetFormat(); assert(!chunk.IsEmpty() && OutputFormat != inputFormat); DspChunk output(OutputFormat, chunk.GetChannelCount(), chunk.GetFrameCount(), chunk.GetRate()); auto outputData = (DspFormatTraits<OutputFormat>::SampleType*)output.GetData(); switch (inputFormat) { case DspFormat::Pcm8: ConvertSamples<DspFormat::Pcm8, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Pcm16: ConvertSamples<DspFormat::Pcm16, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Pcm24: ConvertSamples<DspFormat::Pcm24, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Pcm32: ConvertSamples<DspFormat::Pcm32, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Float: ConvertSamples<DspFormat::Float, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; case DspFormat::Double: ConvertSamples<DspFormat::Double, OutputFormat>(chunk.GetConstData(), outputData, chunk.GetSampleCount()); break; } chunk = std::move(output); } } void DspChunk::ToFormat(DspFormat format, DspChunk& chunk) { assert(format != DspFormat::Pcm8); if (chunk.IsEmpty() || format == chunk.GetFormat()) return; switch (format) { case DspFormat::Pcm16: ConvertChunk<DspFormat::Pcm16>(chunk); break; case DspFormat::Pcm24: ConvertChunk<DspFormat::Pcm24>(chunk); break; case DspFormat::Pcm32: ConvertChunk<DspFormat::Pcm32>(chunk); break; case DspFormat::Float: ConvertChunk<DspFormat::Float>(chunk); break; case DspFormat::Double: ConvertChunk<DspFormat::Double>(chunk); break; } } DspChunk::DspChunk() : m_format(DspFormat::Pcm16) , m_channels(1) , m_rate(1) , m_dataSize(0) , m_constData(nullptr) , m_delayedCopy(false) { } DspChunk::DspChunk(DspFormat format, uint32_t channels, size_t frames, uint32_t rate) : m_format(format) , m_channels(channels) , m_rate(rate) , m_dataSize(DspFormatSize(format) * channels * frames) , m_constData(nullptr) , m_delayedCopy(false) { Allocate(); } DspChunk::DspChunk(IMediaSample* pSample, const AM_SAMPLE2_PROPERTIES& sampleProps, const WAVEFORMATEX& sampleFormat) : m_mediaSample(pSample) , m_channels(sampleFormat.nChannels) , m_rate(sampleFormat.nSamplesPerSec) , m_dataSize(sampleProps.lActual) , m_constData((char*)sampleProps.pbBuffer) , m_delayedCopy(true) { assert(m_mediaSample); assert(m_constData); if (sampleFormat.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { m_format = (sampleFormat.wBitsPerSample == 32) ? DspFormat::Float : DspFormat::Double; } else if (sampleFormat.wFormatTag == WAVE_FORMAT_PCM) { m_format = (sampleFormat.wBitsPerSample == 8) ? DspFormat::Pcm8 : (sampleFormat.wBitsPerSample == 16) ? DspFormat::Pcm16 : (sampleFormat.wBitsPerSample == 24) ? DspFormat::Pcm24 : DspFormat::Pcm32; } else if (sampleFormat.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { const WAVEFORMATEXTENSIBLE& sampleFormatExtensible = (const WAVEFORMATEXTENSIBLE&)sampleFormat; if (sampleFormatExtensible.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) { m_format = (sampleFormat.wBitsPerSample == 32) ? DspFormat::Float : DspFormat::Double; } else if (sampleFormatExtensible.SubFormat == KSDATAFORMAT_SUBTYPE_PCM) { m_format = (sampleFormat.wBitsPerSample == 8) ? DspFormat::Pcm8 : (sampleFormat.wBitsPerSample == 16) ? DspFormat::Pcm16 : (sampleFormat.wBitsPerSample == 24) ? DspFormat::Pcm24 : DspFormat::Pcm32; } } // Unpack pcm24 samples right away. if (m_format == DspFormat::Pcm24) { m_dataSize = m_dataSize / 3 * 4; Allocate(); for (size_t i = 0, n = GetSampleCount(); i < n; i++) { int32_t x = *(uint16_t*)(m_constData + i * 3); int32_t h = *(uint8_t*)(m_constData + i * 3 + 2); x |= ((h << 24) >> 8); ((int32_t*)m_data.get())[i] = x; } m_delayedCopy = false; } } DspChunk::DspChunk(DspChunk&& other) : m_mediaSample(other.m_mediaSample) , m_format(other.m_format) , m_channels(other.m_channels) , m_rate(other.m_rate) , m_dataSize(other.m_dataSize) , m_constData(other.m_constData) , m_delayedCopy(other.m_delayedCopy) { other.m_mediaSample = nullptr; other.m_dataSize = 0; std::swap(m_data, other.m_data); } DspChunk& DspChunk::operator=(DspChunk&& other) { if (this != &other) { m_mediaSample = other.m_mediaSample; other.m_mediaSample = nullptr; m_format = other.m_format; m_channels = other.m_channels; m_rate = other.m_rate; m_dataSize = other.m_dataSize; other.m_dataSize = 0; m_constData = other.m_constData; m_delayedCopy = other.m_delayedCopy; m_data = nullptr; std::swap(m_data, other.m_data); } return *this; } char* DspChunk::GetData() { InvokeDelayedCopy(); return m_data.get(); } void DspChunk::Shrink(size_t toFrames) { if (toFrames < GetFrameCount()) { InvokeDelayedCopy(); m_dataSize = GetFormatSize() * GetChannelCount() * toFrames; } } void DspChunk::Allocate() { if (m_dataSize > 0) { m_data.reset((char*)_aligned_malloc(m_dataSize, 16)); if (!m_data.get()) throw std::bad_alloc(); } } void DspChunk::InvokeDelayedCopy() { if (m_delayedCopy) { Allocate(); assert(m_constData); memcpy(m_data.get(), m_constData, m_dataSize); m_delayedCopy = false; } } } <|endoftext|>
<commit_before>#include <cstdint> #include <fstream> #include <vector> #ifdef EMSCRIPTEN #include <emscripten/emscripten.h> #endif #include "wonderland.storage.detail/base64_helper.hxx" namespace wonder_rabbit_project { namespace wonderland { namespace storage { template < class T = void > auto save( const std::string& path, const std::vector< char >& data ) -> void { #ifndef EMSCRIPTEN // PC: standard filesystem std::ofstream f; f.exceptions( std::ofstream::failbit | std::ofstream::badbit ); f.open( path, std::ofstream::binary ); f.write( data.data(), data.size() ); #else const auto base64_data = base64_helper::base64_encode( data ); // Emscripten: Web Storage std::string asm_code; asm_code += "try {"; asm_code += "localStorage.setItem( '"; asm_code += path; asm_code += "', '"; asm_code += base64_data; asm_code += "' );"; asm_code += "} catch ( e ) { 1; } 0;"; const auto result = emscripten_run_script_int( asm_code.data() ); if ( result != 0 ) throw std::ios_base::failure("fail writing(on the Web Local Storage)"); #endif } template < class T = void > auto save( const std::string& path, const std::string& data ) -> void { save( path, std::vector< char >( std::begin( data ), std::end( data ) ) ); } template < class T = void > auto save( const std::string& path, const char* data ) -> void { std::string buffer( data ); save( path, buffer ); } template < class T = void > auto save( const std::string& path, const void* data, std::size_t size ) -> void { const auto begin = reinterpret_cast< const char* >( data ); const auto end = begin + size; save( path, std::vector< char >( begin, end ) ); } template < class T > auto save( const std::string& path, const T& data ) -> void { const auto begin = reinterpret_cast< const char* >( &data ); const auto end = begin + sizeof( T ); save( path, std::vector< char >( begin, end ) ); } template < class T = std::string > auto load( const std::string& path ) -> T { const auto buffer = load< std::string >( path ); // cannot the method, its take an unexptected value on Emscripten-1.16.0. // https://github.com/kripken/emscripten/issues/2346 //return *reinterpret_cast< const T* >( buffer.data() ); // the alternative method is ok on Emscripten-1.16.0. T result; std::copy( std::begin( buffer ), std::end( buffer ), reinterpret_cast<char*>(&result) ); return result; } template < > auto load< std::string >( const std::string& path ) -> std::string { #ifndef EMSCRIPTEN // PC: standard filesystem std::ifstream f; f.exceptions( std::ifstream::failbit | std::ifstream::badbit ); f.open( path, std::ifstream::binary ); f.seekg( 0, std::ifstream::end ); const auto size = f.tellg(); f.seekg( 0, std::ifstream::beg ); std::string buffer; buffer.resize( size ); f.read( const_cast< char* >( buffer.data() ), size ); #else // Emscripten: Web Storage std::string asm_code; asm_code += "localStorage.getItem( '"; asm_code += path; asm_code += "' );"; std::string buffer = emscripten_run_script_string( asm_code.data() ); if ( buffer == "null" ) throw std::ios_base::failure("file not found(on the Web Local Storage)"); buffer = base64_helper::base64_decode( buffer ); #endif return buffer; } } } }<commit_msg>std::vector<std::uint8_t>でデータ取得できるように対応<commit_after>#include <cstdint> #include <fstream> #include <vector> #ifdef EMSCRIPTEN #include <emscripten/emscripten.h> #endif #include "wonderland.storage.detail/base64_helper.hxx" namespace wonder_rabbit_project { namespace wonderland { namespace storage { template < class T = void > auto save( const std::string& path, const std::vector< char >& data ) -> void { #ifndef EMSCRIPTEN // PC: standard filesystem std::ofstream f; f.exceptions( std::ofstream::failbit | std::ofstream::badbit ); f.open( path, std::ofstream::binary ); f.write( data.data(), data.size() ); #else const auto base64_data = base64_helper::base64_encode( data ); // Emscripten: Web Storage std::string asm_code; asm_code += "try {"; asm_code += "localStorage.setItem( '"; asm_code += path; asm_code += "', '"; asm_code += base64_data; asm_code += "' );"; asm_code += "} catch ( e ) { 1; } 0;"; const auto result = emscripten_run_script_int( asm_code.data() ); if ( result != 0 ) throw std::ios_base::failure("fail writing(on the Web Local Storage)"); #endif } template < class T = void > auto save( const std::string& path, const std::string& data ) -> void { save( path, std::vector< char >( std::begin( data ), std::end( data ) ) ); } template < class T = void > auto save( const std::string& path, const char* data ) -> void { std::string buffer( data ); save( path, buffer ); } template < class T = void > auto save( const std::string& path, const void* data, std::size_t size ) -> void { const auto begin = reinterpret_cast< const char* >( data ); const auto end = begin + size; save( path, std::vector< char >( begin, end ) ); } template < class T > auto save( const std::string& path, const T& data ) -> void { const auto begin = reinterpret_cast< const char* >( &data ); const auto end = begin + sizeof( T ); save( path, std::vector< char >( begin, end ) ); } template < class T = std::string > auto load( const std::string& path ) -> T { const auto buffer = load< std::string >( path ); // cannot the method, its take an unexptected value on Emscripten-1.16.0. // https://github.com/kripken/emscripten/issues/2346 //return *reinterpret_cast< const T* >( buffer.data() ); // the alternative method is ok on Emscripten-1.16.0. T result; std::copy( std::begin( buffer ), std::end( buffer ), reinterpret_cast<char*>(&result) ); return result; } template < > auto load< std::string >( const std::string& path ) -> std::string { #ifndef EMSCRIPTEN // PC: standard filesystem std::ifstream f; f.exceptions( std::ifstream::failbit | std::ifstream::badbit ); f.open( path, std::ifstream::binary ); f.seekg( 0, std::ifstream::end ); const auto size = f.tellg(); f.seekg( 0, std::ifstream::beg ); std::string buffer; buffer.resize( size ); f.read( const_cast< char* >( buffer.data() ), size ); #else // Emscripten: Web Storage std::string asm_code; asm_code += "localStorage.getItem( '"; asm_code += path; asm_code += "' );"; std::string buffer = emscripten_run_script_string( asm_code.data() ); if ( buffer == "null" ) throw std::ios_base::failure("file not found(on the Web Local Storage)"); buffer = base64_helper::base64_decode( buffer ); #endif return buffer; } template < > auto load< std::vector< std::uint8_t > > ( const std::string& path ) -> std::vector< std::uint8_t > { const auto buffer = load< std::string >( path ); return { buffer.cbegin(), buffer.cend() }; } } } }<|endoftext|>
<commit_before>#include "core/Apportionment.hpp" #include <algorithm> #include <random> Apportionment::Apportionment( PopulationNode * upperNode, ApportionmentFunction * apportionment, AggregationFunction * aggregator ) { // TODO: Empirically determine a sane default for try-on count this->init( upperNode, apportionment, aggregator, upperNode->populationSize() ); } Apportionment::Apportionment( PopulationNode * upperNode, ApportionmentFunction * apportionment, AggregationFunction * aggregator, unsigned int tryOns ) { this->init(upperNode, apportionment, aggregator, tryOns); } Apportionment::~Apportionment() {} void Apportionment::init( PopulationNode * upperNode, ApportionmentFunction * apportionment, AggregationFunction * aggregator, unsigned int tryOns ) { this->upperNode = upperNode; this->apportionment = apportionment; this->aggregator = aggregator; this->tryOns = tryOns; } Genome * Apportionment::getOperableGenome(Genome * genome) { return new Genome(genome->flattenGenome()); } std::vector<unsigned int> Apportionment::getComponentIndices( Genome * upper, Genome * target ) { return upper->getFlattenedIndices(target); } void Apportionment::evaluatePair( Genome * upper, Genome * target, int upperFitness, std::vector<int> & apportionedFitnesses ) { std::vector<unsigned int> componentIndices = this->getComponentIndices(upper, target); Genome * provider = this->getOperableGenome(upper); Genome flattened = target->flattenGenome(); for (unsigned int i = 0; i < componentIndices.size(); i++) apportionedFitnesses.push_back( this->apportionment->apportionFitness( &flattened, provider, componentIndices[i], upperFitness ) ); delete(provider); } // TODO: Refactor this function int Apportionment::checkFitness(Genome * genome) { std::vector<int> apportionedFitnesses; std::vector<bool> tried(this->upperNode->populationSize(), false); unsigned int triedOn = 0; for (unsigned int i = 0; i < this->upperNode->populationSize(); i++) if (this->upperNode->getIndex(i)->usesComponent(genome)) { this->evaluatePair( this->upperNode->getIndex(i), genome, this->upperNode->getFitnessAtIndex(i), apportionedFitnesses ); triedOn++; tried[i] = true; } std::vector<unsigned int> untriedIndices; for (unsigned int i = 0; i < tried.size(); i++) if (!tried[i]) untriedIndices.push_back(i); // TODO: Refactor this into the class def mt19937 generator; unsigned int tryOns = std::min( this->upperNode->populationSize(), this->tryOns ); unsigned int index; while (triedOn < tryOns) { uniform_int_distribution<unsigned int> selDist( 0, untriedIndices.size() - 1 ); index = selDist(generator); Genome * provider = this->upperNode ->getIndex(untriedIndices[index]) ->replaceComponent(genome); this->evaluatePair( provider, genome, this->upperNode->evaluateFitness(provider), apportionedFitnesses ); delete(provider); untriedIndices.erase(untriedIndices.begin() + index); triedOn++; } return this->aggregateFitnesses(apportionedFitnesses); } int Apportionment::aggregateFitnesses(std::vector<int> apportionedFitnesses) { return this->aggregator->aggregateFitnesses(apportionedFitnesses); } bool Apportionment::isApportioning() { return true; } ApportionmentFunction * Apportionment::getApportionmentFunction() { return this->apportionment; } AggregationFunction * Apportionment::getAggregationFunction() { return this->aggregator; } <commit_msg>[Apportionment]: Made code a little clearer<commit_after>#include "core/Apportionment.hpp" #include <algorithm> #include <random> Apportionment::Apportionment( PopulationNode * upperNode, ApportionmentFunction * apportionment, AggregationFunction * aggregator ) { // TODO: Empirically determine a sane default for try-on count this->init( upperNode, apportionment, aggregator, upperNode->populationSize() ); } Apportionment::Apportionment( PopulationNode * upperNode, ApportionmentFunction * apportionment, AggregationFunction * aggregator, unsigned int tryOns ) { this->init(upperNode, apportionment, aggregator, tryOns); } Apportionment::~Apportionment() {} void Apportionment::init( PopulationNode * upperNode, ApportionmentFunction * apportionment, AggregationFunction * aggregator, unsigned int tryOns ) { this->upperNode = upperNode; this->apportionment = apportionment; this->aggregator = aggregator; this->tryOns = tryOns; } Genome * Apportionment::getOperableGenome(Genome * genome) { return new Genome(genome->flattenGenome()); } std::vector<unsigned int> Apportionment::getComponentIndices( Genome * upper, Genome * target ) { return upper->getFlattenedIndices(target); } void Apportionment::evaluatePair( Genome * upper, Genome * target, int upperFitness, std::vector<int> & apportionedFitnesses ) { std::vector<unsigned int> componentIndices = this->getComponentIndices(upper, target); Genome * provider = this->getOperableGenome(upper); Genome flattened = target->flattenGenome(); for (unsigned int i = 0; i < componentIndices.size(); i++) apportionedFitnesses.push_back( this->apportionment->apportionFitness( &flattened, provider, componentIndices[i], upperFitness ) ); delete(provider); } // TODO: Refactor this function int Apportionment::checkFitness(Genome * genome) { std::vector<int> apportionedFitnesses; std::vector<bool> tried(this->upperNode->populationSize(), false); unsigned int triedOn = 0; for (unsigned int i = 0; i < this->upperNode->populationSize(); i++) if (this->upperNode->getIndex(i)->usesComponent(genome)) { this->evaluatePair( this->upperNode->getIndex(i), genome, this->upperNode->getFitnessAtIndex(i), apportionedFitnesses ); triedOn++; tried[i] = true; } std::vector<unsigned int> untriedIndices; for (unsigned int i = 0; i < tried.size(); i++) if (!tried[i]) untriedIndices.push_back(i); // TODO: Refactor this into the class def mt19937 generator; unsigned int realTryOns = std::min( this->upperNode->populationSize(), this->tryOns ); unsigned int index; while (triedOn < realTryOns) { uniform_int_distribution<unsigned int> selDist( 0, untriedIndices.size() - 1 ); index = selDist(generator); Genome * provider = this->upperNode ->getIndex(untriedIndices[index]) ->replaceComponent(genome); this->evaluatePair( provider, genome, this->upperNode->evaluateFitness(provider), apportionedFitnesses ); delete(provider); untriedIndices.erase(untriedIndices.begin() + index); triedOn++; } return this->aggregateFitnesses(apportionedFitnesses); } int Apportionment::aggregateFitnesses(std::vector<int> apportionedFitnesses) { return this->aggregator->aggregateFitnesses(apportionedFitnesses); } bool Apportionment::isApportioning() { return true; } ApportionmentFunction * Apportionment::getApportionmentFunction() { return this->apportionment; } AggregationFunction * Apportionment::getAggregationFunction() { return this->aggregator; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2011 Instituto Nokia de Tecnologia (INdT) * * * * 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. * * * * 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 Lesser General Public License for more details. * ****************************************************************************/ #include "BookmarkModel.h" #include <QtSql/QSqlError> #include <QtSql/QSqlQuery> #include <QtSql/QSqlRecord> BookmarkModel::BookmarkModel(QSqlDatabase database, QObject *parent) : QSqlTableModel(parent, database) { connect(this, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SIGNAL(countChanged())); connect(this, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), SIGNAL(countChanged())); setEditStrategy(OnManualSubmit); } void BookmarkModel::generateRoleNames() { for (int i = 0; i < this->columnCount(); i++) m_roles[Qt::UserRole + i] = this->headerData(i, Qt::Horizontal).toByteArray(); setRoleNames(m_roles); } QString BookmarkModel::tableCreateQuery() const { const QLatin1String bookmarkQuery("CREATE TABLE IF NOT EXISTS bookmarks (id INTEGER PRIMARY KEY AUTOINCREMENT," "name VARCHAR, url VARCHAR, dateAdded DATE);"); return bookmarkQuery; } void BookmarkModel::setFilter(const QString& filter) { QSqlTableModel::setFilter(filter); } bool BookmarkModel::select() { return QSqlTableModel::select(); } void BookmarkModel::insert(const QString& name, const QString& url) { if (contains(url)) return; QSqlRecord record = this->record(); record.setValue(QLatin1String("name"), name); record.setValue(QLatin1String("url"), url); insertRecord(-1, record); submitAll(); } void BookmarkModel::remove(const QString& url) { if (!contains(url)) return; QSqlQuery sqlQuery(database()); sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?")); sqlQuery.addBindValue(url); sqlQuery.exec(); sqlQuery.first(); int indexToDelete = -1; for (int row = 0; row < rowCount(); ++row) { if (index(row, 0).data(Qt::DisplayRole).toInt() == sqlQuery.value(0).toInt()) { indexToDelete = row; break; } } if (indexToDelete >= 0) { removeRow(indexToDelete); submitAll(); } } void BookmarkModel::togglePin(const QString& url) { if (contains(url)) remove(url); else insert(url, url); } void BookmarkModel::update(int index, const QString& name, const QString& url) { setData(this->index(index, 1), name); setData(this->index(index, 2), url); } bool BookmarkModel::contains(const QString& url) { QSqlQuery sqlQuery(database()); sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?")); sqlQuery.addBindValue(url); sqlQuery.exec(); return sqlQuery.first(); } QVariant BookmarkModel::data(const QModelIndex& index, int role) const { QVariant value; if (role < Qt::UserRole) value = QSqlQueryModel::data(index, role); else { const int columnId = role - Qt::UserRole; const QModelIndex modelIndex = this->index(index.row(), columnId); value = QSqlTableModel::data(modelIndex, Qt::DisplayRole); } return value; } <commit_msg>BookmarkModel should advertise when removing items.<commit_after>/**************************************************************************** * Copyright (C) 2011 Instituto Nokia de Tecnologia (INdT) * * * * 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. * * * * 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 Lesser General Public License for more details. * ****************************************************************************/ #include "BookmarkModel.h" #include <QtSql/QSqlError> #include <QtSql/QSqlQuery> #include <QtSql/QSqlRecord> BookmarkModel::BookmarkModel(QSqlDatabase database, QObject *parent) : QSqlTableModel(parent, database) { connect(this, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SIGNAL(countChanged())); connect(this, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), SIGNAL(countChanged())); setEditStrategy(OnManualSubmit); } void BookmarkModel::generateRoleNames() { for (int i = 0; i < this->columnCount(); i++) m_roles[Qt::UserRole + i] = this->headerData(i, Qt::Horizontal).toByteArray(); setRoleNames(m_roles); } QString BookmarkModel::tableCreateQuery() const { const QLatin1String bookmarkQuery("CREATE TABLE IF NOT EXISTS bookmarks (id INTEGER PRIMARY KEY AUTOINCREMENT," "name VARCHAR, url VARCHAR, dateAdded DATE);"); return bookmarkQuery; } void BookmarkModel::setFilter(const QString& filter) { QSqlTableModel::setFilter(filter); } bool BookmarkModel::select() { return QSqlTableModel::select(); } void BookmarkModel::insert(const QString& name, const QString& url) { if (contains(url)) return; QSqlRecord record = this->record(); record.setValue(QLatin1String("name"), name); record.setValue(QLatin1String("url"), url); insertRecord(-1, record); submitAll(); } void BookmarkModel::remove(const QString& url) { if (!contains(url)) return; QSqlQuery sqlQuery(database()); sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?")); sqlQuery.addBindValue(url); sqlQuery.exec(); sqlQuery.first(); int indexToDelete = -1; for (int row = 0; row < rowCount(); ++row) { if (index(row, 0).data(Qt::DisplayRole).toInt() == sqlQuery.value(0).toInt()) { indexToDelete = row; break; } } if (indexToDelete >= 0) { beginRemoveRows(QModelIndex(), indexToDelete, indexToDelete); removeRow(indexToDelete); submitAll(); endRemoveRows(); } } void BookmarkModel::togglePin(const QString& url) { if (contains(url)) remove(url); else insert(url, url); } void BookmarkModel::update(int index, const QString& name, const QString& url) { setData(this->index(index, 1), name); setData(this->index(index, 2), url); } bool BookmarkModel::contains(const QString& url) { QSqlQuery sqlQuery(database()); sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?")); sqlQuery.addBindValue(url); sqlQuery.exec(); return sqlQuery.first(); } QVariant BookmarkModel::data(const QModelIndex& index, int role) const { QVariant value; if (role < Qt::UserRole) value = QSqlQueryModel::data(index, role); else { const int columnId = role - Qt::UserRole; const QModelIndex modelIndex = this->index(index.row(), columnId); value = QSqlTableModel::data(modelIndex, Qt::DisplayRole); } return value; } <|endoftext|>
<commit_before>/* * stream.hpp * * Created on: Mar 1, 2015 * Author: hugo */ #ifndef MFLASH_CPP_CORE_MAPPED_STREAM_HPP_ #define MFLASH_CPP_CORE_MAPPED_STREAM_HPP_ #include <fcntl.h> #include <stdio.h> #include <sys/mman.h> #include <unistd.h> #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <boost/interprocess/mapped_region.hpp> #include "../core/type.hpp" #include "../core/util.hpp" using namespace std; namespace mflash{ /** * It creates a stream using memory mapping for reading files in sequential mode. * The first implementation suppose that we can map whole file. */ class MappedStream{ const static int64 CHAR_SIZE = (int64)sizeof(char); const static int64 INT_SIZE = (int64)sizeof(int); const static int64 INT64_SIZE = (int64)sizeof(int64); const static int64 FLOAT_SIZE = (int64)sizeof(float); const static int64 DOUBLE_SIZE = (int64)sizeof(double); int64 PAGE_SIZE = boost::interprocess::mapped_region::get_page_size(); public: string file; int64 offset; int64 size; char *ptr; char *current_ptr; char *last_ptr; int file_id; bool reverse; MappedStream(string file, int64 offset, int64 size); MappedStream(string file): MappedStream(file, 0,0){}; int64 position(); void set_position(int64 position); char next(); int next_int(); int next_int(int64 step); char* next(int64 bytes, int64 step = 0); bool has_remain(); void close_stream(); }; inline MappedStream::MappedStream(string file, int64 offset, int64 size){ this->file = file; this->offset = offset; //this->opposite_direction = opposite_direction; if(size <=0){ size = file_size(file); } //PAGE ALIGNMENT int64 bytes_align = offset %PAGE_SIZE; offset -= bytes_align; size += bytes_align; this->size = size; reverse = false; file_id = open(this->file.c_str(), O_RDONLY); if (file_id == -1) { perror("Error opening file for reading"); exit(EXIT_FAILURE); } //cout<< file << endl; //cout<< sizeof(size_t)<<endl; ptr = (char*) mmap(0, size , PROT_READ, MAP_SHARED, file_id, offset); //MOVING POINTER TO THE FIRST POSITION OF THE OFFSET //if(!opposite_direction){ current_ptr = ptr + bytes_align; last_ptr = ptr + size; /*}else{ last_ptr = ptr + bytes_align; current_ptr = ptr + size; }*/ if (ptr == MAP_FAILED) { close(file_id); perror("Error mmapping the file"); exit(EXIT_FAILURE); } } inline bool MappedStream::has_remain(){ return /*opposite_direction? current_ptr > last_ptr : */current_ptr < last_ptr; } inline char* MappedStream::next(int64 bytes, int64 step){ char* ptr; //if(!opposite_direction){ ptr = current_ptr; current_ptr += bytes + step; /*}else{ ptr = current_ptr - bytes; current_ptr -= (bytes + step); }*/ return ptr; } inline int MappedStream::next_int(){ return next_int(0); } inline char MappedStream::next(){ return *( (char*) next(CHAR_SIZE, 0) ); } inline int MappedStream::next_int(int64 step){ return *( (int*) next(INT_SIZE, step) ); //int v = *( (int*) next(INT_SIZE, step) ); /*if(reverse) return ((v >> 24) & 0xFF) +(((v >> 16) & 0xFF) << 8) +(((v >> 8) & 0xFF) << 16) + ((v & 0xFF) << 24);*/ // return v; } /* inline int64 Stream::next_int64(){ return (int)*( next(INT64_SIZE) ); }*/ /*inline float Stream::next_float(){ return (float)*( next(FLOAT_SIZE) ); } inline double Stream::next_double(){ return (double)*( next(DOUBLE_SIZE) ); }*/ inline int64 MappedStream::position(){ return current_ptr - ptr; } inline void MappedStream::set_position(int64 position){ char* p = position + ptr; if(p> ptr && p< last_ptr){ current_ptr = p; } } inline void MappedStream::close_stream(){ if (munmap(ptr, size) == -1) { perror("Error un-mmapping the file"); } close(file_id); } } #endif /* MFLASH_CPP_CORE_MAPPED_STREAM_HPP_ */ <commit_msg>Adding support for custom types to MappedStream<commit_after>/* * stream.hpp * * Created on: Mar 1, 2015 * Author: hugo */ #ifndef MFLASH_CPP_CORE_MAPPED_STREAM_HPP_ #define MFLASH_CPP_CORE_MAPPED_STREAM_HPP_ #include <fcntl.h> #include <stdio.h> #include <sys/mman.h> #include <unistd.h> #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <boost/interprocess/mapped_region.hpp> #include "../core/type.hpp" #include "../core/util.hpp" using namespace std; namespace mflash{ /** * It creates a stream using memory mapping for reading files in sequential mode. * The first implementation suppose that we can map whole file. */ class MappedStream{ const static int64 CHAR_SIZE = (int64)sizeof(char); const static int64 INT_SIZE = (int64)sizeof(int); const static int64 INT64_SIZE = (int64)sizeof(int64); const static int64 FLOAT_SIZE = (int64)sizeof(float); const static int64 DOUBLE_SIZE = (int64)sizeof(double); int64 PAGE_SIZE = boost::interprocess::mapped_region::get_page_size(); public: string file; int64 offset; int64 size; char *ptr; char *current_ptr; char *last_ptr; int file_id; bool reverse; MappedStream(string file, int64 offset, int64 size); MappedStream(string file): MappedStream(file, 0,0){}; int64 position(); void set_position(int64 position); char next_char(); int next_int(); int next_int(int64 step); char* next(int64 bytes, int64 step = 0); template<class Type> Type next(int64 step = 0); bool has_remain(); void close_stream(); }; inline MappedStream::MappedStream(string file, int64 offset, int64 size){ this->file = file; this->offset = offset; //this->opposite_direction = opposite_direction; if(size <=0){ size = file_size(file); } //PAGE ALIGNMENT int64 bytes_align = offset %PAGE_SIZE; offset -= bytes_align; size += bytes_align; this->size = size; reverse = false; file_id = open(this->file.c_str(), O_RDONLY); if (file_id == -1) { perror("Error opening file for reading"); exit(EXIT_FAILURE); } //cout<< file << endl; //cout<< sizeof(size_t)<<endl; ptr = (char*) mmap(0, size , PROT_READ, MAP_SHARED, file_id, offset); //MOVING POINTER TO THE FIRST POSITION OF THE OFFSET //if(!opposite_direction){ current_ptr = ptr + bytes_align; last_ptr = ptr + size; /*}else{ last_ptr = ptr + bytes_align; current_ptr = ptr + size; }*/ if (ptr == MAP_FAILED) { close(file_id); perror("Error mmapping the file"); exit(EXIT_FAILURE); } } inline bool MappedStream::has_remain(){ return /*opposite_direction? current_ptr > last_ptr : */current_ptr < last_ptr; } inline char* MappedStream::next(int64 bytes, int64 step){ char* ptr; //if(!opposite_direction){ ptr = current_ptr; current_ptr += bytes + step; /*}else{ ptr = current_ptr - bytes; current_ptr -= (bytes + step); }*/ return ptr; } template<class Type> inline Type MappedStream::next(int64 step){ Type ptr = *( (Type*)current_ptr); current_ptr += sizeof(Type) + step; return ptr; } /*inline char* MappedStream::next(int64 bytes, int64 step){ char* ptr; ptr = current_ptr; current_ptr += bytes + step; return ptr; }*/ inline int MappedStream::next_int(){ return next_int(0); } inline char MappedStream::next_char(){ return next<char>(); } inline int MappedStream::next_int(int64 step){ return *( (int*) next(INT_SIZE, step) ); //int v = *( (int*) next(INT_SIZE, step) ); /*if(reverse) return ((v >> 24) & 0xFF) +(((v >> 16) & 0xFF) << 8) +(((v >> 8) & 0xFF) << 16) + ((v & 0xFF) << 24);*/ // return v; } /* inline int64 Stream::next_int64(){ return (int)*( next(INT64_SIZE) ); }*/ /*inline float Stream::next_float(){ return (float)*( next(FLOAT_SIZE) ); } inline double Stream::next_double(){ return (double)*( next(DOUBLE_SIZE) ); }*/ inline int64 MappedStream::position(){ return current_ptr - ptr; } inline void MappedStream::set_position(int64 position){ char* p = position + ptr; if(p> ptr && p< last_ptr){ current_ptr = p; } } inline void MappedStream::close_stream(){ if (munmap(ptr, size) == -1) { perror("Error un-mmapping the file"); } close(file_id); } } #endif /* MFLASH_CPP_CORE_MAPPED_STREAM_HPP_ */ <|endoftext|>
<commit_before>/* * * Copyright (c) 2014, James Hurlbut * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of James Hurlbut nor the names of its * contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "GLTFNode.h" #include "GLTFMesh.h" #include "cinder/gl/gl.h" using namespace std; using namespace ci; using namespace ci::app; using namespace gl; namespace cinder { namespace gltf { typedef vector<float>::const_iterator myiter; struct ordering { bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) { return *(a.second) > *(b.second); } }; void Node::draw(bool child, int numInstances, std::vector<mat4> rotMats, std::vector<ci::mat4> positions, std::vector<ci::mat4> scales){ { if (numInstances == 0){ gl::pushModelView(); matrix = glm::scale(scale)* rotmat; matrix[3] = vec4(trans,1); gl::multModelMatrix(matrix); } else { matrix = rotmat; rotMats.push_back(matrix); positions.push_back(glm::translate(trans)); scales.push_back(glm::scale(scale)); } //matrix[3] = vec4(trans,1); //gl::multModelMatrix(matrix); //double t1 = ci::app::getElapsedSeconds(); //ci::app::console() << (t1 - t0) * 1000 << " : " << name << " : matrix node time " << std::endl; for (MeshRef pMesh : pMeshes) { //double t0 = ci::app::getElapsedSeconds(); pMesh->draw(numInstances, rotMats, positions,scales); //double t1 = ci::app::getElapsedSeconds(); //ci::app::console() << (t1 - t0) * 1000 << " : "<< name << " : node draw time " << std::endl; } std::vector<float> distances; for (NodeRef pChild : pChildren) { vec4 start = vec4(1); vec4 xform = getProjectionMatrix() * getViewMatrix() * getModelMatrix() * pChild->matrix * vec4(pChild->bounds.getCenter(), 1); //gl::drawColorCube(vec3(xform.x, xform.y, xform.z), vec3(.1)); distances.push_back(xform.z); } vector<pair<size_t, myiter> > order(distances.size()); size_t n = 0; for (myiter it = distances.begin(); it != distances.end(); ++it, ++n) order[n] = make_pair(n, it); sort(order.begin(), order.end(), ordering()); //ci::app::console() << ":::::::::::" << endl; for (auto pDrawOrder : order) { pChildren[pDrawOrder.first]->draw(true, numInstances, rotMats, positions, scales); } if (numInstances == 0){ gl::popModelView(); } } }; } }<commit_msg>reorder xform<commit_after>/* * * Copyright (c) 2014, James Hurlbut * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of James Hurlbut nor the names of its * contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "GLTFNode.h" #include "GLTFMesh.h" #include "cinder/gl/gl.h" using namespace std; using namespace ci; using namespace ci::app; using namespace gl; namespace cinder { namespace gltf { typedef vector<float>::const_iterator myiter; struct ordering { bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) { return *(a.second) > *(b.second); } }; void Node::draw(bool child, int numInstances, std::vector<mat4> rotMats, std::vector<ci::mat4> positions, std::vector<ci::mat4> scales){ { if (numInstances == 0){ gl::pushModelView(); matrix = rotmat * glm::scale(scale); matrix[3] = vec4(trans,1); gl::multModelMatrix(matrix); } else { matrix = rotmat; rotMats.push_back(matrix); positions.push_back(glm::translate(trans)); scales.push_back(glm::scale(scale)); } //matrix[3] = vec4(trans,1); //gl::multModelMatrix(matrix); //double t1 = ci::app::getElapsedSeconds(); //ci::app::console() << (t1 - t0) * 1000 << " : " << name << " : matrix node time " << std::endl; for (MeshRef pMesh : pMeshes) { //double t0 = ci::app::getElapsedSeconds(); pMesh->draw(numInstances, rotMats, positions,scales); //double t1 = ci::app::getElapsedSeconds(); //ci::app::console() << (t1 - t0) * 1000 << " : "<< name << " : node draw time " << std::endl; } std::vector<float> distances; for (NodeRef pChild : pChildren) { vec4 start = vec4(1); vec4 xform = getProjectionMatrix() * getViewMatrix() * getModelMatrix() * pChild->matrix * vec4(pChild->bounds.getCenter(), 1); //gl::drawColorCube(vec3(xform.x, xform.y, xform.z), vec3(.1)); distances.push_back(xform.z); } vector<pair<size_t, myiter> > order(distances.size()); size_t n = 0; for (myiter it = distances.begin(); it != distances.end(); ++it, ++n) order[n] = make_pair(n, it); sort(order.begin(), order.end(), ordering()); //ci::app::console() << ":::::::::::" << endl; for (auto pDrawOrder : order) { pChildren[pDrawOrder.first]->draw(true, numInstances, rotMats, positions, scales); } if (numInstances == 0){ gl::popModelView(); } } }; } }<|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_BUFFER_HPP_ # define _QI_BUFFER_HPP_ # include <qi/api.hpp> # include <qi/types.hpp> # include <boost/shared_ptr.hpp> # include <vector> # include <cstddef> #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4251 ) #endif namespace qi { class BufferPrivate; /** * \brief Class to store buffer. * \includename{qi/buffer.hpp} * * \verbatim * This class can store buffer and sub-buffers. * Here is a representation of internal management of sub-buffers. * * .. graphviz:: * * digraph g { * graph [ rankdir = "LR" ]; * node [ fontsize = "16", shape = "ellipse" ]; * * subgraph cluster_buffer { * mainbuffer; * label = "Main buffer"; * } * * subgraph cluster_subbuffer1 { * subbuffer1; * label = "Sub-buffer 1"; * } * * subgraph cluster_subbuffer2 { * subbuffer2; * label = "Sub-buffer 2"; * } * * "mainbuffer" [ * label = "...| ...| ...| ...| ...| ...|<f0> uint32_t subBufferSize| ...| ...|<f1> uint32_t subBufferSize| ...| ...| ..." * shape = "record" * ]; * "subbuffer1" [ * label = "<f0> ...| ...|...| ...| ...| ...| ...| ...| ...| ..." * shape = "record" * ]; * "subbuffer2" [ * label = "<f0> ...| ...|...| ...| ...| ...| ...| ...| ...| ..." * shape = "record" * ]; * "mainbuffer":f0-> "subbuffer1":f0[ * id = 0 * ]; * "mainbuffer":f1-> "subbuffer2":f0[ * id = 0 * ]; * } * * \endverbatim */ class QI_API Buffer { public: /// \brief Default constructor. Buffer(); /** * \brief Copy constructor. * \param buffer The buffer to copy. * * As data are store as a shared pointer, the different copy * of the same buffer all handle the same data. */ Buffer(const Buffer& buffer); /** * \brief Assignment operator. * As data are store as a shared pointer, the different copy * of the same buffer all handle the same data. * \param buffer The buffer to copy. */ Buffer& operator = (const Buffer& buffer); /** * \brief Write data in the buffer. * \param data The data to write * \param size The size of the data to write * \return true if operation succeeded, false otherwise. */ bool write(const void *data, size_t size); /** * \brief Add a sub-buffer to the main buffer. * This function add a uint32_t for the size of sub-buffers in main buffer * and add the buffer to the list of sub-buffers. * \param buffer The buffer to have as sub-buffer. * \return return te offset at which sub-buffer have been added. */ size_t addSubBuffer(const Buffer& buffer); /** * \brief Check if there is a sub-buffer at given offset. * \param offset The offset to look at the presence of sub-buffer. * \return true if there is a sub-buffer, false otherwise. */ bool hasSubBuffer(size_t offset) const; /** * \brief Return the sub-buffer at given offset. * If there is no sub-buffer throw a std::runtime_error. * \param offset The offset to look for sub-buffer. * \return the sub-buffer. */ const Buffer& subBuffer(size_t offset) const; /** * \brief Return the content size of this buffer not counting sub-buffers. * \return the size. * \see totalSize */ size_t size() const; /** * \brief Return the content size of this buffer and of all its sub-buffers. * \return the size. * \see size */ size_t totalSize() const; /** * \brief Return a vector of sub-buffers of the current buffer. * \return a vector of pairs. The first value of the pair is the offset of the * sub-buffer into the master buffer. The second value is the sub-buffer itself. */ const std::vector<std::pair<size_t, Buffer> >& subBuffers() const; /** * \brief Reserve bytes at the end of current buffer. * \param size number of new bytes to reserve at the end of buffer. * \return a pointer to the data. * \warning The return value is valid until the next non-const operation. */ void* reserve(size_t size); /** * \brief Erase content of buffer and remove sub-buffers whithout clearing them. */ void clear(); /** * \brief Return a pointer to the raw data storage of this buffer. * \return the pointer to the data. */ void* data(); /** * \brief Return a const pointer to the raw data in this buffer. * \return the pointer to the data. */ const void* data() const; /** * \brief Read some data from the buffer. * \param offset offset at which reading begin in the buffer. * \param length length of the data to read. * \return 0 if the buffer is empty or if we try to read data after the end * of the buffer.\n * Otherwise return a pointer to the data. Only \a length bytes can be read in * the returned buffer. */ const void* read(size_t offset = 0, size_t length = 0) const; /** * \brief Read some data in the buffer and store it in a new pre-allocated buffer. * \warning the given buffer must be freed. * \param buffer the pre-allocated buffer to store data. * \param offset Offset in the current buffer to start copy. * \param length Length of the data to be copied. * \return -1 if there is no data in buffer or if \a offset is bigger than * total data in buffer.\n * Otherwise return the total length of copied data. */ size_t read(void* buffer, size_t offset = 0, size_t length = 0) const; private: friend class BufferReader; // CS4251 boost::shared_ptr<BufferPrivate> _p; }; /** * \brief Class to read const buffer. * \includename{qi/buffer.hpp} * This class is intendeed to read buffer. * It store an internal data cursor and an internal sub-buffer index. * All offset are relative to the current position. */ class QI_API BufferReader { public: /** * \brief Constructor. * \param buf The buffer to copy. */ explicit BufferReader(const Buffer& buf); /// \brief Default destructor. ~BufferReader(); /** * \brief read and store data from the buffer. * \param data A pre-allocated pointer to store read data. * \param length Size of the object pointed by \a data or size to read. * \return size of really read and stored data. */ size_t read(void *data, size_t length); /** * \brief read data from buffer. * \param offset Number of bytes to read. * \return a pointer to data at the given */ void *read(size_t offset); /** * \brief Move forward the buffer cursor by the given offset. * \param offset Value for move forward the cursor. * \return Return true if succeed, false otherwise. */ bool seek(size_t offset); /** * \brief Check if we can read from the actual position toward \a offset bytes. * \warning This function doesn't move the internal pointer. * \param offset The relative offset. * \return The pointer if it succeed. If actual position + * \a offset exceed size of buffer return 0. */ void *peek(size_t offset) const; /** * \brief Check if there is sub-buffer at the actual position. * \return true if there is sub-buffer, false otherwise. */ bool hasSubBuffer() const; /** * \brief return the sub-buffer at the actual position. * If there is no sub-buffer at actual position throw a std::runtime-error. * \return Return the sub-buffer if any. */ const Buffer& subBuffer(); /** * \brief Return the actual position in the buffer. * \return The current offset. */ size_t position() const; private: Buffer _buffer; size_t _cursor; size_t _subCursor; // position in sub-buffers }; namespace detail { QI_API void printBuffer(std::ostream& stream, const Buffer& buffer); } } #ifdef _MSC_VER # pragma warning( pop ) #endif #endif // _QI_BUFFER_HPP_ <commit_msg>test build pull request<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_BUFFER_HPP_ # define _QI_BUFFER_HPP_ # include <qi/api.hpp> # include <qi/types.hpp> # include <boost/shared_ptr.hpp> # include <vector> # include <cstddef> #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4251 ) #endif namespace qi { class BufferPrivate; /** * \brief Class to store buffer. * \includename{qi/buffer.hpp} * * \verbatim * This class can store buffer and sub-buffers. * Here is a representation of internal management of sub-buffers. * * .. graphviz:: * * digraph g { * graph [ rankdir = "LR" ]; * node [ fontsize = "16", shape = "ellipse" ]; * * subgraph cluster_buffer { * mainbuffer; * label = "Main buffer"; * } * * subgraph cluster_subbuffer1 { * subbuffer1; * label = "Sub-buffer 1"; * } * * subgraph cluster_subbuffer2 { * subbuffer2; * label = "Sub-buffer 2"; * } * * "mainbuffer" [ * label = "...| ...| ...| ...| ...| ...|<f0> uint32_t subBufferSize| ...| ...|<f1> uint32_t subBufferSize| ...| ...| ..." * shape = "record" * ]; * "subbuffer1" [ * label = "<f0> ...| ...|...| ...| ...| ...| ...| ...| ...| ..." * shape = "record" * ]; * "subbuffer2" [ * label = "<f0> ...| ...|...| ...| ...| ...| ...| ...| ...| ..." * shape = "record" * ]; * "mainbuffer":f0-> "subbuffer1":f0[ * id = 0 * ]; * "mainbuffer":f1-> "subbuffer2":f0[ * id = 0 * ]; * } * * \endverbatim */ class QI_API Buffer { public: /// \brief Default constructor. Buffer(); /** * \brief Copy constructor. * \param buffer The buffer to copy. * * As data are store as a shared pointer, the different copy * of the same buffer all handle the same data. */ Buffer(const Buffer& buffer); /** * \brief Assignment operator. * As data are store as a shared pointer, the different copy * of the same buffer all handle the same data. * \param buffer The buffer to copy. */ Buffer& operator = (const Buffer& buffer); /** * \brief Write data in the buffer. * \param data The data to write * \param size The size of the data to write * \return true if operation succeeded, false otherwise. */ bool write(const void *data, size_t size); /** * \brief Add a sub-buffer to the main buffer. * This function add a uint32_t for the size of sub-buffers in main buffer * and add the buffer to the list of sub-buffers. * \param buffer The buffer to have as sub-buffer. * \return return te offset at which sub-buffer have been added. */ size_t addSubBuffer(const Buffer& buffer); /** * \brief Check if there is a sub-buffer at given offset. * \param offset The offset to look at the presence of sub-buffer. * \return true if there is a sub-buffer, false otherwise. */ bool hasSubBuffer(size_t offset) const; /** * \brief Return the sub-buffer at given offset. * If there is no sub-buffer throw a std::runtime_error. * \param offset The offset to look for sub-buffer. * \return the sub-buffer. */ const Buffer& subBuffer(size_t offset) const; /** * \brief Return the content size of this buffer not counting sub-buffers. * \return the size. * \see totalSize */ size_t size() const; /** * \brief Return the content size of this buffer and of all its sub-buffers. * \return the size. * \see size */ size_t totalSize() const; /** * \brief Return a vector of sub-buffers of the current buffer. * \return a vector of pairs. The first value of the pair is the offset of the * sub-buffer into the master buffer. The second value is the sub-buffer itself. */ const std::vector<std::pair<size_t, Buffer> >& subBuffers() const; /** * \brief Reserve bytes at the end of current buffer. * \param size number of new bytes to reserve at the end of buffer. * \return a pointer to the data. * \warning The return value is valid until the next non-const operation. */ void* reserve(size_t size); /** * \brief Erase content of buffer and remove sub-buffers whithout clearing them. */ void clear(); /** * \brief Return a pointer to the raw data storage of this buffer. * \return the pointer to the data. */ void* data(); /** * \brief Return a const pointer to the raw data in this buffer. * \return the pointer to the data. */ const void* data() const; /** * \brief Read some data from the buffer. * \param offset offset at which reading begin in the buffer. * \param length length of the data to read. * \return 0 if the buffer is empty or if we try to read data after the end * of the buffer.\n * Otherwise return a pointer to the data. Only \a length bytes can be read in * the returned buffer. */ const void* read(size_t offset = 0, size_t length = 0) const; /** * \brief Read some data in the buffer and store it in a new pre-allocated buffer. * \warning the given buffer must be freed. * \param buffer the pre-allocated buffer to store data. * \param offset Offset in the current buffer to start copy. * \param length Length of the data to be copied. * \return -1 if there is no data in buffer or if \a offset is bigger than * total data in buffer.\n * Otherwise return the total length of copied data. */ size_t read(void* buffer, size_t offset = 0, size_t length = 0) const; private: friend class BufferReader; // CS4251 boost::shared_ptr<BufferPrivate> _p; bool test_github; }; /** * \brief Class to read const buffer. * \includename{qi/buffer.hpp} * This class is intendeed to read buffer. * It store an internal data cursor and an internal sub-buffer index. * All offset are relative to the current position. */ class QI_API BufferReader { public: /** * \brief Constructor. * \param buf The buffer to copy. */ explicit BufferReader(const Buffer& buf); /// \brief Default destructor. ~BufferReader(); /** * \brief read and store data from the buffer. * \param data A pre-allocated pointer to store read data. * \param length Size of the object pointed by \a data or size to read. * \return size of really read and stored data. */ size_t read(void *data, size_t length); /** * \brief read data from buffer. * \param offset Number of bytes to read. * \return a pointer to data at the given */ void *read(size_t offset); /** * \brief Move forward the buffer cursor by the given offset. * \param offset Value for move forward the cursor. * \return Return true if succeed, false otherwise. */ bool seek(size_t offset); /** * \brief Check if we can read from the actual position toward \a offset bytes. * \warning This function doesn't move the internal pointer. * \param offset The relative offset. * \return The pointer if it succeed. If actual position + * \a offset exceed size of buffer return 0. */ void *peek(size_t offset) const; /** * \brief Check if there is sub-buffer at the actual position. * \return true if there is sub-buffer, false otherwise. */ bool hasSubBuffer() const; /** * \brief return the sub-buffer at the actual position. * If there is no sub-buffer at actual position throw a std::runtime-error. * \return Return the sub-buffer if any. */ const Buffer& subBuffer(); /** * \brief Return the actual position in the buffer. * \return The current offset. */ size_t position() const; private: Buffer _buffer; size_t _cursor; size_t _subCursor; // position in sub-buffers }; namespace detail { QI_API void printBuffer(std::ostream& stream, const Buffer& buffer); } } #ifdef _MSC_VER # pragma warning( pop ) #endif #endif // _QI_BUFFER_HPP_ <|endoftext|>
<commit_before>#include <QtGui/QApplication> #include <QtGui> #include <QtGui/QWidget> #include "gui_form.h" #include "ui_gui_form.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); gui_form w; w.setWindowTitle("Camera Calibration of Projector Based Tiled Display"); //w.show(); w.showMaximized(); return a.exec(); } <commit_msg>minor: GUI window label change<commit_after>#include <QtGui/QApplication> #include <QtGui> #include <QtGui/QWidget> #include "gui_form.h" #include "ui_gui_form.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); gui_form w; w.setWindowTitle("Multiprojector tiled display calibration tool"); //w.show(); w.showMaximized(); return a.exec(); } <|endoftext|>
<commit_before>#include <cstring> #include <linux/input-event-codes.h> #include <xkbcommon/xkbcommon.h> #include <wayfire/util/log.hpp> #include "keyboard.hpp" #include "../core-impl.hpp" #include "../../output/output-impl.hpp" #include "cursor.hpp" #include "touch.hpp" #include "input-manager.hpp" #include "wayfire/compositor-view.hpp" #include "wayfire/signal-definitions.hpp" void wf_keyboard::setup_listeners() { on_key.set_callback([&] (void *data) { auto ev = static_cast<wlr_event_keyboard_key*>(data); emit_device_event_signal("keyboard_key", ev); auto seat = wf::get_core().get_current_seat(); wlr_seat_set_keyboard(seat, this->device); if (!wf::get_core_impl().input->handle_keyboard_key(ev->keycode, ev->state)) { wlr_seat_keyboard_notify_key(wf::get_core_impl().input->seat, ev->time_msec, ev->keycode, ev->state); } wlr_idle_notify_activity(wf::get_core().protocols.idle, seat); }); on_modifier.set_callback([&] (void *data) { auto kbd = static_cast<wlr_keyboard*>(data); auto seat = wf::get_core().get_current_seat(); wlr_seat_set_keyboard(seat, this->device); wlr_seat_keyboard_send_modifiers(seat, &kbd->modifiers); wlr_idle_notify_activity(wf::get_core().protocols.idle, seat); }); on_key.connect(&handle->events.key); on_modifier.connect(&handle->events.modifiers); } wf_keyboard::wf_keyboard(wlr_input_device *dev) : handle(dev->keyboard), device(dev) { model.load_option("input/xkb_model"); variant.load_option("input/xkb_variant"); layout.load_option("input/xkb_layout"); options.load_option("input/xkb_options"); rules.load_option("input/xkb_rules"); repeat_rate.load_option("input/kb_repeat_rate"); repeat_delay.load_option("input/kb_repeat_delay"); // When the configuration options change, mark them as dirty. // They are applied at the config-reloaded signal. model.set_callback([=] () { this->dirty_options = true; }); variant.set_callback([=] () { this->dirty_options = true; }); layout.set_callback([=] () { this->dirty_options = true; }); options.set_callback([=] () { this->dirty_options = true; }); rules.set_callback([=] () { this->dirty_options = true; }); repeat_rate.set_callback([=] () { this->dirty_options = true; }); repeat_delay.set_callback([=] () { this->dirty_options = true; }); setup_listeners(); reload_input_options(); wlr_seat_set_keyboard(wf::get_core().get_current_seat(), dev); } static void set_locked_mod(xkb_mod_mask_t *mods, xkb_keymap *keymap, char *mod) { xkb_mod_index_t mod_index = xkb_map_mod_get_index(keymap, mod); if (mod_index != XKB_MOD_INVALID) { *mods |= (uint32_t)1 << mod_index; } } void wf_keyboard::reload_input_options() { if (!this->dirty_options) { return; } this->dirty_options = false; auto ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS); /* Copy memory to stack, so that .c_str() is valid */ std::string rules = this->rules; std::string model = this->model; std::string layout = this->layout; std::string variant = this->variant; std::string options = this->options; xkb_rule_names names; names.rules = rules.c_str(); names.model = model.c_str(); names.layout = layout.c_str(); names.variant = variant.c_str(); names.options = options.c_str(); auto keymap = xkb_map_new_from_names(ctx, &names, XKB_KEYMAP_COMPILE_NO_FLAGS); if (!keymap) { LOGE("Could not create keymap with given configuration:", " rules=\"", rules, "\" model=\"", model, "\" layout=\"", layout, "\" variant=\"", variant, "\" options=\"", options, "\""); // reset to NULL std::memset(&names, 0, sizeof(names)); keymap = xkb_map_new_from_names(ctx, &names, XKB_KEYMAP_COMPILE_NO_FLAGS); } xkb_mod_mask_t locked_mods = 0; if (wf::get_core_impl().input->locked_mods & WF_KB_NUM) { set_locked_mod(&locked_mods, keymap, XKB_MOD_NAME_NUM); } if (wf::get_core_impl().input->locked_mods & WF_KB_CAPS) { set_locked_mod(&locked_mods, keymap, XKB_MOD_NAME_CAPS); } wlr_keyboard_set_keymap(handle, keymap); xkb_keymap_unref(keymap); xkb_context_unref(ctx); wlr_keyboard_set_repeat_info(handle, repeat_rate, repeat_delay); wlr_keyboard_notify_modifiers(handle, 0, 0, locked_mods, 0); } wf_keyboard::~wf_keyboard() {} /* input manager things */ void input_manager::set_keyboard_focus(wayfire_view view, wlr_seat *seat) { auto surface = view ? view->get_keyboard_focus_surface() : NULL; auto iv = interactive_view_from_view(view.get()); auto oiv = interactive_view_from_view(keyboard_focus.get()); if (oiv) { oiv->handle_keyboard_leave(); } if (iv) { iv->handle_keyboard_enter(); } /* Don't focus if we have an active grab */ if (!active_grab) { if (surface) { auto kbd = wlr_seat_get_keyboard(seat); wlr_seat_keyboard_notify_enter(seat, surface, kbd ? kbd->keycodes : NULL, kbd ? kbd->num_keycodes : 0, kbd ? &kbd->modifiers : NULL); } else { wlr_seat_keyboard_notify_clear_focus(seat); } keyboard_focus = view; } else { wlr_seat_keyboard_notify_clear_focus(seat); keyboard_focus = nullptr; } wf::keyboard_focus_changed_signal data; data.view = view; data.surface = surface; wf::get_core().emit_signal("keyboard-focus-changed", &data); } static bool check_vt_switch(wlr_session *session, uint32_t key, uint32_t mods) { if (!session) { return false; } if (mods ^ (WLR_MODIFIER_ALT | WLR_MODIFIER_CTRL)) { return false; } if ((key < KEY_F1) || (key > KEY_F10)) { return false; } /* Somebody inhibited the output, most probably a lockscreen */ auto output_impl = static_cast<wf::output_impl_t*>(wf::get_core().get_active_output()); if (output_impl->is_inhibited()) { return false; } int target_vt = key - KEY_F1 + 1; wlr_session_change_vt(session, target_vt); return true; } static uint32_t mod_from_key(wlr_seat *seat, uint32_t key) { xkb_keycode_t keycode = key + 8; auto keyboard = wlr_seat_get_keyboard(seat); if (!keyboard) { return 0; // potentially a bug? } const xkb_keysym_t *keysyms; auto keysyms_len = xkb_state_key_get_syms(keyboard->xkb_state, keycode, &keysyms); for (int i = 0; i < keysyms_len; i++) { auto key = keysyms[i]; if ((key == XKB_KEY_Alt_L) || (key == XKB_KEY_Alt_R)) { return WLR_MODIFIER_ALT; } if ((key == XKB_KEY_Control_L) || (key == XKB_KEY_Control_R)) { return WLR_MODIFIER_CTRL; } if ((key == XKB_KEY_Shift_L) || (key == XKB_KEY_Shift_R)) { return WLR_MODIFIER_SHIFT; } if ((key == XKB_KEY_Super_L) || (key == XKB_KEY_Super_R)) { return WLR_MODIFIER_LOGO; } } return 0; } std::vector<std::function<bool()>> input_manager::match_keys(uint32_t mod_state, uint32_t key, uint32_t mod_binding_key) { std::vector<std::function<bool()>> callbacks; uint32_t actual_key = key == 0 ? mod_binding_key : key; for (auto& binding : bindings[WF_BINDING_KEY]) { auto as_key = std::dynamic_pointer_cast< wf::config::option_t<wf::keybinding_t>>(binding->value); assert(as_key); if ((as_key->get_value() == wf::keybinding_t{mod_state, key}) && (binding->output == wf::get_core().get_active_output())) { /* We must be careful because the callback might be erased, * so force copy the callback into the lambda */ auto callback = binding->call.key; callbacks.push_back([actual_key, callback] () { return (*callback)(actual_key); }); } } for (auto& binding : bindings[WF_BINDING_ACTIVATOR]) { auto as_activator = std::dynamic_pointer_cast< wf::config::option_t<wf::activatorbinding_t>>(binding->value); assert(as_activator); if (as_activator->get_value().has_match(wf::keybinding_t{mod_state, key}) && (binding->output == wf::get_core().get_active_output())) { /* We must be careful because the callback might be erased, * so force copy the callback into the lambda * * Also, do not send keys for modifier bindings */ auto callback = binding->call.activator; callbacks.push_back([=] () { return (*callback)(wf::ACTIVATOR_SOURCE_KEYBINDING, mod_from_key(seat, actual_key) ? 0 : actual_key); }); } } return callbacks; } void update_keyboard_locked_mods(wlr_keyboard *kbd, xkb_mod_mask_t& locked_mods) { uint32_t leds = 0; for (uint32_t i = 0; i < WLR_LED_COUNT; i++) { if (xkb_state_led_index_is_active( kbd->xkb_state, kbd->led_indexes[i])) { leds |= (1 << i); } } if (leds & WLR_LED_NUM_LOCK) { locked_mods |= WF_KB_NUM; } else { locked_mods &= ~WF_KB_NUM; } if (leds & WLR_LED_CAPS_LOCK) { locked_mods |= WF_KB_CAPS; } else { locked_mods &= ~WF_KB_CAPS; } } bool input_manager::handle_keyboard_key(uint32_t key, uint32_t state) { using namespace std::chrono; if (active_grab && active_grab->callbacks.keyboard.key) { active_grab->callbacks.keyboard.key(key, state); } auto mod = mod_from_key(seat, key); if (mod) { handle_keyboard_mod(mod, state); } std::vector<std::function<bool()>> callbacks; auto kbd = wlr_seat_get_keyboard(seat); update_keyboard_locked_mods(kbd, locked_mods); if (state == WLR_KEY_PRESSED) { auto session = wlr_backend_get_session(wf::get_core().backend); if (check_vt_switch(session, key, get_modifiers())) { return true; } /* as long as we have pressed only modifiers, we should check for modifier * bindings on release */ if (mod) { bool modifiers_only = !lpointer->has_pressed_buttons() && (touch->get_state().fingers.empty()); for (size_t i = 0; kbd && i < kbd->num_keycodes; i++) { if (!mod_from_key(seat, kbd->keycodes[i])) { modifiers_only = false; } } if (modifiers_only) { mod_binding_start = steady_clock::now(); mod_binding_key = key; } } else { mod_binding_key = 0; } callbacks = match_keys(get_modifiers(), key); } else { if (mod_binding_key != 0) { int timeout = wf::option_wrapper_t<int>( "input/modifier_binding_timeout"); if ((timeout <= 0) || (duration_cast<milliseconds>(steady_clock::now() - mod_binding_start) <= milliseconds(timeout))) { callbacks = match_keys(get_modifiers() | mod, 0, mod_binding_key); } } mod_binding_key = 0; } bool keybinding_handled = false; for (auto call : callbacks) { keybinding_handled |= call(); } auto iv = interactive_view_from_view(keyboard_focus.get()); if (iv) { iv->handle_key(key, state); } return active_grab || keybinding_handled; } void input_manager::handle_keyboard_mod(uint32_t modifier, uint32_t state) { if (active_grab && active_grab->callbacks.keyboard.mod) { active_grab->callbacks.keyboard.mod(modifier, state); } } <commit_msg>Make char* argument const<commit_after>#include <cstring> #include <linux/input-event-codes.h> #include <xkbcommon/xkbcommon.h> #include <wayfire/util/log.hpp> #include "keyboard.hpp" #include "../core-impl.hpp" #include "../../output/output-impl.hpp" #include "cursor.hpp" #include "touch.hpp" #include "input-manager.hpp" #include "wayfire/compositor-view.hpp" #include "wayfire/signal-definitions.hpp" void wf_keyboard::setup_listeners() { on_key.set_callback([&] (void *data) { auto ev = static_cast<wlr_event_keyboard_key*>(data); emit_device_event_signal("keyboard_key", ev); auto seat = wf::get_core().get_current_seat(); wlr_seat_set_keyboard(seat, this->device); if (!wf::get_core_impl().input->handle_keyboard_key(ev->keycode, ev->state)) { wlr_seat_keyboard_notify_key(wf::get_core_impl().input->seat, ev->time_msec, ev->keycode, ev->state); } wlr_idle_notify_activity(wf::get_core().protocols.idle, seat); }); on_modifier.set_callback([&] (void *data) { auto kbd = static_cast<wlr_keyboard*>(data); auto seat = wf::get_core().get_current_seat(); wlr_seat_set_keyboard(seat, this->device); wlr_seat_keyboard_send_modifiers(seat, &kbd->modifiers); wlr_idle_notify_activity(wf::get_core().protocols.idle, seat); }); on_key.connect(&handle->events.key); on_modifier.connect(&handle->events.modifiers); } wf_keyboard::wf_keyboard(wlr_input_device *dev) : handle(dev->keyboard), device(dev) { model.load_option("input/xkb_model"); variant.load_option("input/xkb_variant"); layout.load_option("input/xkb_layout"); options.load_option("input/xkb_options"); rules.load_option("input/xkb_rules"); repeat_rate.load_option("input/kb_repeat_rate"); repeat_delay.load_option("input/kb_repeat_delay"); // When the configuration options change, mark them as dirty. // They are applied at the config-reloaded signal. model.set_callback([=] () { this->dirty_options = true; }); variant.set_callback([=] () { this->dirty_options = true; }); layout.set_callback([=] () { this->dirty_options = true; }); options.set_callback([=] () { this->dirty_options = true; }); rules.set_callback([=] () { this->dirty_options = true; }); repeat_rate.set_callback([=] () { this->dirty_options = true; }); repeat_delay.set_callback([=] () { this->dirty_options = true; }); setup_listeners(); reload_input_options(); wlr_seat_set_keyboard(wf::get_core().get_current_seat(), dev); } static void set_locked_mod(xkb_mod_mask_t *mods, xkb_keymap *keymap, const char *mod) { xkb_mod_index_t mod_index = xkb_map_mod_get_index(keymap, mod); if (mod_index != XKB_MOD_INVALID) { *mods |= (uint32_t)1 << mod_index; } } void wf_keyboard::reload_input_options() { if (!this->dirty_options) { return; } this->dirty_options = false; auto ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS); /* Copy memory to stack, so that .c_str() is valid */ std::string rules = this->rules; std::string model = this->model; std::string layout = this->layout; std::string variant = this->variant; std::string options = this->options; xkb_rule_names names; names.rules = rules.c_str(); names.model = model.c_str(); names.layout = layout.c_str(); names.variant = variant.c_str(); names.options = options.c_str(); auto keymap = xkb_map_new_from_names(ctx, &names, XKB_KEYMAP_COMPILE_NO_FLAGS); if (!keymap) { LOGE("Could not create keymap with given configuration:", " rules=\"", rules, "\" model=\"", model, "\" layout=\"", layout, "\" variant=\"", variant, "\" options=\"", options, "\""); // reset to NULL std::memset(&names, 0, sizeof(names)); keymap = xkb_map_new_from_names(ctx, &names, XKB_KEYMAP_COMPILE_NO_FLAGS); } xkb_mod_mask_t locked_mods = 0; if (wf::get_core_impl().input->locked_mods & WF_KB_NUM) { set_locked_mod(&locked_mods, keymap, XKB_MOD_NAME_NUM); } if (wf::get_core_impl().input->locked_mods & WF_KB_CAPS) { set_locked_mod(&locked_mods, keymap, XKB_MOD_NAME_CAPS); } wlr_keyboard_set_keymap(handle, keymap); xkb_keymap_unref(keymap); xkb_context_unref(ctx); wlr_keyboard_set_repeat_info(handle, repeat_rate, repeat_delay); wlr_keyboard_notify_modifiers(handle, 0, 0, locked_mods, 0); } wf_keyboard::~wf_keyboard() {} /* input manager things */ void input_manager::set_keyboard_focus(wayfire_view view, wlr_seat *seat) { auto surface = view ? view->get_keyboard_focus_surface() : NULL; auto iv = interactive_view_from_view(view.get()); auto oiv = interactive_view_from_view(keyboard_focus.get()); if (oiv) { oiv->handle_keyboard_leave(); } if (iv) { iv->handle_keyboard_enter(); } /* Don't focus if we have an active grab */ if (!active_grab) { if (surface) { auto kbd = wlr_seat_get_keyboard(seat); wlr_seat_keyboard_notify_enter(seat, surface, kbd ? kbd->keycodes : NULL, kbd ? kbd->num_keycodes : 0, kbd ? &kbd->modifiers : NULL); } else { wlr_seat_keyboard_notify_clear_focus(seat); } keyboard_focus = view; } else { wlr_seat_keyboard_notify_clear_focus(seat); keyboard_focus = nullptr; } wf::keyboard_focus_changed_signal data; data.view = view; data.surface = surface; wf::get_core().emit_signal("keyboard-focus-changed", &data); } static bool check_vt_switch(wlr_session *session, uint32_t key, uint32_t mods) { if (!session) { return false; } if (mods ^ (WLR_MODIFIER_ALT | WLR_MODIFIER_CTRL)) { return false; } if ((key < KEY_F1) || (key > KEY_F10)) { return false; } /* Somebody inhibited the output, most probably a lockscreen */ auto output_impl = static_cast<wf::output_impl_t*>(wf::get_core().get_active_output()); if (output_impl->is_inhibited()) { return false; } int target_vt = key - KEY_F1 + 1; wlr_session_change_vt(session, target_vt); return true; } static uint32_t mod_from_key(wlr_seat *seat, uint32_t key) { xkb_keycode_t keycode = key + 8; auto keyboard = wlr_seat_get_keyboard(seat); if (!keyboard) { return 0; // potentially a bug? } const xkb_keysym_t *keysyms; auto keysyms_len = xkb_state_key_get_syms(keyboard->xkb_state, keycode, &keysyms); for (int i = 0; i < keysyms_len; i++) { auto key = keysyms[i]; if ((key == XKB_KEY_Alt_L) || (key == XKB_KEY_Alt_R)) { return WLR_MODIFIER_ALT; } if ((key == XKB_KEY_Control_L) || (key == XKB_KEY_Control_R)) { return WLR_MODIFIER_CTRL; } if ((key == XKB_KEY_Shift_L) || (key == XKB_KEY_Shift_R)) { return WLR_MODIFIER_SHIFT; } if ((key == XKB_KEY_Super_L) || (key == XKB_KEY_Super_R)) { return WLR_MODIFIER_LOGO; } } return 0; } std::vector<std::function<bool()>> input_manager::match_keys(uint32_t mod_state, uint32_t key, uint32_t mod_binding_key) { std::vector<std::function<bool()>> callbacks; uint32_t actual_key = key == 0 ? mod_binding_key : key; for (auto& binding : bindings[WF_BINDING_KEY]) { auto as_key = std::dynamic_pointer_cast< wf::config::option_t<wf::keybinding_t>>(binding->value); assert(as_key); if ((as_key->get_value() == wf::keybinding_t{mod_state, key}) && (binding->output == wf::get_core().get_active_output())) { /* We must be careful because the callback might be erased, * so force copy the callback into the lambda */ auto callback = binding->call.key; callbacks.push_back([actual_key, callback] () { return (*callback)(actual_key); }); } } for (auto& binding : bindings[WF_BINDING_ACTIVATOR]) { auto as_activator = std::dynamic_pointer_cast< wf::config::option_t<wf::activatorbinding_t>>(binding->value); assert(as_activator); if (as_activator->get_value().has_match(wf::keybinding_t{mod_state, key}) && (binding->output == wf::get_core().get_active_output())) { /* We must be careful because the callback might be erased, * so force copy the callback into the lambda * * Also, do not send keys for modifier bindings */ auto callback = binding->call.activator; callbacks.push_back([=] () { return (*callback)(wf::ACTIVATOR_SOURCE_KEYBINDING, mod_from_key(seat, actual_key) ? 0 : actual_key); }); } } return callbacks; } void update_keyboard_locked_mods(wlr_keyboard *kbd, xkb_mod_mask_t& locked_mods) { uint32_t leds = 0; for (uint32_t i = 0; i < WLR_LED_COUNT; i++) { if (xkb_state_led_index_is_active( kbd->xkb_state, kbd->led_indexes[i])) { leds |= (1 << i); } } if (leds & WLR_LED_NUM_LOCK) { locked_mods |= WF_KB_NUM; } else { locked_mods &= ~WF_KB_NUM; } if (leds & WLR_LED_CAPS_LOCK) { locked_mods |= WF_KB_CAPS; } else { locked_mods &= ~WF_KB_CAPS; } } bool input_manager::handle_keyboard_key(uint32_t key, uint32_t state) { using namespace std::chrono; if (active_grab && active_grab->callbacks.keyboard.key) { active_grab->callbacks.keyboard.key(key, state); } auto mod = mod_from_key(seat, key); if (mod) { handle_keyboard_mod(mod, state); } std::vector<std::function<bool()>> callbacks; auto kbd = wlr_seat_get_keyboard(seat); update_keyboard_locked_mods(kbd, locked_mods); if (state == WLR_KEY_PRESSED) { auto session = wlr_backend_get_session(wf::get_core().backend); if (check_vt_switch(session, key, get_modifiers())) { return true; } /* as long as we have pressed only modifiers, we should check for modifier * bindings on release */ if (mod) { bool modifiers_only = !lpointer->has_pressed_buttons() && (touch->get_state().fingers.empty()); for (size_t i = 0; kbd && i < kbd->num_keycodes; i++) { if (!mod_from_key(seat, kbd->keycodes[i])) { modifiers_only = false; } } if (modifiers_only) { mod_binding_start = steady_clock::now(); mod_binding_key = key; } } else { mod_binding_key = 0; } callbacks = match_keys(get_modifiers(), key); } else { if (mod_binding_key != 0) { int timeout = wf::option_wrapper_t<int>( "input/modifier_binding_timeout"); if ((timeout <= 0) || (duration_cast<milliseconds>(steady_clock::now() - mod_binding_start) <= milliseconds(timeout))) { callbacks = match_keys(get_modifiers() | mod, 0, mod_binding_key); } } mod_binding_key = 0; } bool keybinding_handled = false; for (auto call : callbacks) { keybinding_handled |= call(); } auto iv = interactive_view_from_view(keyboard_focus.get()); if (iv) { iv->handle_key(key, state); } return active_grab || keybinding_handled; } void input_manager::handle_keyboard_mod(uint32_t modifier, uint32_t state) { if (active_grab && active_grab->callbacks.keyboard.mod) { active_grab->callbacks.keyboard.mod(modifier, state); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: menumanager.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: cd $ $Date: 2001-05-02 05:42:28 $ * * 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 __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ #define __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_ #include <com/sun/star/frame/FeatureStateEvent.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef __SGI_STL_VECTOR #include <stl/vector> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef __FRAMEWORK_HELPER_OMUTEXMEMBER_HXX_ #include <helper/omutexmember.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #define REFERENCE ::com::sun::star::uno::Reference #define XFRAME ::com::sun::star::frame::XFrame #define XDISPATCH ::com::sun::star::frame::XDispatch #define XDISPATCHPROVIDER ::com::sun::star::frame::XDispatchProvider #define XSTATUSLISTENER ::com::sun::star::frame::XStatusListener #define XEVENTLISTENER ::com::sun::star::lang::XEventListener #define FEATURSTATEEVENT ::com::sun::star::frame::FeatureStateEvent #define RUNTIMEEXCEPTION ::com::sun::star::uno::RuntimeException #define EVENTOBJECT ::com::sun::star::lang::EventObject #define BMKMENU_ITEMID_START 20000 namespace framework { class MenuManager : public XSTATUSLISTENER , public OMutexMember , public ::cppu::OWeakObject { public: MenuManager( REFERENCE< XFRAME >& rFrame, Menu* pMenu, sal_Bool bDelete, sal_Bool bDeleteChildren, sal_Bool bIsBookmarkMenu = sal_False ); virtual ~MenuManager(); // XInterface virtual void SAL_CALL acquire() throw( RUNTIMEEXCEPTION ) { OWeakObject::acquire(); } virtual void SAL_CALL release() throw( RUNTIMEEXCEPTION ) { OWeakObject::release(); } virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( RUNTIMEEXCEPTION ); // XStatusListener virtual void SAL_CALL statusChanged( const FEATURSTATEEVENT& Event ) throw ( RUNTIMEEXCEPTION ); // XEventListener virtual void SAL_CALL disposing( const EVENTOBJECT& Source ) throw ( RUNTIMEEXCEPTION ); DECL_LINK( Select, Menu * ); Menu* GetMenu() const { return m_pVCLMenu; } protected: DECL_LINK( Highlight, Menu * ); DECL_LINK( Activate, Menu * ); DECL_LINK( Deactivate, Menu * ); private: void UpdateSpecialFileMenu( Menu* pMenu ); void UpdateSpecialWindowMenu( Menu* pMenu ); PopupMenu* CreateBookmarkMenu( const ::rtl::OUString aURL, const ::rtl::OUString aReferer ); struct MenuItemHandler { MenuItemHandler( USHORT aItemId, MenuManager* pManager, REFERENCE< XDISPATCH >& rDispatch ) : nItemId( aItemId ), pSubMenuManager( pManager ), xMenuItemDispatch( rDispatch ) {} USHORT nItemId; ::rtl::OUString aMenuItemURL; ::rtl::OUString aFilter; ::rtl::OUString aPassword; ::rtl::OUString aTitle; MenuManager* pSubMenuManager; REFERENCE< XDISPATCH > xMenuItemDispatch; }; MenuItemHandler* GetMenuItemHandler( USHORT nItemId ); sal_Bool m_bInitialized; sal_Bool m_bDeleteMenu; sal_Bool m_bDeleteChildren; sal_Bool m_bActive; sal_Bool m_bIsBookmarkMenu; ::rtl::OUString m_aMenuItemCommand; Menu* m_pVCLMenu; REFERENCE< XFRAME > m_xFrame; ::std::vector< MenuItemHandler* > m_aMenuItemHandlerVector; }; } // namespace #endif <commit_msg>support for images<commit_after>/************************************************************************* * * $RCSfile: menumanager.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: cd $ $Date: 2001-05-03 08:03:31 $ * * 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 __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ #define __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_ #include <com/sun/star/frame/FeatureStateEvent.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef __SGI_STL_VECTOR #include <stl/vector> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef __FRAMEWORK_HELPER_OMUTEXMEMBER_HXX_ #include <helper/omutexmember.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #define REFERENCE ::com::sun::star::uno::Reference #define XFRAME ::com::sun::star::frame::XFrame #define XDISPATCH ::com::sun::star::frame::XDispatch #define XDISPATCHPROVIDER ::com::sun::star::frame::XDispatchProvider #define XSTATUSLISTENER ::com::sun::star::frame::XStatusListener #define XEVENTLISTENER ::com::sun::star::lang::XEventListener #define FEATURSTATEEVENT ::com::sun::star::frame::FeatureStateEvent #define RUNTIMEEXCEPTION ::com::sun::star::uno::RuntimeException #define EVENTOBJECT ::com::sun::star::lang::EventObject #define BMKMENU_ITEMID_START 20000 namespace framework { class BmkMenu; class MenuManager : public XSTATUSLISTENER , public OMutexMember , public ::cppu::OWeakObject { public: MenuManager( REFERENCE< XFRAME >& rFrame, Menu* pMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); MenuManager( REFERENCE< XFRAME >& rFrame, BmkMenu* pBmkMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); virtual ~MenuManager(); // XInterface virtual void SAL_CALL acquire() throw( RUNTIMEEXCEPTION ) { OWeakObject::acquire(); } virtual void SAL_CALL release() throw( RUNTIMEEXCEPTION ) { OWeakObject::release(); } virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( RUNTIMEEXCEPTION ); // XStatusListener virtual void SAL_CALL statusChanged( const FEATURSTATEEVENT& Event ) throw ( RUNTIMEEXCEPTION ); // XEventListener virtual void SAL_CALL disposing( const EVENTOBJECT& Source ) throw ( RUNTIMEEXCEPTION ); DECL_LINK( Select, Menu * ); Menu* GetMenu() const { return m_pVCLMenu; } protected: DECL_LINK( Highlight, Menu * ); DECL_LINK( Activate, Menu * ); DECL_LINK( Deactivate, Menu * ); private: void UpdateSpecialFileMenu( Menu* pMenu ); void UpdateSpecialWindowMenu( Menu* pMenu ); BmkMenu* CreateBookmarkMenu( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL ); struct MenuItemHandler { MenuItemHandler( USHORT aItemId, MenuManager* pManager, REFERENCE< XDISPATCH >& rDispatch ) : nItemId( aItemId ), pSubMenuManager( pManager ), xMenuItemDispatch( rDispatch ) {} USHORT nItemId; ::rtl::OUString aTargetFrame; ::rtl::OUString aMenuItemURL; ::rtl::OUString aFilter; ::rtl::OUString aPassword; ::rtl::OUString aTitle; MenuManager* pSubMenuManager; REFERENCE< XDISPATCH > xMenuItemDispatch; }; void CreatePicklistArguments( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgsList, const MenuItemHandler* ); MenuItemHandler* GetMenuItemHandler( USHORT nItemId ); sal_Bool m_bInitialized; sal_Bool m_bDeleteMenu; sal_Bool m_bDeleteChildren; sal_Bool m_bActive; sal_Bool m_bIsBookmarkMenu; ::rtl::OUString m_aMenuItemCommand; Menu* m_pVCLMenu; REFERENCE< XFRAME > m_xFrame; ::std::vector< MenuItemHandler* > m_aMenuItemHandlerVector; }; } // namespace #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleJoystickCamera.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkInteractorStyleJoystickCamera.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkInteractorStyleJoystickCamera *vtkInteractorStyleJoystickCamera::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkInteractorStyleJoystickCamera"); if(ret) { return (vtkInteractorStyleJoystickCamera*)ret; } // If the factory was unable to create the object, then create it here. return new vtkInteractorStyleJoystickCamera; } //---------------------------------------------------------------------------- vtkInteractorStyleJoystickCamera::vtkInteractorStyleJoystickCamera() { this->MotionFactor = 10.0; this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- vtkInteractorStyleJoystickCamera::~vtkInteractorStyleJoystickCamera() { } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnTimer(void) { vtkRenderWindowInteractor *rwi = this->Interactor; switch (this->State) { //----- case VTKIS_START: // JCP Animation control if (this->AnimState == VTKIS_ANIM_ON) { rwi->DestroyTimer(); rwi->Render(); rwi->CreateTimer(VTKI_TIMER_FIRST); } // JCP Animation control break; //----- case VTKIS_ROTATE: // rotate with respect to an axis perp to look this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->RotateCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTKIS_PAN: // move perpendicular to camera's look vector this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->PanCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTKIS_ZOOM: this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->DollyCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTKIS_SPIN: this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->SpinCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTKIS_DOLLY: // move along camera's view vector break; //----- case VTKIS_USCALE: break; //----- case VTKIS_TIMER: rwi->Render(); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- default : break; } } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnMouseMove(int vtkNotUsed(ctrl), int vtkNotUsed(shift), int x, int y) { this->LastPos[0] = x; this->LastPos[1] = y; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnLeftButtonDown(int ctrl, int shift, int x, int y) { this->FindPokedRenderer(x, y); if (this->CurrentRenderer == NULL) { vtkErrorMacro("CurrentRenderer is NULL"); return; } this->UpdateInternalState(ctrl, shift, x, y); if (this->CtrlKey) { this->StartSpin(); this->State = VTK_INTERACTOR_STYLE_CAMERA_SPIN; } else { this->StartRotate(); this->State = VTK_INTERACTOR_STYLE_CAMERA_ROTATE; } } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnLeftButtonUp(int ctrl, int shift, int x, int y) { if (this->State == VTK_INTERACTOR_STYLE_CAMERA_ROTATE) { this->EndRotate(); } else { this->EndSpin(); } this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnMiddleButtonDown(int ctrl, int shift, int x, int y) { this->FindPokedRenderer(x, y); if (this->CurrentRenderer == NULL) { return; } this->StartPan(); this->State = VTK_INTERACTOR_STYLE_CAMERA_PAN; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnMiddleButtonUp(int ctrl, int shift, int x, int y) { this->EndPan(); this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnRightButtonDown(int ctrl, int shift, int x, int y) { this->FindPokedRenderer(x, y); if (this->CurrentRenderer == NULL) { return; } this->StartZoom(); this->State = VTK_INTERACTOR_STYLE_CAMERA_ZOOM; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnRightButtonUp(int ctrl, int shift, int x, int y) { this->EndZoom(); this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::PrintSelf(ostream& os, vtkIndent indent) { vtkInteractorStyle::PrintSelf(os,indent); } <commit_msg>In the process of putting the interactor styles in separate classes, I managed to reverse the function of the middle and right mouse buttons in vtkInteractorStyleJoystickCamera. This puts them back the way they were before.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleJoystickCamera.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkInteractorStyleJoystickCamera.h" #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkInteractorStyleJoystickCamera *vtkInteractorStyleJoystickCamera::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkInteractorStyleJoystickCamera"); if(ret) { return (vtkInteractorStyleJoystickCamera*)ret; } // If the factory was unable to create the object, then create it here. return new vtkInteractorStyleJoystickCamera; } //---------------------------------------------------------------------------- vtkInteractorStyleJoystickCamera::vtkInteractorStyleJoystickCamera() { this->MotionFactor = 10.0; this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- vtkInteractorStyleJoystickCamera::~vtkInteractorStyleJoystickCamera() { } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnTimer(void) { vtkRenderWindowInteractor *rwi = this->Interactor; switch (this->State) { //----- case VTKIS_START: // JCP Animation control if (this->AnimState == VTKIS_ANIM_ON) { rwi->DestroyTimer(); rwi->Render(); rwi->CreateTimer(VTKI_TIMER_FIRST); } // JCP Animation control break; //----- case VTK_INTERACTOR_STYLE_CAMERA_ROTATE: // rotate with respect to an axis perp to look this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->RotateCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTK_INTERACTOR_STYLE_CAMERA_PAN: // move perpendicular to camera's look vector this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->PanCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTK_INTERACTOR_STYLE_CAMERA_ZOOM: this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->DollyCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTK_INTERACTOR_STYLE_CAMERA_SPIN: this->FindPokedCamera(this->LastPos[0], this->LastPos[1]); this->SpinCamera(this->LastPos[0], this->LastPos[1]); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- case VTKIS_TIMER: rwi->Render(); rwi->CreateTimer(VTKI_TIMER_UPDATE); break; //----- default : break; } } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnMouseMove(int vtkNotUsed(ctrl), int vtkNotUsed(shift), int x, int y) { this->LastPos[0] = x; this->LastPos[1] = y; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnLeftButtonDown(int ctrl, int shift, int x, int y) { this->FindPokedRenderer(x, y); if (this->CurrentRenderer == NULL) { vtkErrorMacro("CurrentRenderer is NULL"); return; } this->UpdateInternalState(ctrl, shift, x, y); if (this->CtrlKey) { this->StartSpin(); this->State = VTK_INTERACTOR_STYLE_CAMERA_SPIN; } else { this->StartRotate(); this->State = VTK_INTERACTOR_STYLE_CAMERA_ROTATE; } } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnLeftButtonUp(int ctrl, int shift, int x, int y) { if (this->State == VTK_INTERACTOR_STYLE_CAMERA_ROTATE) { this->EndRotate(); } else { this->EndSpin(); } this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnMiddleButtonDown(int ctrl, int shift, int x, int y) { this->FindPokedRenderer(x, y); if (this->CurrentRenderer == NULL) { return; } this->StartPan(); this->State = VTK_INTERACTOR_STYLE_CAMERA_PAN; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnMiddleButtonUp(int ctrl, int shift, int x, int y) { this->EndPan(); this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnRightButtonDown(int ctrl, int shift, int x, int y) { this->FindPokedRenderer(x, y); if (this->CurrentRenderer == NULL) { return; } this->StartZoom(); this->State = VTK_INTERACTOR_STYLE_CAMERA_ZOOM; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::OnRightButtonUp(int ctrl, int shift, int x, int y) { this->EndZoom(); this->State = VTK_INTERACTOR_STYLE_CAMERA_NONE; } //---------------------------------------------------------------------------- void vtkInteractorStyleJoystickCamera::PrintSelf(ostream& os, vtkIndent indent) { vtkInteractorStyle::PrintSelf(os,indent); } <|endoftext|>
<commit_before>// Copyright (c) 2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypto/hmac_sha256.h" #include <string.h> CHMAC_SHA256::CHMAC_SHA256(const unsigned char* key, size_t keylen) { unsigned char rkey[64]; if (keylen <= 64) { memcpy(rkey, key, keylen); memset(rkey + keylen, 0, 64 - keylen); } else { CSHA256().Write(key, keylen).Finalize(rkey); memset(rkey + 32, 0, 32); } for (int n = 0; n < 64; n++) rkey[n] ^= 0x5c; outer.Write(rkey, 64); for (int n = 0; n < 64; n++) rkey[n] ^= 0x5c ^ 0x36; inner.Write(rkey, 64); } void CHMAC_SHA256::Finalize(unsigned char hash[OUTPUT_SIZE]) { unsigned char temp[32]; inner.Finalize(temp); outer.Write(temp, 32).Finalize(hash); } <commit_msg>Delete hmac_sha256.cpp<commit_after><|endoftext|>
<commit_before>#include <os> #include <net/inet4> #include <math.h> #include <iostream> #include <sstream> //#include <thread> => <thread> is not supported on this single threaded system using namespace std::chrono; void Service::start() { // Wonder when these are used...? std::set_terminate([](){ printf("CUSTOM TERMINATE Handler \n"); }); std::set_new_handler([](){ printf("CUSTOM NEW Handler \n"); }); // TODO: find some implementation for long double, or not... or use double //auto sine = sinl(42); // Assign an IP-address, using Hårek-mapping :-) auto& mac = Dev::eth(0).mac(); net::Inet4::ifconfig(net::ETH0, {{ mac.part[2],mac.part[3],mac.part[4],mac.part[5] }}, {{ 255,255,0,0 }} ); // Bring up the interface net::Inet4* inet = net::Inet4::up(); std::cout << "Service IP address: " << net::Inet4::ip4(net::ETH0) << std::endl; // Set up a server on port 80 net::TCP::Socket& sock = inet->tcp().bind(80); printf("SERVICE: %i open ports in TCP @ %p \n", inet->tcp().openPorts(), &(inet->tcp())); srand(OS::cycles_since_boot()); sock.onConnect([](net::TCP::Socket& conn){ printf("SERVICE got data: %s \n",conn.read(1024).c_str()); int color = rand(); std::stringstream stream; std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; "; std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; "; std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; "; stream << "<html><head>" << "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>" << "</head><body>" << "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">" << "<span style=\""+ubuntu_medium+"\">Include</span><span style=\""+ubuntu_light+"\">OS</span> </h1>" << "<h2>Now speaks TCP!</h2>" // .... generate more dynamic content << "<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far </p>" << "<footer><hr /> &copy; 2015, Oslo and Akershus University College of Applied Sciences </footer>" << "</body></html>\n"; std::string html = stream.str(); std::string header="HTTP/1.1 200 OK \n " \ "Date: Mon, 01 Jan 1970 00:00:01 GMT \n" \ "Server: IncludeOS prototype 4.0 \n" \ "Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n" \ "Content-Type: text/html; charset=UTF-8 \n" \ "Content-Length: "+std::to_string(html.size())+"\n" \ "Accept-Ranges: bytes\n" \ "Connection: close\n\n"; conn.write(header); conn.write(html); // We don't have to actively close when the http-header says "Connection: close" //conn.close(); }); uint64_t my_llu = 42; printf("BUG? My llu is: %llu, and 42 == %i \n",my_llu, 42); printf("*** SERVICE STARTED *** \n"); } <commit_msg>Clean out cout<commit_after>#include <os> #include <net/inet4> #include <math.h> #include <iostream> #include <sstream> //#include <thread> => <thread> is not supported on this single threaded system using namespace std::chrono; void Service::start() { // Wonder when these are used...? std::set_terminate([](){ printf("CUSTOM TERMINATE Handler \n"); }); std::set_new_handler([](){ printf("CUSTOM NEW Handler \n"); }); // TODO: find some implementation for long double, or not... or use double //auto sine = sinl(42); // Assign an IP-address, using Hårek-mapping :-) auto& mac = Dev::eth(0).mac(); net::Inet4::ifconfig(net::ETH0, {{ mac.part[2],mac.part[3],mac.part[4],mac.part[5] }}, {{ 255,255,0,0 }} ); // Bring up the interface net::Inet4* inet = net::Inet4::up(); printf("Service IP address: %s \n", net::Inet4::ip4(net::ETH0).str().c_str()); // Set up a server on port 80 net::TCP::Socket& sock = inet->tcp().bind(80); printf("SERVICE: %i open ports in TCP @ %p \n", inet->tcp().openPorts(), &(inet->tcp())); srand(OS::cycles_since_boot()); sock.onConnect([](net::TCP::Socket& conn){ printf("SERVICE got data: %s \n",conn.read(1024).c_str()); int color = rand(); std::stringstream stream; std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; "; std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; "; std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; "; stream << "<html><head>" << "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>" << "</head><body>" << "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">" << "<span style=\""+ubuntu_medium+"\">Include</span><span style=\""+ubuntu_light+"\">OS</span> </h1>" << "<h2>Now speaks TCP!</h2>" // .... generate more dynamic content << "<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far </p>" << "<footer><hr /> &copy; 2015, Oslo and Akershus University College of Applied Sciences </footer>" << "</body></html>\n"; std::string html = stream.str(); std::string header="HTTP/1.1 200 OK \n " \ "Date: Mon, 01 Jan 1970 00:00:01 GMT \n" \ "Server: IncludeOS prototype 4.0 \n" \ "Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n" \ "Content-Type: text/html; charset=UTF-8 \n" \ "Content-Length: "+std::to_string(html.size())+"\n" \ "Accept-Ranges: bytes\n" \ "Connection: close\n\n"; conn.write(header); conn.write(html); // We don't have to actively close when the http-header says "Connection: close" //conn.close(); }); uint64_t my_llu = 42; printf("BUG? My llu is: %llu, and 42 == %i \n",my_llu, 42); printf("*** SERVICE STARTED *** \n"); } <|endoftext|>
<commit_before>/// /// @file S2.hpp. /// @brief S2 function declarations. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef S2_HPP #define S2_HPP #include <PiTable.hpp> #include <FactorTable.hpp> #include <int128.hpp> #include <stdint.h> #include <vector> namespace primecount { /// ------------------------ S2_trivial() ---------------------------- int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, std::vector<int32_t>& pi, std::vector<int32_t>& primes, int threads); int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int32_t>& primes, int threads); #ifdef HAVE_INT128_T int128_t S2_trivial(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<uint32_t>& primes, int threads); int128_t S2_trivial(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int64_t>& primes, int threads); #endif /// ------------------------ S2_easy() ------------------------------- int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, std::vector<int32_t>& pi, std::vector<int32_t>& primes, int threads); int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int32_t>& primes, int threads); #ifdef HAVE_INT128_T int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<uint32_t>& primes, int threads); int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int64_t>& primes, int threads); #endif /// ------------------------ S2_sieve() ------------------------------ int64_t S2_sieve(int64_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int32_t>& primes, FactorTable<uint16_t>& factors, int threads); #ifdef HAVE_INT128_T int128_t S2_sieve(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<uint32_t>& primes, FactorTable<uint16_t>& factors, int threads); int128_t S2_sieve(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int64_t>& primes, FactorTable<uint32_t>& factors, int threads); #endif } // namespace primecount #endif <commit_msg>Add s2_sieve_approx<commit_after>/// /// @file S2.hpp. /// @brief S2 function declarations. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef S2_HPP #define S2_HPP #include <PiTable.hpp> #include <FactorTable.hpp> #include <int128.hpp> #include <stdint.h> #include <vector> namespace primecount { /// ------------------------ S2_trivial() ---------------------------- int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, std::vector<int32_t>& pi, std::vector<int32_t>& primes, int threads); int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int32_t>& primes, int threads); #ifdef HAVE_INT128_T int128_t S2_trivial(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<uint32_t>& primes, int threads); int128_t S2_trivial(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int64_t>& primes, int threads); #endif /// ------------------------ S2_easy() ------------------------------- int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, std::vector<int32_t>& pi, std::vector<int32_t>& primes, int threads); int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int32_t>& primes, int threads); #ifdef HAVE_INT128_T int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<uint32_t>& primes, int threads); int128_t S2_easy(uint128_t x, int64_t y, int64_t z, int64_t c, PiTable& pi, std::vector<int64_t>& primes, int threads); #endif /// ------------------------ S2_sieve() ------------------------------ int64_t S2_sieve(int64_t x, int64_t y, int64_t z, int64_t c, int64_t s2_sieve_approx, PiTable& pi, std::vector<int32_t>& primes, FactorTable<uint16_t>& factors, int threads); #ifdef HAVE_INT128_T int128_t S2_sieve(uint128_t x, int64_t y, int64_t z, int64_t c, uint128_t s2_sieve_approx, PiTable& pi, std::vector<uint32_t>& primes, FactorTable<uint16_t>& factors, int threads); int128_t S2_sieve(uint128_t x, int64_t y, int64_t z, int64_t c, uint128_t s2_sieve_approx, PiTable& pi, std::vector<int64_t>& primes, FactorTable<uint32_t>& factors, int threads); #endif } // namespace primecount #endif <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file PredicateMask.cpp * @author Peter Schueller <[email protected]> * * @brief Incrementally managed bitmask for projecting ground * interpretations to certain predicates. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex/PredicateMask.hpp" #include "dlvhex/Interpretation.hpp" #include "dlvhex/Logger.hpp" #include "dlvhex/Printhelpers.hpp" #include "dlvhex/Registry.hpp" #include "dlvhex/Printer.hpp" #include "dlvhex/OrdinaryAtomTable.hpp" #include <boost/foreach.hpp> DLVHEX_NAMESPACE_BEGIN PredicateMask::PredicateMask(): maski(), knownAddresses(0) { } PredicateMask::~PredicateMask() { } void PredicateMask::setRegistry(RegistryPtr reg) { assert((!maski || maski->getRegistry() == reg) && "PredicateMask cannot change registry!"); if( !maski ) { maski.reset(new Interpretation(reg)); } } void PredicateMask::addPredicate(ID pred) { assert(knownAddresses == 0 && "TODO implement incremental addition of predicates to mask"); // should be easy assert(pred.isTerm() && pred.isConstantTerm() && "predicate masks can only be done on constant terms"); predicates.insert(pred.address); } void PredicateMask::updateMask() { boost::mutex::scoped_lock lock(updateMutex); // lock ogatoms for reading -> no updates can happen while we are here // (this is necessary, otherwise the end iterator might change during execution) OrdinaryAtomTable::ReadLock oalock(reg->ogatoms.mutex); DBGLOG_VSCOPE(DBG,"PM::uM",this,false); DBGLOG(DBG,"= PredicateMask::updateMask for predicates " << printset(predicates)); assert(!!maski); RegistryPtr reg = maski->getRegistry(); Interpretation::Storage& bits = maski->getStorage(); // get range over all ogatoms OrdinaryAtomTable::AddressIterator it_begin, it, it_end; boost::tie(it_begin, it_end) = reg->ogatoms.getAllByAddress(); // check if we have unknown atoms DBGLOG(DBG,"already inspected ogatoms with address < " << knownAddresses << ", iterator range has size " << (it_end - it_begin)); if( (it_end - it_begin) == knownAddresses ) return; // if not equal, it must be larger -> we must inspect assert((it_end - it_begin) > knownAddresses); // advance iterator to first ogatom unknown to predicateInputMask it = it_begin; it += knownAddresses; unsigned missingBits = it_end - it; DBGLOG(DBG,"need to inspect " << missingBits << " missing bits"); // check all new ogatoms till the end #ifndef NDEBUG { std::stringstream s; s << "relevant predicate constants are "; RawPrinter printer(s, reg); BOOST_FOREACH(IDAddress addr, predicates) { printer.print(ID(ID::MAINKIND_TERM | ID::SUBKIND_TERM_CONSTANT, addr)); s << ", "; } DBGLOG(DBG,s.str()); } #endif assert(knownAddresses == (it - it_begin)); for(;it != it_end; ++it) { const OrdinaryAtom& oatom = *it; //DBGLOG(DBG,"checking " << oatom.tuple.front()); IDAddress addr = oatom.tuple.front().address; if( predicates.find(addr) != predicates.end() ) { bits.set(it - it_begin); } } knownAddresses = (it_end - it_begin); DBGLOG(DBG,"updateMask created new set of relevant ogatoms: " << *maski << " and knownAddresses is " << knownAddresses); } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <commit_msg>fixing race condition in PredicateMask without extra mutex (such a mutex would need to be recursive and this is not possible with a shared mutex)<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file PredicateMask.cpp * @author Peter Schueller <[email protected]> * * @brief Incrementally managed bitmask for projecting ground * interpretations to certain predicates. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex/PredicateMask.hpp" #include "dlvhex/Interpretation.hpp" #include "dlvhex/Logger.hpp" #include "dlvhex/Printhelpers.hpp" #include "dlvhex/Registry.hpp" #include "dlvhex/Printer.hpp" #include "dlvhex/OrdinaryAtomTable.hpp" #include <boost/foreach.hpp> DLVHEX_NAMESPACE_BEGIN PredicateMask::PredicateMask(): maski(), knownAddresses(0) { } PredicateMask::~PredicateMask() { } void PredicateMask::setRegistry(RegistryPtr reg) { assert((!maski || maski->getRegistry() == reg) && "PredicateMask cannot change registry!"); if( !maski ) { maski.reset(new Interpretation(reg)); } } void PredicateMask::addPredicate(ID pred) { assert(knownAddresses == 0 && "TODO implement incremental addition of predicates to mask"); // should be easy assert(pred.isTerm() && pred.isConstantTerm() && "predicate masks can only be done on constant terms"); predicates.insert(pred.address); } void PredicateMask::updateMask() { DBGLOG_VSCOPE(DBG,"PM::uM",this,false); DBGLOG(DBG,"= PredicateMask::updateMask for predicates " << printset(predicates)); assert(!!maski); RegistryPtr reg = maski->getRegistry(); Interpretation::Storage& bits = maski->getStorage(); unsigned maxaddr = 0; OrdinaryAtomTable::AddressIterator it_begin; { // get one state of it_end, encoded in maxaddr // (we must not use it_end, as it is a generic object but denotes // different endpoints if ogatoms changes during this method) OrdinaryAtomTable::AddressIterator it_end; boost::tie(it_begin, it_end) = reg->ogatoms.getAllByAddress(); maxaddr = it_end - it_begin; } boost::mutex::scoped_lock lock(updateMutex); // check if we have unknown atoms DBGLOG(DBG,"already inspected ogatoms with address < " << knownAddresses << ", iterator range has size " << maxaddr); if( maxaddr == knownAddresses ) return; // if not equal, it must be larger -> we must inspect assert(maxaddr > knownAddresses); // advance iterator to first ogatom unknown to predicateInputMask OrdinaryAtomTable::AddressIterator it = it_begin; it += knownAddresses; unsigned missingBits = maxaddr - knownAddresses; DBGLOG(DBG,"need to inspect " << missingBits << " missing bits"); // check all new ogatoms till the end #ifndef NDEBUG { std::stringstream s; s << "relevant predicate constants are "; RawPrinter printer(s, reg); BOOST_FOREACH(IDAddress addr, predicates) { printer.print(ID(ID::MAINKIND_TERM | ID::SUBKIND_TERM_CONSTANT, addr)); s << ", "; } DBGLOG(DBG,s.str()); } #endif assert(knownAddresses == (it - it_begin)); for(;missingBits != 0; it++, missingBits--) { assert(it != reg->ogatoms.getAllByAddress().second); const OrdinaryAtom& oatom = *it; //DBGLOG(DBG,"checking " << oatom.tuple.front()); IDAddress addr = oatom.tuple.front().address; if( predicates.find(addr) != predicates.end() ) { bits.set(it - it_begin); } } knownAddresses += missingBits; DBGLOG(DBG,"updateMask created new set of relevant ogatoms: " << *maski << " and knownAddresses is " << knownAddresses); } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <|endoftext|>
<commit_before>/* ************************************************************************************ * * ftFluidFlow * * Created by Matthias Oostrik on 03/16.14. * Copyright 2014 http://www.MatthiasOostrik.com All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author 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. * * The Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones: * * Mark J Harris: Various online sources * * Patricio Gonzalez Vivo (http://www.patriciogonzalezvivo.com): ofxFluid * * ************************************************************************************ */ #include "ftFluidFlow.h" namespace flowTools { ftFluidFlow::ftFluidFlow(){ parameters.setName("fluid"); parameters.add(speed.set("speed", .5, 0, 1)); parameters.add(numJacobiIterations.set("iterations", 40, 1, 100)); parameters.add(viscosity.set("viscosity", 0.0, 0, 1)); parameters.add(vorticity.set("vorticity", 0.0, 0.0, 1)); dissipationParameters.setName("dissipation"); dissipationParameters.add(dissipationVel.set("velocity",0.0015, 0, 0.025)); dissipationParameters.add(dissipationDen.set("density", 0.0015, 0, 0.025)); dissipationParameters.add(dissipationPrs.set("pressure",0.025, 0, 0.1)); parameters.add(dissipationParameters); // smokeBuoyancyParameters.setName("smoke buoyancy"); // smokeBuoyancyParameters.add(smokeSigma.set("buoyancy", 0.5, 0.0, 1.0)); // smokeBuoyancyParameters.add(smokeWeight.set("weight", 0.05, 0.0, 1.0)); // smokeBuoyancyParameters.add(ambientTemperature.set("ambient temperature", 0.75, 0.0, 1.0)); // smokeBuoyancyParameters.add(gravity.set("gravity", ofDefaultVec2(0., -0.980665), ofDefaultVec2(-1, -1), ofDefaultVec2(1, 1))); // parameters.add(smokeBuoyancyParameters); } //-------------------------------------------------------------- void ftFluidFlow::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) { allocate(_simulationWidth, _simulationHeight, GL_RG32F, _densityWidth, _densityHeight, GL_RGBA32F); } void ftFluidFlow::allocate(int _simulationWidth, int _simulationHeight, GLint _simulationInternalFormat, int _densityWidth, int _densityHeight, GLint _densityInternalFormat) { simulationWidth = _simulationWidth; simulationHeight = _simulationHeight; densityWidth = _densityWidth; densityHeight = _densityHeight; ftFlow::allocate(simulationWidth, simulationHeight, _simulationInternalFormat, densityWidth, densityHeight, _densityInternalFormat); visualizationField.setup(simulationWidth, simulationHeight); temperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(temperatureFbo); pressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(pressureFbo); obstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8); ftUtil::zero(obstacleFbo); obstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGB32F); ftUtil::zero(obstacleOffsetFbo); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); divergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F); ftUtil::zero(divergenceFbo); smokeBuoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(smokeBuoyancyFbo); vorticityVelocityFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); vorticityConfinementFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); initObstacle(); } //-------------------------------------------------------------- void ftFluidFlow::update(float _deltaTime){ float timeStep = _deltaTime * speed.get() * simulationWidth; ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftPingPongFbo& velocityFbo = inputFbo; ftPingPongFbo& densityFbo = outputFbo; // ADVECT velocityFbo.swap(); advectShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), timeStep, 1.0 - dissipationVel.get()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // ADD FORCES: DIFFUSE if (viscosity.get() > 0.0) { for (int i = 0; i < numJacobiIterations.get(); i++) { velocityFbo.swap(); diffuseShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), viscosity.get()); } velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: VORTEX CONFINEMENT if (vorticity.get() > 0.0) { vorticityVelocityShader.update(vorticityVelocityFbo.get(), velocityFbo.getTexture()); vorticityVelocityFbo.swap(); applyObstacleShader.update(vorticityVelocityFbo.get(), vorticityVelocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 0.0); vorticityConfinementShader.update(vorticityConfinementFbo, vorticityVelocityFbo.getTexture(), timeStep, vorticity.get()); addVelocity(vorticityConfinementFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: SMOKE BUOYANCY // if (smokeSigma.get() > 0.0 && smokeWeight.get() > 0.0 ) { // temperatureFbo.swap(); // advectShader.update(temperatureFbo, temperatureFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); // temperatureFbo.swap(); // clampLengthShader.update(temperatureFbo, temperatureFbo.getBackTexture(), 2.0, 1.0); // temperatureFbo.swap(); // applyObstacleShader.update(temperatureFbo, temperatureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); // ftUtil::zero(smokeBuoyancyFbo); // smokeBuoyancyShader.update(smokeBuoyancyFbo, temperatureFbo.getTexture(), densityFbo.getTexture(), ambientTemperature.get(), timeStep, smokeSigma.get(), smokeWeight.get(), gravity.get()); // addVelocity(smokeBuoyancyFbo.getTexture()); // velocityFbo.swap(); // applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // } // else { // ftUtil::zero(temperatureFbo); // } // PRESSURE: DIVERGENCE // ftUtil::zero(divergenceFbo); divergenceShader.update(divergenceFbo, velocityFbo.getTexture()); // PRESSURE: JACOBI // ftUtil::zero(pressureFbo); pressureFbo.swap(); multiplyForceShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), 1.0 - dissipationPrs.get()); for (int i = 0; i < numJacobiIterations.get(); i++) { pressureFbo.swap(); jacobiShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), divergenceFbo.getTexture()); } pressureFbo.swap(); applyObstacleShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); // PRESSURE: SUBSTRACT GRADIENT velocityFbo.swap(); substractGradientShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), pressureFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // DENSITY: densityFbo.swap(); advectShader.update(densityFbo.get(), densityFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); // densityFbo.swap(); // clampLengthShader.update(densityFbo.get(), densityFbo.getBackTexture(), sqrt(3), 1.0); // densityFbo.swap(); // applyObstacleDensityShader.update(densityFbo.get(), densityFbo.getBackTexture(), obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) { switch (_type) { case FT_VELOCITY: setVelocity(_tex); break; case FT_DENSITY: setDensity(_tex); break; case FT_TEMPERATURE: setTemperature(_tex); break; case FT_PRESSURE: setPressure(_tex); break; case FT_OBSTACLE: setObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) { switch (_type) { case FT_VELOCITY: addVelocity(_tex, _strength); break; case FT_DENSITY: addDensity(_tex, _strength); break; case FT_TEMPERATURE: addTemperature(_tex, _strength); break; case FT_PRESSURE: addPressure(_tex, _strength); break; case FT_OBSTACLE: addObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::initObstacle(){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftUtil::one(obstacleFbo); obstacleFbo.begin(); ofSetColor(0,0,0,255); ofDrawRectangle(1, 1, obstacleFbo.getWidth()-2, obstacleFbo.getHeight()-2); obstacleFbo.end(); ofPopStyle(); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); } //-------------------------------------------------------------- void ftFluidFlow::setObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); initObstacle(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); ftUtil::zero(obstacleOffsetFbo); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::addObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); obstacleFbo.swap(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::reset() { ftFlow::reset(); ftUtil::zero(pressureFbo); ftUtil::zero(temperatureFbo); ftUtil::zero(divergenceFbo); ftUtil::zero(vorticityVelocityFbo); ftUtil::zero(vorticityConfinementFbo); ftUtil::zero(smokeBuoyancyFbo); initObstacle(); diffuseShader = ftDiffuseShader(); divergenceShader = ftDivergenceShader(); jacobiShader = ftJacobiShader(); substractGradientShader = ftSubstractGradientShader(); obstacleOffsetShader = ftObstacleOffsetShader(); applyObstacleShader = ftApplyObstacleShader(); } } <commit_msg>much better obstacle handling, also much slower<commit_after>/* ************************************************************************************ * * ftFluidFlow * * Created by Matthias Oostrik on 03/16.14. * Copyright 2014 http://www.MatthiasOostrik.com All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author 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. * * The Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones: * * Mark J Harris: Various online sources * * Patricio Gonzalez Vivo (http://www.patriciogonzalezvivo.com): ofxFluid * * ************************************************************************************ */ #include "ftFluidFlow.h" namespace flowTools { ftFluidFlow::ftFluidFlow(){ parameters.setName("fluid"); parameters.add(speed.set("speed", .5, 0, 1)); parameters.add(numJacobiIterations.set("iterations", 40, 1, 100)); parameters.add(viscosity.set("viscosity", 0.0, 0, 1)); parameters.add(vorticity.set("vorticity", 0.0, 0.0, 1)); dissipationParameters.setName("dissipation"); dissipationParameters.add(dissipationVel.set("velocity",0.0015, 0, 0.025)); dissipationParameters.add(dissipationDen.set("density", 0.0015, 0, 0.025)); dissipationParameters.add(dissipationPrs.set("pressure",0.025, 0, 0.1)); parameters.add(dissipationParameters); // smokeBuoyancyParameters.setName("smoke buoyancy"); // smokeBuoyancyParameters.add(smokeSigma.set("buoyancy", 0.5, 0.0, 1.0)); // smokeBuoyancyParameters.add(smokeWeight.set("weight", 0.05, 0.0, 1.0)); // smokeBuoyancyParameters.add(ambientTemperature.set("ambient temperature", 0.75, 0.0, 1.0)); // smokeBuoyancyParameters.add(gravity.set("gravity", ofDefaultVec2(0., -0.980665), ofDefaultVec2(-1, -1), ofDefaultVec2(1, 1))); // parameters.add(smokeBuoyancyParameters); } //-------------------------------------------------------------- void ftFluidFlow::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) { allocate(_simulationWidth, _simulationHeight, GL_RG32F, _densityWidth, _densityHeight, GL_RGBA32F); } void ftFluidFlow::allocate(int _simulationWidth, int _simulationHeight, GLint _simulationInternalFormat, int _densityWidth, int _densityHeight, GLint _densityInternalFormat) { simulationWidth = _simulationWidth; simulationHeight = _simulationHeight; densityWidth = _densityWidth; densityHeight = _densityHeight; ftFlow::allocate(simulationWidth, simulationHeight, _simulationInternalFormat, densityWidth, densityHeight, _densityInternalFormat); visualizationField.setup(simulationWidth, simulationHeight); temperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(temperatureFbo); pressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(pressureFbo); obstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8); ftUtil::zero(obstacleFbo); obstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGB32F); ftUtil::zero(obstacleOffsetFbo); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); divergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F); ftUtil::zero(divergenceFbo); smokeBuoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(smokeBuoyancyFbo); vorticityVelocityFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); vorticityConfinementFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); initObstacle(); } //-------------------------------------------------------------- void ftFluidFlow::update(float _deltaTime){ float timeStep = _deltaTime * speed.get() * simulationWidth; ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftPingPongFbo& velocityFbo = inputFbo; ftPingPongFbo& densityFbo = outputFbo; // ADVECT velocityFbo.swap(); advectShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), timeStep, 1.0 - dissipationVel.get()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // ADD FORCES: DIFFUSE if (viscosity.get() > 0.0) { for (int i = 0; i < numJacobiIterations.get(); i++) { velocityFbo.swap(); diffuseShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), viscosity.get()); } velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: VORTEX CONFINEMENT if (vorticity.get() > 0.0) { vorticityVelocityShader.update(vorticityVelocityFbo.get(), velocityFbo.getTexture()); vorticityVelocityFbo.swap(); applyObstacleShader.update(vorticityVelocityFbo.get(), vorticityVelocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 0.0); vorticityConfinementShader.update(vorticityConfinementFbo, vorticityVelocityFbo.getTexture(), timeStep, vorticity.get()); addVelocity(vorticityConfinementFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: SMOKE BUOYANCY // if (smokeSigma.get() > 0.0 && smokeWeight.get() > 0.0 ) { // temperatureFbo.swap(); // advectShader.update(temperatureFbo, temperatureFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); // temperatureFbo.swap(); // clampLengthShader.update(temperatureFbo, temperatureFbo.getBackTexture(), 2.0, 1.0); // temperatureFbo.swap(); // applyObstacleShader.update(temperatureFbo, temperatureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); // ftUtil::zero(smokeBuoyancyFbo); // smokeBuoyancyShader.update(smokeBuoyancyFbo, temperatureFbo.getTexture(), densityFbo.getTexture(), ambientTemperature.get(), timeStep, smokeSigma.get(), smokeWeight.get(), gravity.get()); // addVelocity(smokeBuoyancyFbo.getTexture()); // velocityFbo.swap(); // applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // } // else { // ftUtil::zero(temperatureFbo); // } // PRESSURE: DIVERGENCE // ftUtil::zero(divergenceFbo); divergenceShader.update(divergenceFbo, velocityFbo.getTexture()); // PRESSURE: JACOBI // ftUtil::zero(pressureFbo); pressureFbo.swap(); multiplyForceShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), 1.0 - dissipationPrs.get()); for (int i = 0; i < numJacobiIterations.get(); i++) { pressureFbo.swap(); jacobiShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), divergenceFbo.getTexture()); pressureFbo.swap(); applyObstacleShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); } // PRESSURE: SUBSTRACT GRADIENT velocityFbo.swap(); substractGradientShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), pressureFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // DENSITY: densityFbo.swap(); advectShader.update(densityFbo.get(), densityFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); // densityFbo.swap(); // clampLengthShader.update(densityFbo.get(), densityFbo.getBackTexture(), sqrt(3), 1.0); // densityFbo.swap(); // applyObstacleDensityShader.update(densityFbo.get(), densityFbo.getBackTexture(), obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) { switch (_type) { case FT_VELOCITY: setVelocity(_tex); break; case FT_DENSITY: setDensity(_tex); break; case FT_TEMPERATURE: setTemperature(_tex); break; case FT_PRESSURE: setPressure(_tex); break; case FT_OBSTACLE: setObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) { switch (_type) { case FT_VELOCITY: addVelocity(_tex, _strength); break; case FT_DENSITY: addDensity(_tex, _strength); break; case FT_TEMPERATURE: addTemperature(_tex, _strength); break; case FT_PRESSURE: addPressure(_tex, _strength); break; case FT_OBSTACLE: addObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::initObstacle(){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftUtil::one(obstacleFbo); obstacleFbo.begin(); ofSetColor(0,0,0,255); ofDrawRectangle(1, 1, obstacleFbo.getWidth()-2, obstacleFbo.getHeight()-2); obstacleFbo.end(); ofPopStyle(); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); } //-------------------------------------------------------------- void ftFluidFlow::setObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); initObstacle(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); ftUtil::zero(obstacleOffsetFbo); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::addObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); obstacleFbo.swap(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::reset() { ftFlow::reset(); ftUtil::zero(pressureFbo); ftUtil::zero(temperatureFbo); ftUtil::zero(divergenceFbo); ftUtil::zero(vorticityVelocityFbo); ftUtil::zero(vorticityConfinementFbo); ftUtil::zero(smokeBuoyancyFbo); initObstacle(); diffuseShader = ftDiffuseShader(); divergenceShader = ftDivergenceShader(); jacobiShader = ftJacobiShader(); substractGradientShader = ftSubstractGradientShader(); obstacleOffsetShader = ftObstacleOffsetShader(); applyObstacleShader = ftApplyObstacleShader(); } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "renderlayer2.h" #include "aabb2.h" #include "buffers.h" #include "camera2.h" #include "effect2.h" #include "matrix4.h" #include "particle.h" #include "perfcounter.h" #include "shadercache.h" #include "sprite.h" #include "textmeshinstance.h" #include "renderer2.h" #include "vertextypes2.h" namespace dukat { // module-global buffer for particle data used during rendering static ParticleVertex2 particle_data[Renderer2::max_particles]; RenderLayer2::RenderLayer2(ShaderCache* shader_cache, VertexBuffer* sprite_buffer, VertexBuffer* particle_buffer, const std::string& id, float priority, float parallax) : id(id), priority(priority), parallax(parallax), is_visible(true), shader_cache(shader_cache), sprite_buffer(sprite_buffer), particle_buffer(particle_buffer) { sprite_program = shader_cache->get_program("sc_sprite.vsh", "sc_sprite.fsh"); particle_program = shader_cache->get_program("sc_particle.vsh", "sc_particle.fsh"); } RenderLayer2::~RenderLayer2(void) { } void RenderLayer2::add(Sprite* sprite) { sprites.push_back(sprite); } void RenderLayer2::remove(Sprite* sprite) { sprites.erase(std::remove(sprites.begin(), sprites.end(), sprite), sprites.end()); } Effect2* RenderLayer2::add(std::unique_ptr<Effect2> fx) { auto res = fx.get(); fx->set_layer(this); effects.push_back(std::move(fx)); return res; } void RenderLayer2::remove(Effect2* fx) { fx->set_layer(nullptr); auto it = std::find_if(effects.begin(), effects.end(), [fx](const std::unique_ptr<Effect2>& ptr) -> bool { return fx == ptr.get(); }); if (it != effects.end()) { effects.erase(it, effects.end()); } } void RenderLayer2::add(Particle* particle) { particles.push_front(particle); } void RenderLayer2::remove(Particle* p) { particles.erase(std::remove(particles.begin(), particles.end(), p), particles.end()); } void RenderLayer2::add(TextMeshInstance * text) { texts.push_back(text); } void RenderLayer2::remove(TextMeshInstance* text) { texts.erase(std::remove(texts.begin(), texts.end(), text), texts.end()); } void RenderLayer2::render(Renderer2* renderer) { // Compute bounding box for current layer adjusted for parallax value auto camera = renderer->get_camera(); Vector2 camera_pos = camera->transform.position * parallax; Vector2 camera_dim = camera->transform.dimension / 2.0f; AABB2 camera_bb(camera_pos - camera_dim, camera_pos + camera_dim); // TODO: set up per-layer lighting here if (has_effects()) { render_effects(renderer, camera_bb); } if (has_sprites()) { render_sprites(renderer, camera_bb); } if (has_particles()) { render_particles(renderer, camera_bb); } if (has_text()) { render_text(renderer, camera_bb); } } void RenderLayer2::clear(void) { sprites.clear(); effects.clear(); particles.clear(); texts.clear(); } void RenderLayer2::fill_sprite_queue(const AABB2& camera_bb, std::priority_queue<Sprite*, std::deque<Sprite*>, SpriteComparator>& queue) { // Fill queue with sprites ordered by priority from low to high for (auto sprite : sprites) { if (sprite->relative) { // TODO: perform occlusion check against untranslated camera bounding box sprite->rendered = true; queue.push(sprite); perfc.inc(PerformanceCounter::SPRITES); } else { Vector2 half_dim(sprite->scale * sprite->w / 2.0f, sprite->scale * sprite->h / 2.0f); AABB2 sprite_bb(sprite->p - half_dim, sprite->p + half_dim); if (!camera_bb.overlaps(sprite_bb)) { sprite->rendered = false; } else { sprite->rendered = true; queue.push(sprite); perfc.inc(PerformanceCounter::SPRITES); } } } } void RenderLayer2::render_sprites(Renderer2* renderer, const AABB2& camera_bb) { std::priority_queue<Sprite*, std::deque<Sprite*>, SpriteComparator> queue; fill_sprite_queue(camera_bb, queue); if (queue.empty()) return; // nothing to render renderer->switch_shader(sprite_program); // Set parallax value for this layer glUniform1f(sprite_program->attr("u_parallax"), parallax); // bind sprite vertex buffers #if OPENGL_VERSION >= 30 glBindVertexArray(sprite_buffer->vao); glBindBuffer(GL_ARRAY_BUFFER, sprite_buffer->buffers[0]); // bind vertex position auto pos_id = sprite_program->attr(Renderer::at_pos); glEnableVertexAttribArray(pos_id); glVertexAttribPointer(pos_id, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, x))); // bind texture position auto uv_id = sprite_program->attr(Renderer::at_texcoord); glEnableVertexAttribArray(uv_id); glVertexAttribPointer(uv_id, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, u))); #else glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, sprite_buffer->buffers[0]); // bind vertex position glVertexPointer(2, GL_FLOAT, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, x))); // bind texture position glTexCoordPointer(2, GL_FLOAT, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, u))); #endif // set texture unit 0 glUniform1i(sprite_program->attr(Renderer::uf_tex0), 0); // Get uniforms that will be set for each sprite auto uvwh_id = sprite_program->attr("u_uvwh"); auto color_id = sprite_program->attr(Renderer::uf_color); auto model_id = sprite_program->attr(Renderer::uf_model); // Render in order GLuint last_texture = -1; Matrix4 mat_m; while (!queue.empty()) { // get top element from queue auto sprite = queue.top(); queue.pop(); // switch texture if necessary if (last_texture != sprite->texture_id) { perfc.inc(PerformanceCounter::TEXTURES); glActiveTextureARB(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sprite->texture_id); last_texture = sprite->texture_id; } compute_model_matrix(*sprite, renderer->get_camera()->transform.position, mat_m); glUniformMatrix4fv(model_id, 1, false, &mat_m.m[0]); glUniform4fv(color_id, 1, &sprite->color.r); glUniform4fv(uvwh_id, 1, sprite->tex); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } #ifdef _DEBUG #if OPENGL_VERSION >= 30 // unbind buffers glDisableVertexAttribArray(pos_id); glDisableVertexAttribArray(uv_id); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); #else glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif #endif } void RenderLayer2::compute_model_matrix(const Sprite& sprite, const Vector2& camera_position, Matrix4& mat_model) { Vector2 pos = sprite.p; // adjust position based on alignment if (sprite.center > 0) { if ((sprite.center & Sprite::align_bottom) == Sprite::align_bottom) { pos.y -= (sprite.h / 2) * sprite.scale; } else if ((sprite.center & Sprite::align_top) == Sprite::align_top) { pos.y += (sprite.h / 2) * sprite.scale; } if ((sprite.center & Sprite::align_right) == Sprite::align_right) { pos.x -= (sprite.w / 2) * sprite.scale; } else if ((sprite.center & Sprite::align_left) == Sprite::align_left) { pos.x += (sprite.w / 2) * sprite.scale; } } // if we're in relative addressing mode, transpose sprite // position by camera position. if (sprite.relative) { pos += camera_position; } if (sprite.pixel_aligned) { pos.x = std::round(pos.x); pos.y = std::round(pos.y); } // scale * rotation * translation static Matrix4 tmp; mat_model.setup_translation(Vector3(pos.x, pos.y, 0.0f)); if (sprite.rot != 0.0f) { tmp.setup_rotation(Vector3::unit_z, sprite.rot); mat_model *= tmp; } tmp.setup_scale(Vector3(sprite.scale * sprite.w, sprite.scale * sprite.h, 1.0f)); mat_model *= tmp; } void RenderLayer2::render_particles(Renderer2* renderer, const AABB2& camera_bb) { int particle_count = 0; for (auto it = particles.begin(); it != particles.end(); ) { Particle* p = (*it); // remove dead particles if (p->ttl <= 0) { it = particles.erase(it); continue; } // check if particle visible and store result in ->rendered if (p->rendered = camera_bb.contains(p->pos)) { particle_data[particle_count].x = p->pos.x; particle_data[particle_count].y = p->pos.y; particle_data[particle_count].size = p->size; particle_data[particle_count].r = p->color.r; particle_data[particle_count].g = p->color.g; particle_data[particle_count].b = p->color.b; particle_data[particle_count].a = p->color.a; perfc.inc(PerformanceCounter::PARTICLES); particle_count++; } ++it; } if (particle_count == 0) { return; // no particles left to render } renderer->switch_shader(particle_program); // Set parallax value for this layer glUniform1f(particle_program->attr("u_parallax"), parallax); #if OPENGL_VERSION >= 30 // bind particle vertex buffers glBindVertexArray(particle_buffer->vao); glBindBuffer(GL_ARRAY_BUFFER, particle_buffer->buffers[0]); // Orphan buffer to improve streaming performance glBufferData(GL_ARRAY_BUFFER, Renderer2::max_particles * sizeof(ParticleVertex2), nullptr, GL_STREAM_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, particle_count * sizeof(ParticleVertex2), particle_data); // bind vertex position auto pos_id = particle_program->attr(Renderer::at_pos); glEnableVertexAttribArray(pos_id); glVertexAttribPointer(pos_id, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, x))); // bind color position auto color_id = particle_program->attr(Renderer::at_color); glEnableVertexAttribArray(color_id); glVertexAttribPointer(color_id, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, r))); #else glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, particle_buffer->buffers[0]); // Orphan buffer to improve streaming performance glBufferData(GL_ARRAY_BUFFER, Renderer2::max_particles * sizeof(ParticleVertex2), NULL, GL_STREAM_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, particle_count * sizeof(ParticleVertex2), particle_data); // bind vertex position glVertexPointer(4, GL_FLOAT, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, x))); // bind color position glColorPointer(4, GL_FLOAT, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, r))); #endif glDrawArrays(GL_POINTS, 0, particle_count); #ifdef _DEBUG #if OPENGL_VERSION >= 30 glDisableVertexAttribArray(pos_id); glDisableVertexAttribArray(color_id); glBindVertexArray(0); #else glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); #endif glBindBuffer(GL_ARRAY_BUFFER, 0); #endif } void RenderLayer2::render_text(Renderer2* renderer, const AABB2& camera_bb) { // set up matrix once Matrix4 mat_identity; mat_identity.identity(); for (const auto& text : texts) { // TODO: perform boundary check text->render(renderer, mat_identity); } } void RenderLayer2::render_effects(Renderer2* renderer, const AABB2& camera_bb) { for (const auto& fx : effects) { fx->render(renderer, camera_bb); } } }<commit_msg>Fixed sprite clipping<commit_after>#include "stdafx.h" #include "renderlayer2.h" #include "aabb2.h" #include "buffers.h" #include "camera2.h" #include "effect2.h" #include "matrix4.h" #include "particle.h" #include "perfcounter.h" #include "shadercache.h" #include "sprite.h" #include "textmeshinstance.h" #include "renderer2.h" #include "vertextypes2.h" namespace dukat { // module-global buffer for particle data used during rendering static ParticleVertex2 particle_data[Renderer2::max_particles]; RenderLayer2::RenderLayer2(ShaderCache* shader_cache, VertexBuffer* sprite_buffer, VertexBuffer* particle_buffer, const std::string& id, float priority, float parallax) : id(id), priority(priority), parallax(parallax), is_visible(true), shader_cache(shader_cache), sprite_buffer(sprite_buffer), particle_buffer(particle_buffer) { sprite_program = shader_cache->get_program("sc_sprite.vsh", "sc_sprite.fsh"); particle_program = shader_cache->get_program("sc_particle.vsh", "sc_particle.fsh"); } RenderLayer2::~RenderLayer2(void) { } void RenderLayer2::add(Sprite* sprite) { sprites.push_back(sprite); } void RenderLayer2::remove(Sprite* sprite) { sprites.erase(std::remove(sprites.begin(), sprites.end(), sprite), sprites.end()); } Effect2* RenderLayer2::add(std::unique_ptr<Effect2> fx) { auto res = fx.get(); fx->set_layer(this); effects.push_back(std::move(fx)); return res; } void RenderLayer2::remove(Effect2* fx) { fx->set_layer(nullptr); auto it = std::find_if(effects.begin(), effects.end(), [fx](const std::unique_ptr<Effect2>& ptr) -> bool { return fx == ptr.get(); }); if (it != effects.end()) { effects.erase(it, effects.end()); } } void RenderLayer2::add(Particle* particle) { particles.push_front(particle); } void RenderLayer2::remove(Particle* p) { particles.erase(std::remove(particles.begin(), particles.end(), p), particles.end()); } void RenderLayer2::add(TextMeshInstance * text) { texts.push_back(text); } void RenderLayer2::remove(TextMeshInstance* text) { texts.erase(std::remove(texts.begin(), texts.end(), text), texts.end()); } void RenderLayer2::render(Renderer2* renderer) { // Compute bounding box for current layer adjusted for parallax value auto camera = renderer->get_camera(); Vector2 camera_pos = camera->transform.position * parallax; Vector2 camera_dim = camera->transform.dimension / 2.0f; AABB2 camera_bb(camera_pos - camera_dim, camera_pos + camera_dim); // TODO: set up per-layer lighting here if (has_effects()) { render_effects(renderer, camera_bb); } if (has_sprites()) { render_sprites(renderer, camera_bb); } if (has_particles()) { render_particles(renderer, camera_bb); } if (has_text()) { render_text(renderer, camera_bb); } } void RenderLayer2::clear(void) { sprites.clear(); effects.clear(); particles.clear(); texts.clear(); } void RenderLayer2::fill_sprite_queue(const AABB2& camera_bb, std::priority_queue<Sprite*, std::deque<Sprite*>, SpriteComparator>& queue) { // Fill queue with sprites ordered by priority from low to high for (auto sprite : sprites) { if (sprite->relative) { // TODO: perform occlusion check against untranslated camera bounding box sprite->rendered = true; queue.push(sprite); perfc.inc(PerformanceCounter::SPRITES); } else { Vector2 half_dim(sprite->scale * sprite->w / 2.0f, sprite->scale * sprite->h / 2.0f); auto min_p = sprite->p - half_dim; auto max_p = sprite->p + half_dim; if (sprite->center > 0) { if ((sprite->center & Sprite::align_bottom) == Sprite::align_bottom) { min_p.y -= (sprite->h / 2) * sprite->scale; max_p.y -= (sprite->h / 2) * sprite->scale; } else if ((sprite->center & Sprite::align_top) == Sprite::align_top) { min_p.y += (sprite->h / 2) * sprite->scale; max_p.y += (sprite->h / 2) * sprite->scale; } if ((sprite->center & Sprite::align_right) == Sprite::align_right) { min_p.x -= (sprite->w / 2) * sprite->scale; max_p.x -= (sprite->w / 2) * sprite->scale; } else if ((sprite->center & Sprite::align_left) == Sprite::align_left) { min_p.x += (sprite->w / 2) * sprite->scale; max_p.x += (sprite->w / 2) * sprite->scale; } } AABB2 sprite_bb(min_p, max_p); if (!camera_bb.overlaps(sprite_bb)) { sprite->rendered = false; } else { sprite->rendered = true; queue.push(sprite); perfc.inc(PerformanceCounter::SPRITES); } } } } void RenderLayer2::render_sprites(Renderer2* renderer, const AABB2& camera_bb) { std::priority_queue<Sprite*, std::deque<Sprite*>, SpriteComparator> queue; fill_sprite_queue(camera_bb, queue); if (queue.empty()) return; // nothing to render renderer->switch_shader(sprite_program); // Set parallax value for this layer glUniform1f(sprite_program->attr("u_parallax"), parallax); // bind sprite vertex buffers #if OPENGL_VERSION >= 30 glBindVertexArray(sprite_buffer->vao); glBindBuffer(GL_ARRAY_BUFFER, sprite_buffer->buffers[0]); // bind vertex position auto pos_id = sprite_program->attr(Renderer::at_pos); glEnableVertexAttribArray(pos_id); glVertexAttribPointer(pos_id, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, x))); // bind texture position auto uv_id = sprite_program->attr(Renderer::at_texcoord); glEnableVertexAttribArray(uv_id); glVertexAttribPointer(uv_id, 2, GL_FLOAT, GL_FALSE, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, u))); #else glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, sprite_buffer->buffers[0]); // bind vertex position glVertexPointer(2, GL_FLOAT, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, x))); // bind texture position glTexCoordPointer(2, GL_FLOAT, sizeof(TexturedVertex2), reinterpret_cast<const GLvoid*>(offsetof(TexturedVertex2, u))); #endif // set texture unit 0 glUniform1i(sprite_program->attr(Renderer::uf_tex0), 0); // Get uniforms that will be set for each sprite auto uvwh_id = sprite_program->attr("u_uvwh"); auto color_id = sprite_program->attr(Renderer::uf_color); auto model_id = sprite_program->attr(Renderer::uf_model); // Render in order GLuint last_texture = -1; Matrix4 mat_m; while (!queue.empty()) { // get top element from queue auto sprite = queue.top(); queue.pop(); // switch texture if necessary if (last_texture != sprite->texture_id) { perfc.inc(PerformanceCounter::TEXTURES); glActiveTextureARB(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sprite->texture_id); last_texture = sprite->texture_id; } compute_model_matrix(*sprite, renderer->get_camera()->transform.position, mat_m); glUniformMatrix4fv(model_id, 1, false, &mat_m.m[0]); glUniform4fv(color_id, 1, &sprite->color.r); glUniform4fv(uvwh_id, 1, sprite->tex); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } #ifdef _DEBUG #if OPENGL_VERSION >= 30 // unbind buffers glDisableVertexAttribArray(pos_id); glDisableVertexAttribArray(uv_id); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); #else glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif #endif } void RenderLayer2::compute_model_matrix(const Sprite& sprite, const Vector2& camera_position, Matrix4& mat_model) { Vector2 pos = sprite.p; // adjust position based on alignment if (sprite.center > 0) { if ((sprite.center & Sprite::align_bottom) == Sprite::align_bottom) { pos.y -= (sprite.h / 2) * sprite.scale; } else if ((sprite.center & Sprite::align_top) == Sprite::align_top) { pos.y += (sprite.h / 2) * sprite.scale; } if ((sprite.center & Sprite::align_right) == Sprite::align_right) { pos.x -= (sprite.w / 2) * sprite.scale; } else if ((sprite.center & Sprite::align_left) == Sprite::align_left) { pos.x += (sprite.w / 2) * sprite.scale; } } // if we're in relative addressing mode, transpose sprite // position by camera position. if (sprite.relative) { pos += camera_position; } if (sprite.pixel_aligned) { pos.x = std::round(pos.x); pos.y = std::round(pos.y); } // scale * rotation * translation static Matrix4 tmp; mat_model.setup_translation(Vector3(pos.x, pos.y, 0.0f)); if (sprite.rot != 0.0f) { tmp.setup_rotation(Vector3::unit_z, sprite.rot); mat_model *= tmp; } tmp.setup_scale(Vector3(sprite.scale * sprite.w, sprite.scale * sprite.h, 1.0f)); mat_model *= tmp; } void RenderLayer2::render_particles(Renderer2* renderer, const AABB2& camera_bb) { int particle_count = 0; for (auto it = particles.begin(); it != particles.end(); ) { Particle* p = (*it); // remove dead particles if (p->ttl <= 0) { it = particles.erase(it); continue; } // check if particle visible and store result in ->rendered if (p->rendered = camera_bb.contains(p->pos)) { particle_data[particle_count].x = p->pos.x; particle_data[particle_count].y = p->pos.y; particle_data[particle_count].size = p->size; particle_data[particle_count].r = p->color.r; particle_data[particle_count].g = p->color.g; particle_data[particle_count].b = p->color.b; particle_data[particle_count].a = p->color.a; perfc.inc(PerformanceCounter::PARTICLES); particle_count++; } ++it; } if (particle_count == 0) { return; // no particles left to render } renderer->switch_shader(particle_program); // Set parallax value for this layer glUniform1f(particle_program->attr("u_parallax"), parallax); #if OPENGL_VERSION >= 30 // bind particle vertex buffers glBindVertexArray(particle_buffer->vao); glBindBuffer(GL_ARRAY_BUFFER, particle_buffer->buffers[0]); // Orphan buffer to improve streaming performance glBufferData(GL_ARRAY_BUFFER, Renderer2::max_particles * sizeof(ParticleVertex2), nullptr, GL_STREAM_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, particle_count * sizeof(ParticleVertex2), particle_data); // bind vertex position auto pos_id = particle_program->attr(Renderer::at_pos); glEnableVertexAttribArray(pos_id); glVertexAttribPointer(pos_id, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, x))); // bind color position auto color_id = particle_program->attr(Renderer::at_color); glEnableVertexAttribArray(color_id); glVertexAttribPointer(color_id, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, r))); #else glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, particle_buffer->buffers[0]); // Orphan buffer to improve streaming performance glBufferData(GL_ARRAY_BUFFER, Renderer2::max_particles * sizeof(ParticleVertex2), NULL, GL_STREAM_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, particle_count * sizeof(ParticleVertex2), particle_data); // bind vertex position glVertexPointer(4, GL_FLOAT, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, x))); // bind color position glColorPointer(4, GL_FLOAT, sizeof(ParticleVertex2), reinterpret_cast<const GLvoid*>(offsetof(ParticleVertex2, r))); #endif glDrawArrays(GL_POINTS, 0, particle_count); #ifdef _DEBUG #if OPENGL_VERSION >= 30 glDisableVertexAttribArray(pos_id); glDisableVertexAttribArray(color_id); glBindVertexArray(0); #else glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); #endif glBindBuffer(GL_ARRAY_BUFFER, 0); #endif } void RenderLayer2::render_text(Renderer2* renderer, const AABB2& camera_bb) { // set up matrix once Matrix4 mat_identity; mat_identity.identity(); for (const auto& text : texts) { // TODO: perform boundary check text->render(renderer, mat_identity); } } void RenderLayer2::render_effects(Renderer2* renderer, const AABB2& camera_bb) { for (const auto& fx : effects) { fx->render(renderer, camera_bb); } } }<|endoftext|>
<commit_before>/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * 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 or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #include <stdlib.h> #include <time.h> #include <pthread.h> static void *pthreadEntryFunction(void* fthreadObj); #include "push/FThread.h" #include "base/globalsdef.h" USE_NAMESPACE FThread::FThread() :isRunning(false), terminate(false) { } FThread::~FThread() { } void FThread::start( FThread::Priority priority ) { isRunning = true; pthread_create( &pthread, NULL, pthreadEntryFunction, (void*)this); } void FThread::wait() { pthread_join( pthread, NULL); } bool FThread::wait(unsigned long timeout) { struct timespec t; time_t seconds = timeout / 1000; long nanoseconds = (timeout % 1000) * 1000; t.tv_sec = seconds; t.tv_nsec = nanoseconds; #if !defined(__APPLE__) && defined(__MACH__) if(pthread_timedjoin_np(pthread, NULL, &t) == ETIMEDOUT) { return true; } #endif return false; } bool FThread::finished() const { return !isRunning; } bool FThread::running() const { return isRunning; } void FThread::softTerminate() { // pthread allows a thread to be killed (pthread_cancel) // but this is somehow risky. What should we do? terminate = true; } void FThread::sleep(long msec) { struct timespec t, rt; int ret = 0; time_t seconds = msec / 1000; long nanoseconds = (msec % 1000) * 1000; t.tv_sec = seconds; t.tv_nsec = nanoseconds; do { ret = nanosleep(&t, &rt); t = rt; } while (ret != 0); } void FThread::setRunning(bool value) { isRunning = value; } static void *pthreadEntryFunction(void* fthreadObj) { FThread* threadObj = (FThread*)fthreadObj; threadObj->run(); threadObj->setRunning(false); pthread_exit(NULL); return NULL; } <commit_msg>change initialization order, in order to avoid warning<commit_after>/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * 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 or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #include <stdlib.h> #include <time.h> #include <pthread.h> static void *pthreadEntryFunction(void* fthreadObj); #include "push/FThread.h" #include "base/globalsdef.h" USE_NAMESPACE FThread::FThread() : terminate(false), isRunning(false) { } FThread::~FThread() { } void FThread::start( FThread::Priority priority ) { isRunning = true; pthread_create( &pthread, NULL, pthreadEntryFunction, (void*)this); } void FThread::wait() { pthread_join( pthread, NULL); } bool FThread::wait(unsigned long timeout) { struct timespec t; time_t seconds = timeout / 1000; long nanoseconds = (timeout % 1000) * 1000; t.tv_sec = seconds; t.tv_nsec = nanoseconds; #if !defined(__APPLE__) && defined(__MACH__) if(pthread_timedjoin_np(pthread, NULL, &t) == ETIMEDOUT) { return true; } #endif return false; } bool FThread::finished() const { return !isRunning; } bool FThread::running() const { return isRunning; } void FThread::softTerminate() { // pthread allows a thread to be killed (pthread_cancel) // but this is somehow risky. What should we do? terminate = true; } void FThread::sleep(long msec) { struct timespec t, rt; int ret = 0; time_t seconds = msec / 1000; long nanoseconds = (msec % 1000) * 1000; t.tv_sec = seconds; t.tv_nsec = nanoseconds; do { ret = nanosleep(&t, &rt); t = rt; } while (ret != 0); } void FThread::setRunning(bool value) { isRunning = value; } static void *pthreadEntryFunction(void* fthreadObj) { FThread* threadObj = (FThread*)fthreadObj; threadObj->run(); threadObj->setRunning(false); pthread_exit(NULL); return NULL; } <|endoftext|>
<commit_before>#include "SDL.h" #include <SDL_opengl.h> #include "core/crc32.h" #include "core/file_system.h" #include "core/json_serializer.h" #include "core/memory_stream.h" #include "editor/editor_client.h" #include "editor/editor_server.h" #include "editor/server_message_types.h" #include "editor_native/main_frame.h" #include "engine/engine.h" #include "engine/plugin_manager.h" #include "graphics/renderer.h" #include "gui/block.h" #include "gui/decorators/box_decorator.h" #include "gui/decorators/check_box_decorator.h" #include "gui/decorators/text_decorator.h" #include "gui/gui.h" #include "gui/opengl_renderer.h" #include "platform/socket.h" SDL_Renderer* displayRenderer; SDL_Window* displayWindow; MainFrame g_main_frame; void Display_InitGL() { glShadeModel( GL_SMOOTH ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClearDepth( 1.0f ); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); } int Display_SetViewport( int width, int height ) { GLfloat ratio; if ( height == 0 ) { height = 1; } ratio = ( GLfloat )width / ( GLfloat )height; glViewport( 0, 0, ( GLsizei )width, ( GLsizei )height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); return 1; } void initGui(Lux::EditorClient& client, Lux::EditorServer& server) { Lux::UI::OpenGLRenderer* renderer = new Lux::UI::OpenGLRenderer(); renderer->create(); renderer->loadFont("gui/font.tga"); renderer->setWindowHeight(600); Lux::UI::CheckBoxDecorator* check_box_decorator = new Lux::UI::CheckBoxDecorator("_check_box"); Lux::UI::TextDecorator* text_decorator = new Lux::UI::TextDecorator("_text"); Lux::UI::TextDecorator* text_centered_decorator = new Lux::UI::TextDecorator("_text_centered"); text_centered_decorator->setTextCentered(true); Lux::UI::BoxDecorator* box_decorator = new Lux::UI::BoxDecorator("_box"); server.getEngine().loadPlugin("gui.dll"); Lux::UI::Gui* gui = (Lux::UI::Gui*)server.getEngine().getPluginManager().getPlugin("gui"); gui->addDecorator(*text_decorator); gui->addDecorator(*text_centered_decorator); gui->addDecorator(*box_decorator); gui->addDecorator(*check_box_decorator); gui->setRenderer(*renderer); check_box_decorator->create(*gui, "gui/skin.atl"); box_decorator->create(*gui, "gui/skin.atl"); g_main_frame.create(client, *gui, 800, 600); } int main(int argc, char* argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_RendererInfo displayRendererInfo; SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_OPENGL, &displayWindow, &displayRenderer); SDL_GetRendererInfo(displayRenderer, &displayRendererInfo); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); if ((displayRendererInfo.flags & SDL_RENDERER_ACCELERATED) == 0 || (displayRendererInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) { return -1; } SDL_GL_MakeCurrent(displayWindow, context); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 2 ); // Display_InitGL(); Display_SetViewport(800, 600); char path[MAX_PATH]; GetCurrentDirectoryA(MAX_PATH, path); GLenum glerr = glGetError(); const GLubyte* glstr = glGetString(GL_VENDOR); Lux::EditorServer server; server.create(NULL, NULL, path); server.onResize(800, 600); Lux::EditorClient client; client.create(); initGui(client, server); Lux::UI::Gui* gui = (Lux::UI::Gui*)server.getEngine().getPluginManager().getPlugin("gui"); SDL_Event evt; bool finished = false; while(!finished) { while(SDL_PollEvent(&evt)) { switch(evt.type) { case SDL_TEXTEDITING: evt.text.text; finished = false; break; case SDL_KEYDOWN: gui->keyDown(evt.key.keysym.sym); if(evt.key.keysym.sym == SDLK_ESCAPE) finished = true; break; case SDL_KEYUP: break; case SDL_MOUSEBUTTONDOWN: if(!gui->click(evt.button.x, evt.button.y)) { client.mouseDown(evt.button.x, evt.button.y, evt.button.button == SDL_BUTTON_LEFT ? 0 : 2); } break; case SDL_MOUSEBUTTONUP: client.mouseUp(evt.button.x, evt.button.y, evt.button.button == SDL_BUTTON_LEFT ? 0 : 2); break; case SDL_MOUSEMOTION: client.mouseMove(evt.motion.x, evt.motion.y, evt.motion.xrel, evt.motion.yrel); break; case SDL_QUIT: finished = true; break; } } const Uint8* keys = SDL_GetKeyboardState(NULL); if(gui->getFocusedBlock() == NULL) { bool forward = keys[SDL_SCANCODE_W] != 0; bool backward = keys[SDL_SCANCODE_S] != 0; bool left = keys[SDL_SCANCODE_A] != 0; bool right = keys[SDL_SCANCODE_D] != 0; bool shift = keys[SDL_SCANCODE_LSHIFT] != 0; if (forward || backward || left || right) { float camera_speed = 1.0f; client.navigate(forward ? camera_speed : (backward ? -camera_speed : 0.0f) , right ? camera_speed : (left ? -camera_speed : 0.0f) , shift ? 1 : 0); } } server.tick(NULL, NULL); gui->render(); SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }<commit_msg>release build fix<commit_after>#include "SDL.h" #include <SDL_opengl.h> #include "core/blob.h" #include "core/crc32.h" #include "core/file_system.h" #include "core/json_serializer.h" #include "editor/editor_client.h" #include "editor/editor_server.h" #include "editor/server_message_types.h" #include "editor_native/main_frame.h" #include "engine/engine.h" #include "engine/plugin_manager.h" #include "graphics/renderer.h" #include "gui/block.h" #include "gui/decorators/box_decorator.h" #include "gui/decorators/check_box_decorator.h" #include "gui/decorators/text_decorator.h" #include "gui/gui.h" #include "gui/opengl_renderer.h" #include "platform/socket.h" SDL_Renderer* displayRenderer; SDL_Window* displayWindow; MainFrame g_main_frame; void Display_InitGL() { glShadeModel( GL_SMOOTH ); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); glClearDepth( 1.0f ); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); } int Display_SetViewport( int width, int height ) { GLfloat ratio; if ( height == 0 ) { height = 1; } ratio = ( GLfloat )width / ( GLfloat )height; glViewport( 0, 0, ( GLsizei )width, ( GLsizei )height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); return 1; } void initGui(Lux::EditorClient& client, Lux::EditorServer& server) { Lux::UI::OpenGLRenderer* renderer = new Lux::UI::OpenGLRenderer(); renderer->create(); renderer->loadFont("gui/font.tga"); renderer->setWindowHeight(600); Lux::UI::CheckBoxDecorator* check_box_decorator = new Lux::UI::CheckBoxDecorator("_check_box"); Lux::UI::TextDecorator* text_decorator = new Lux::UI::TextDecorator("_text"); Lux::UI::TextDecorator* text_centered_decorator = new Lux::UI::TextDecorator("_text_centered"); text_centered_decorator->setTextCentered(true); Lux::UI::BoxDecorator* box_decorator = new Lux::UI::BoxDecorator("_box"); server.getEngine().loadPlugin("gui.dll"); Lux::UI::Gui* gui = (Lux::UI::Gui*)server.getEngine().getPluginManager().getPlugin("gui"); gui->addDecorator(*text_decorator); gui->addDecorator(*text_centered_decorator); gui->addDecorator(*box_decorator); gui->addDecorator(*check_box_decorator); gui->setRenderer(*renderer); check_box_decorator->create(*gui, "gui/skin.atl"); box_decorator->create(*gui, "gui/skin.atl"); g_main_frame.create(client, *gui, 800, 600); } int main(int argc, char* argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_RendererInfo displayRendererInfo; SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_OPENGL, &displayWindow, &displayRenderer); SDL_GetRendererInfo(displayRenderer, &displayRendererInfo); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); if ((displayRendererInfo.flags & SDL_RENDERER_ACCELERATED) == 0 || (displayRendererInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) { return -1; } SDL_GL_MakeCurrent(displayWindow, context); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 2 ); // Display_InitGL(); Display_SetViewport(800, 600); char path[MAX_PATH]; GetCurrentDirectoryA(MAX_PATH, path); GLenum glerr = glGetError(); const GLubyte* glstr = glGetString(GL_VENDOR); Lux::EditorServer server; server.create(NULL, NULL, path); server.onResize(800, 600); Lux::EditorClient client; client.create(); initGui(client, server); Lux::UI::Gui* gui = (Lux::UI::Gui*)server.getEngine().getPluginManager().getPlugin("gui"); SDL_Event evt; bool finished = false; while(!finished) { while(SDL_PollEvent(&evt)) { switch(evt.type) { case SDL_TEXTEDITING: evt.text.text; finished = false; break; case SDL_KEYDOWN: gui->keyDown(evt.key.keysym.sym); if(evt.key.keysym.sym == SDLK_ESCAPE) finished = true; break; case SDL_KEYUP: break; case SDL_MOUSEBUTTONDOWN: if(!gui->click(evt.button.x, evt.button.y)) { client.mouseDown(evt.button.x, evt.button.y, evt.button.button == SDL_BUTTON_LEFT ? 0 : 2); } break; case SDL_MOUSEBUTTONUP: client.mouseUp(evt.button.x, evt.button.y, evt.button.button == SDL_BUTTON_LEFT ? 0 : 2); break; case SDL_MOUSEMOTION: client.mouseMove(evt.motion.x, evt.motion.y, evt.motion.xrel, evt.motion.yrel); break; case SDL_QUIT: finished = true; break; } } const Uint8* keys = SDL_GetKeyboardState(NULL); if(gui->getFocusedBlock() == NULL) { bool forward = keys[SDL_SCANCODE_W] != 0; bool backward = keys[SDL_SCANCODE_S] != 0; bool left = keys[SDL_SCANCODE_A] != 0; bool right = keys[SDL_SCANCODE_D] != 0; bool shift = keys[SDL_SCANCODE_LSHIFT] != 0; if (forward || backward || left || right) { float camera_speed = 1.0f; client.navigate(forward ? camera_speed : (backward ? -camera_speed : 0.0f) , right ? camera_speed : (left ? -camera_speed : 0.0f) , shift ? 1 : 0); } } server.tick(NULL, NULL); gui->render(); SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }<|endoftext|>
<commit_before>/* eXokernel Development Kit (XDK) Based on code by Samsung Research America Copyright (C) 2013 The GNU C 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. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. As a special exception, if you link the code in this file with files compiled with a GNU compiler to produce an executable, that does not cause the resulting executable to be covered by the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. This exception applies to code released by its copyright holders in files containing the exception. */ /* Authors: Copyright (C) 2014, Daniel G. Waddington <[email protected]> */ #include <iostream> #include "exo/pagemap.h" #include "exo/memory.h" /** * Read in the current memory regions from /proc/self/maps. * * @param range_list [out] vector of range_t elements */ void Exokernel::Pagemap::read_regions(std::vector<range_t> &range_list) { std::ifstream ifs; ifs.open("/proc/self/maps"); for (std::string line; std::getline(ifs, line); ) { std::stringstream istr(line); addr_t from, to; char dummy; istr >> std::hex >> from; istr >> dummy; istr >> std::hex >> to; range_list.push_back(range_t(from,to)); } ifs.close(); } void Exokernel::Pagemap::dump_self_region_info() { std::ifstream ifs; ifs.open("/proc/self/maps"); std::cout << std::endl; for (std::string line; std::getline(ifs, line); ) { std::cout << line << std::endl; } ifs.close(); } /** * Look up the physical Page Frame Number from the virtual address * * @param vaddr Virtual address * * @return Page Frame Number if present */ uint64_t Exokernel::Pagemap::__get_page_frame_number(void * vaddr) { using namespace std; size_t pages_in_range; /* check vaddr exists */ vector<range_t> range_list; read_regions(range_list); for (unsigned i=0;i<range_list.size();i++) { pages_in_range = (range_list[i].end - range_list[i].start) / _page_size; /* check if this is our range */ if ((((addr_t)vaddr) >= range_list[i].start) && (((addr_t)vaddr) < range_list[i].end)) { PLOG("found %lx in range %lx-%lx",vaddr,range_list[i].start,range_list[i].end); goto found; } } PERR("virt_to_phys: invalid virtual address."); return 0; found: /* now open up the pagemap entry */ off_t offset = 0; uint64_t entry = 0; /* each entry is a page; an entry is 64 bits. */ offset = ((addr_t)vaddr >> PAGE_SHIFT) * sizeof(uint64_t); off64_t o = lseek64(_fd_pagemap, offset, SEEK_SET); while(pages_in_range > 0) { read(_fd_pagemap,&entry,sizeof(addr_t)); pages_in_range--; PLOG("entry=%016llX", entry); // & 0x7fffffffffffffULL); } // int rc = pread(_fd_pagemap,(void*)&entry,8,offset); // assert(rc == 8); if(entry & (1UL << 55)) { PLOG("page soft-dirty"); } if(entry & (1UL << 61)) { PLOG("page is shared-anon or file-page"); } if(entry & (1UL << 62)) { PLOG("page is swapped"); } if(entry & (1UL << 63)) { PLOG("page is present"); } /* Page Frame Number is bit 0-54 */ return (entry & 0x7fffffffffffffULL); } <commit_msg>bug fix in pagemap.cc<commit_after>/* eXokernel Development Kit (XDK) Based on code by Samsung Research America Copyright (C) 2013 The GNU C 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. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. As a special exception, if you link the code in this file with files compiled with a GNU compiler to produce an executable, that does not cause the resulting executable to be covered by the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. This exception applies to code released by its copyright holders in files containing the exception. */ /* Authors: Copyright (C) 2014, Daniel G. Waddington <[email protected]> */ #include <iostream> #include "exo/pagemap.h" #include "exo/memory.h" /** * Read in the current memory regions from /proc/self/maps. * * @param range_list [out] vector of range_t elements */ void Exokernel::Pagemap::read_regions(std::vector<range_t> &range_list) { std::ifstream ifs; ifs.open("/proc/self/maps"); for (std::string line; std::getline(ifs, line); ) { std::stringstream istr(line); addr_t from, to; char dummy; istr >> std::hex >> from; istr >> dummy; istr >> std::hex >> to; range_list.push_back(range_t(from,to)); } ifs.close(); } void Exokernel::Pagemap::dump_self_region_info() { std::ifstream ifs; ifs.open("/proc/self/maps"); std::cout << std::endl; for (std::string line; std::getline(ifs, line); ) { std::cout << line << std::endl; } ifs.close(); } /** * Look up the physical Page Frame Number from the virtual address * * @param vaddr Virtual address * * @return Page Frame Number if present */ uint64_t Exokernel::Pagemap::__get_page_frame_number(void * vaddr) { using namespace std; size_t pages_in_range; /* check vaddr exists */ vector<range_t> range_list; read_regions(range_list); for (unsigned i=0;i<range_list.size();i++) { pages_in_range = (range_list[i].end - range_list[i].start) / _page_size; /* check if this is our range */ if ((((addr_t)vaddr) >= range_list[i].start) && (((addr_t)vaddr) < range_list[i].end)) { PLOG("found %lx in range %lx-%lx",vaddr,range_list[i].start,range_list[i].end); goto found; } } PERR("virt_to_phys: invalid virtual address."); return 0; found: /* now open up the pagemap entry */ off_t offset = 0; uint64_t entry = 0; /* each entry is a page; an entry is 64 bits. */ offset = ((addr_t)vaddr >> PAGE_SHIFT) * sizeof(uint64_t); int rc = pread(_fd_pagemap,(void*)&entry,8,offset); assert(rc == 8); if(entry & (1UL << 55)) { PLOG("page soft-dirty"); } if(entry & (1UL << 61)) { PLOG("page is shared-anon or file-page"); } if(entry & (1UL << 62)) { PLOG("page is swapped"); } if(entry & (1UL << 63)) { PLOG("page is present"); } /* Page Frame Number is bit 0-54 */ return (entry & 0x7fffffffffffffULL); } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <boost/mpl/integral_c.hpp> #include <boost/numeric/conversion/converter.hpp> #include "libport/ufloat.hh" #ifdef LIBPORT_URBI_UFLOAT_LONG_LONG # include "libport/ull-fixed-point.cc" #endif #ifdef LIBPORT_URBI_UFLOAT_FLOATING # include "libport/uffloat.cc" #endif namespace libport { #ifdef LIBPORT_URBI_UFLOAT_TABULATED # ifndef SINTABLE_POWER # define SINTABLE_POWER 10 //the tables will containe 2^sintable_power elements # endif void buildSinusTable(int powersize); class DummyInit { public: DummyInit() { buildSinusTable(SINTABLE_POWER); } }; DummyInit _dummyInit__; static ufloat* sinTable=0; //we store [O, PI/2[ static ufloat* asinTable=0; //we store [O, 1[ static unsigned long tableSize; //must be a power of two static int tableShift; void buildSinusTable(int powersize) { int size = 1<<powersize; tableShift = powersize; //don't use a step-based generation or errors will accumulate delete [] sinTable; delete [] asinTable; sinTable = new ufloat[size]; asinTable = new ufloat[size]; tableSize = size; for (int i=0;i<size;i++) { double idx = (double)i*(M_PI/2.0)/(double)size; float val = ::sin(idx); sinTable[i]=val; double idx2 = (double)i/(double)size; asinTable[i] = ::asin(idx2); } } #endif #if defined LIBPORT_URBI_UFLOAT_TABULATED \ && !defined LIBPORT_URBI_UFLOAT_FLOATING ufloat tabulatedSin(ufloat val) { ufloat fidx = (val*(ufloat)tableSize / (M_PI/2.0)); int idx = (int) fidx; ufloat rem = fidx -(ufloat)idx; idx = idx & (tableSize-1); if (fmod(val, M_PI) >= M_PI/2) idx = (tableSize-idx-1); //sin(pi/2+x) = sin(pi/2-x) ufloat interp = sinTable(idx)*(1.0-rem)+sinTable[(idx+1)%tableSize]*rem; if (fmod(val, M_PI*2) > M_PI) return -interp; else return interp; }; ufloat tabulatedCos(ufloat val) { ufloat fidx = (val*(ufloat)tableSize / (M_PI/2.0)); int idx = (int) fidx; ufloat rem = fidx -(ufloat)idx; idx = idx & (tableSize-1); if (fmod(val, M_PI) < M_PI/2) idx = (tableSize-idx-1); //sin(pi/2+x) = sin(pi/2-x) ufloat interp = sinTable(idx)*(1.0-rem)+sinTable[(idx+1)%tableSize]*rem; if (fmod(val, M_PI*2) > M_PI) return -interp; else return interp; }; ufloat tabulatedASin(ufloat val) { ufloat fidx = val *(ufloat)tableSize; int idx =(int) fidx; ufloat rem = fidx -(ufloat)idx; idx = idx & (tableSize-1); ufloat interp = asinTable(idx)*(1.0-rem)+asinTable[(idx+1)%tableSize]*rem; if (val < 0.0) return -interp; else return interp; } #endif template<typename S> struct ExactFloat2IntRounderPolicy { typedef S source_type ; typedef S argument_type ; static source_type nearbyint (argument_type s) { if (s != ceil (s)) throw boost::numeric::bad_numeric_cast (); return s; } typedef boost::mpl::integral_c<std::float_round_style,std::round_to_nearest> round_style ; }; // Convert a libport::ufloat to a int. This function will raise // boost::numeric::bad_numeric_cast if the provided argument is directly // convertible to an integer. static boost::numeric::converter <int, ufloat, boost::numeric::conversion_traits<int, ufloat>, boost::numeric::def_overflow_handler, ExactFloat2IntRounderPolicy<ufloat> > ufloat_to_int_converter; int ufloat_to_int (ufloat val) { try { return ufloat_to_int_converter (val); } catch (boost::numeric::bad_numeric_cast&) { throw bad_numeric_cast(); } } bool ufloat_to_boolean (ufloat val) { int res = ufloat_to_int_converter (val); if (res != 0 && res != 1) throw new bad_numeric_cast; return static_cast<bool> (res); } } <commit_msg>Remove bogus new when throwing exception<commit_after>#include <iostream> #include <cmath> #include <boost/mpl/integral_c.hpp> #include <boost/numeric/conversion/converter.hpp> #include "libport/ufloat.hh" #ifdef LIBPORT_URBI_UFLOAT_LONG_LONG # include "libport/ull-fixed-point.cc" #endif #ifdef LIBPORT_URBI_UFLOAT_FLOATING # include "libport/uffloat.cc" #endif namespace libport { #ifdef LIBPORT_URBI_UFLOAT_TABULATED # ifndef SINTABLE_POWER # define SINTABLE_POWER 10 //the tables will containe 2^sintable_power elements # endif void buildSinusTable(int powersize); class DummyInit { public: DummyInit() { buildSinusTable(SINTABLE_POWER); } }; DummyInit _dummyInit__; static ufloat* sinTable=0; //we store [O, PI/2[ static ufloat* asinTable=0; //we store [O, 1[ static unsigned long tableSize; //must be a power of two static int tableShift; void buildSinusTable(int powersize) { int size = 1<<powersize; tableShift = powersize; //don't use a step-based generation or errors will accumulate delete [] sinTable; delete [] asinTable; sinTable = new ufloat[size]; asinTable = new ufloat[size]; tableSize = size; for (int i=0;i<size;i++) { double idx = (double)i*(M_PI/2.0)/(double)size; float val = ::sin(idx); sinTable[i]=val; double idx2 = (double)i/(double)size; asinTable[i] = ::asin(idx2); } } #endif #if defined LIBPORT_URBI_UFLOAT_TABULATED \ && !defined LIBPORT_URBI_UFLOAT_FLOATING ufloat tabulatedSin(ufloat val) { ufloat fidx = (val*(ufloat)tableSize / (M_PI/2.0)); int idx = (int) fidx; ufloat rem = fidx -(ufloat)idx; idx = idx & (tableSize-1); if (fmod(val, M_PI) >= M_PI/2) idx = (tableSize-idx-1); //sin(pi/2+x) = sin(pi/2-x) ufloat interp = sinTable(idx)*(1.0-rem)+sinTable[(idx+1)%tableSize]*rem; if (fmod(val, M_PI*2) > M_PI) return -interp; else return interp; }; ufloat tabulatedCos(ufloat val) { ufloat fidx = (val*(ufloat)tableSize / (M_PI/2.0)); int idx = (int) fidx; ufloat rem = fidx -(ufloat)idx; idx = idx & (tableSize-1); if (fmod(val, M_PI) < M_PI/2) idx = (tableSize-idx-1); //sin(pi/2+x) = sin(pi/2-x) ufloat interp = sinTable(idx)*(1.0-rem)+sinTable[(idx+1)%tableSize]*rem; if (fmod(val, M_PI*2) > M_PI) return -interp; else return interp; }; ufloat tabulatedASin(ufloat val) { ufloat fidx = val *(ufloat)tableSize; int idx =(int) fidx; ufloat rem = fidx -(ufloat)idx; idx = idx & (tableSize-1); ufloat interp = asinTable(idx)*(1.0-rem)+asinTable[(idx+1)%tableSize]*rem; if (val < 0.0) return -interp; else return interp; } #endif template<typename S> struct ExactFloat2IntRounderPolicy { typedef S source_type ; typedef S argument_type ; static source_type nearbyint (argument_type s) { if (s != ceil (s)) throw boost::numeric::bad_numeric_cast (); return s; } typedef boost::mpl::integral_c<std::float_round_style,std::round_to_nearest> round_style ; }; // Convert a libport::ufloat to a int. This function will raise // boost::numeric::bad_numeric_cast if the provided argument is directly // convertible to an integer. static boost::numeric::converter <int, ufloat, boost::numeric::conversion_traits<int, ufloat>, boost::numeric::def_overflow_handler, ExactFloat2IntRounderPolicy<ufloat> > ufloat_to_int_converter; int ufloat_to_int (ufloat val) { try { return ufloat_to_int_converter (val); } catch (boost::numeric::bad_numeric_cast&) { throw bad_numeric_cast (); } } bool ufloat_to_boolean (ufloat val) { int res = ufloat_to_int_converter (val); if (res != 0 && res != 1) throw bad_numeric_cast (); return static_cast<bool> (res); } } <|endoftext|>
<commit_before>#ifndef ENTT_ENTITY_ENTITY_HPP #define ENTT_ENTITY_ENTITY_HPP #include <cstddef> #include <cstdint> #include <type_traits> #include "../config/config.h" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename = void> struct entt_traits; template<typename Type> struct entt_traits<Type, std::enable_if_t<std::is_enum_v<Type>>> : entt_traits<std::underlying_type_t<Type>> {}; template<typename Type> struct entt_traits<Type, std::enable_if_t<std::is_class_v<Type>>> : entt_traits<typename Type::entity_type> {}; template<> struct entt_traits<std::uint32_t> { using entity_type = std::uint32_t; using version_type = std::uint16_t; using difference_type = std::int64_t; static constexpr entity_type entity_mask = 0xFFFFF; static constexpr entity_type version_mask = 0xFFF; static constexpr std::size_t entity_shift = 20u; }; template<> struct entt_traits<std::uint64_t> { using entity_type = std::uint64_t; using version_type = std::uint32_t; using difference_type = std::int64_t; static constexpr entity_type entity_mask = 0xFFFFFFFF; static constexpr entity_type version_mask = 0xFFFFFFFF; static constexpr std::size_t entity_shift = 32u; }; } /** * Internal details not to be documented. * @endcond */ /** * @brief Entity traits. * @tparam Type Type of identifier. */ template<typename Type> class entt_traits: private internal::entt_traits<Type> { using traits_type = internal::entt_traits<Type>; public: /*! @brief Underlying entity type. */ using entity_type = typename traits_type::entity_type; /*! @brief Underlying version type. */ using version_type = typename traits_type::version_type; /*! @brief Difference type. */ using difference_type = typename traits_type::difference_type; /** * @brief Converts an entity to its underlying type. * @param value The value to convert. * @return The integral representation of the given value. */ [[nodiscard]] static constexpr auto to_integral(const Type value) ENTT_NOEXCEPT { return static_cast<entity_type>(value); } /** * @brief Returns the entity part once converted to the underlying type. * @param value The value to convert. * @return The integral representation of the entity part. */ [[nodiscard]] static constexpr auto to_entity(const Type value) ENTT_NOEXCEPT { return (to_integral(value) & traits_type::entity_mask); } /** * @brief Returns the version part once converted to the underlying type. * @param value The value to convert. * @return The integral representation of the version part. */ [[nodiscard]] static constexpr auto to_version(const Type value) ENTT_NOEXCEPT { constexpr auto mask = (traits_type::version_mask << traits_type::entity_shift); return ((to_integral(value) & mask) >> traits_type::entity_shift); } /** * @brief Constructs an identifier from its parts. * @param entity The entity part of the identifier. * @param version The version part of the identifier. * @return A properly constructed identifier. */ [[nodiscard]] static constexpr auto to_type(const entity_type entity, const version_type version) ENTT_NOEXCEPT { return Type{(entity & traits_type::entity_mask) | (version << traits_type::entity_shift)}; } /** * @brief Constructs an identifier from its parts. * @param entity The entity part of the identifier. * @param version The version part of the identifier. * @return A properly constructed identifier. */ [[nodiscard]] static constexpr auto to_type(const Type entity, const Type version) ENTT_NOEXCEPT { constexpr auto mask = (traits_type::version_mask << traits_type::entity_shift); return Type{(to_integral(entity) & traits_type::entity_mask) | (to_integral(version) & mask)}; } /** * @brief Returns the reserved identifer. * @return The reserved identifier. */ [[nodiscard]] static constexpr auto reserved() ENTT_NOEXCEPT { return to_type(traits_type::entity_mask, traits_type::version_mask); } }; /** * @brief Converts an entity to its underlying type. * @tparam Entity The value type. * @param entity The value to convert. * @return The integral representation of the given value. */ template<typename Entity> [[nodiscard]] constexpr auto to_integral(const Entity entity) ENTT_NOEXCEPT { return entt_traits<Entity>::to_integral(entity); } /*! @brief Null object for all entity identifiers. */ struct null_t { /** * @brief Converts the null object to identifiers of any type. * @tparam Entity Type of entity identifier. * @return The null representation for the given type. */ template<typename Entity> [[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT { return entt_traits<Entity>::reserved(); } /** * @brief Compares two null objects. * @return True in all cases. */ [[nodiscard]] constexpr bool operator==(const null_t &) const ENTT_NOEXCEPT { return true; } /** * @brief Compares two null objects. * @return False in all cases. */ [[nodiscard]] constexpr bool operator!=(const null_t &) const ENTT_NOEXCEPT { return false; } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity &entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_entity(entity) == entt_traits<Entity>::to_entity(*this); } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity &entity) const ENTT_NOEXCEPT { return !(entity == *this); } /** * @brief Creates a null object from an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier to turn into a null object. * @return The null representation for the given identifier. */ template<typename Entity> [[nodiscard]] constexpr Entity operator|(const Entity &entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_type(*this, entity); } }; /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A null object yet to be converted. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity &entity, const null_t &other) ENTT_NOEXCEPT { return other.operator==(entity); } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A null object yet to be converted. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity &entity, const null_t &other) ENTT_NOEXCEPT { return !(other == entity); } /*! @brief Tombstone object for all entity identifiers. */ struct tombstone_t { /** * @brief Converts the tombstone object to identifiers of any type. * @tparam Entity Type of entity identifier. * @return The tombstone representation for the given type. */ template<typename Entity> [[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT { return entt_traits<Entity>::reserved(); } /** * @brief Compares two tombstone objects. * @return True in all cases. */ [[nodiscard]] constexpr bool operator==(const tombstone_t &) const ENTT_NOEXCEPT { return true; } /** * @brief Compares two tombstone objects. * @return False in all cases. */ [[nodiscard]] constexpr bool operator!=(const tombstone_t &) const ENTT_NOEXCEPT { return false; } /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity &entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_version(entity) == entt_traits<Entity>::to_version(*this); } /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity &entity) const ENTT_NOEXCEPT { return !(entity == *this); } /** * @brief Creates a tombstone object from an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier to turn into a tombstone object. * @return The tombstone representation for the given identifier. */ template<typename Entity> [[nodiscard]] constexpr Entity operator|(const Entity &entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_type(entity, *this); } }; /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A tombstone object yet to be converted. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity &entity, const tombstone_t &other) ENTT_NOEXCEPT { return other.operator==(entity); } /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A tombstone object yet to be converted. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity &entity, const tombstone_t &other) ENTT_NOEXCEPT { return !(other == entity); } /** * @brief Compile-time constant for null entities. * * There exist implicit conversions from this variable to entity identifiers of * any allowed type. Similarly, there exist comparision operators between the * null entity and any other entity identifier. */ inline constexpr null_t null{}; /** * @brief Compile-time constant for tombstone entities. * * There exist implicit conversions from this variable to entity identifiers of * any allowed type. Similarly, there exist comparision operators between the * tombstone entity and any other entity identifier. */ inline constexpr tombstone_t tombstone{}; } #endif <commit_msg>entity: * Updated doc * No const-ref for basic types<commit_after>#ifndef ENTT_ENTITY_ENTITY_HPP #define ENTT_ENTITY_ENTITY_HPP #include <cstddef> #include <cstdint> #include <type_traits> #include "../config/config.h" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename = void> struct entt_traits; template<typename Type> struct entt_traits<Type, std::enable_if_t<std::is_enum_v<Type>>> : entt_traits<std::underlying_type_t<Type>> {}; template<typename Type> struct entt_traits<Type, std::enable_if_t<std::is_class_v<Type>>> : entt_traits<typename Type::entity_type> {}; template<> struct entt_traits<std::uint32_t> { using entity_type = std::uint32_t; using version_type = std::uint16_t; using difference_type = std::int64_t; static constexpr entity_type entity_mask = 0xFFFFF; static constexpr entity_type version_mask = 0xFFF; static constexpr std::size_t entity_shift = 20u; }; template<> struct entt_traits<std::uint64_t> { using entity_type = std::uint64_t; using version_type = std::uint32_t; using difference_type = std::int64_t; static constexpr entity_type entity_mask = 0xFFFFFFFF; static constexpr entity_type version_mask = 0xFFFFFFFF; static constexpr std::size_t entity_shift = 32u; }; } /** * Internal details not to be documented. * @endcond */ /** * @brief Entity traits. * @tparam Type Type of identifier. */ template<typename Type> class entt_traits: private internal::entt_traits<Type> { using traits_type = internal::entt_traits<Type>; public: /*! @brief Underlying entity type. */ using entity_type = typename traits_type::entity_type; /*! @brief Underlying version type. */ using version_type = typename traits_type::version_type; /*! @brief Difference type. */ using difference_type = typename traits_type::difference_type; /** * @brief Converts an entity to its underlying type. * @param value The value to convert. * @return The integral representation of the given value. */ [[nodiscard]] static constexpr auto to_integral(const Type value) ENTT_NOEXCEPT { return static_cast<entity_type>(value); } /** * @brief Returns the entity part once converted to the underlying type. * @param value The value to convert. * @return The integral representation of the entity part. */ [[nodiscard]] static constexpr auto to_entity(const Type value) ENTT_NOEXCEPT { return (to_integral(value) & traits_type::entity_mask); } /** * @brief Returns the version part once converted to the underlying type. * @param value The value to convert. * @return The integral representation of the version part. */ [[nodiscard]] static constexpr auto to_version(const Type value) ENTT_NOEXCEPT { constexpr auto mask = (traits_type::version_mask << traits_type::entity_shift); return ((to_integral(value) & mask) >> traits_type::entity_shift); } /** * @brief Constructs an identifier from its parts. * @param entity The entity part of the identifier. * @param version The version part of the identifier. * @return A properly constructed identifier. */ [[nodiscard]] static constexpr auto to_type(const entity_type entity, const version_type version) ENTT_NOEXCEPT { return Type{(entity & traits_type::entity_mask) | (version << traits_type::entity_shift)}; } /** * @brief Constructs an identifier from its parts. * @param entity The entity part of the identifier. * @param version The version part of the identifier. * @return A properly constructed identifier. */ [[nodiscard]] static constexpr auto to_type(const Type entity, const Type version) ENTT_NOEXCEPT { constexpr auto mask = (traits_type::version_mask << traits_type::entity_shift); return Type{(to_integral(entity) & traits_type::entity_mask) | (to_integral(version) & mask)}; } /** * @brief Returns the reserved identifer. * @return The reserved identifier. */ [[nodiscard]] static constexpr auto reserved() ENTT_NOEXCEPT { return to_type(traits_type::entity_mask, traits_type::version_mask); } }; /** * @brief Converts an entity to its underlying type. * @tparam Entity The value type. * @param entity The value to convert. * @return The integral representation of the given value. */ template<typename Entity> [[nodiscard]] constexpr auto to_integral(const Entity entity) ENTT_NOEXCEPT { return entt_traits<Entity>::to_integral(entity); } /*! @brief Null object for all entity identifiers. */ struct null_t { /** * @brief Converts the null object to identifiers of any type. * @tparam Entity Type of entity identifier. * @return The null representation for the given type. */ template<typename Entity> [[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT { return entt_traits<Entity>::reserved(); } /** * @brief Compares two null objects. * @param other A null object. * @return True in all cases. */ [[nodiscard]] constexpr bool operator==([[maybe_unused]] const null_t other) const ENTT_NOEXCEPT { return true; } /** * @brief Compares two null objects. * @param other A null object. * @return False in all cases. */ [[nodiscard]] constexpr bool operator!=([[maybe_unused]] const null_t other) const ENTT_NOEXCEPT { return false; } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_entity(entity) == entt_traits<Entity>::to_entity(*this); } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT { return !(entity == *this); } /** * @brief Creates a null object from an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier to turn into a null object. * @return The null representation for the given identifier. */ template<typename Entity> [[nodiscard]] constexpr Entity operator|(const Entity entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_type(*this, entity); } }; /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A null object yet to be converted. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity, const null_t other) ENTT_NOEXCEPT { return other.operator==(entity); } /** * @brief Compares a null object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A null object yet to be converted. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity, const null_t other) ENTT_NOEXCEPT { return !(other == entity); } /*! @brief Tombstone object for all entity identifiers. */ struct tombstone_t { /** * @brief Converts the tombstone object to identifiers of any type. * @tparam Entity Type of entity identifier. * @return The tombstone representation for the given type. */ template<typename Entity> [[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT { return entt_traits<Entity>::reserved(); } /** * @brief Compares two tombstone objects. * @param other A tombstone object. * @return True in all cases. */ [[nodiscard]] constexpr bool operator==([[maybe_unused]] const tombstone_t other) const ENTT_NOEXCEPT { return true; } /** * @brief Compares two tombstone objects. * @param other A tombstone object. * @return False in all cases. */ [[nodiscard]] constexpr bool operator!=([[maybe_unused]] const tombstone_t other) const ENTT_NOEXCEPT { return false; } /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_version(entity) == entt_traits<Entity>::to_version(*this); } /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT { return !(entity == *this); } /** * @brief Creates a tombstone object from an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier to turn into a tombstone object. * @return The tombstone representation for the given identifier. */ template<typename Entity> [[nodiscard]] constexpr Entity operator|(const Entity entity) const ENTT_NOEXCEPT { return entt_traits<Entity>::to_type(entity, *this); } }; /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A tombstone object yet to be converted. * @return False if the two elements differ, true otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator==(const Entity entity, const tombstone_t other) ENTT_NOEXCEPT { return other.operator==(entity); } /** * @brief Compares a tombstone object and an entity identifier of any type. * @tparam Entity Type of entity identifier. * @param entity Entity identifier with which to compare. * @param other A tombstone object yet to be converted. * @return True if the two elements differ, false otherwise. */ template<typename Entity> [[nodiscard]] constexpr bool operator!=(const Entity entity, const tombstone_t other) ENTT_NOEXCEPT { return !(other == entity); } /** * @brief Compile-time constant for null entities. * * There exist implicit conversions from this variable to entity identifiers of * any allowed type. Similarly, there exist comparision operators between the * null entity and any other entity identifier. */ inline constexpr null_t null{}; /** * @brief Compile-time constant for tombstone entities. * * There exist implicit conversions from this variable to entity identifiers of * any allowed type. Similarly, there exist comparision operators between the * tombstone entity and any other entity identifier. */ inline constexpr tombstone_t tombstone{}; } #endif <|endoftext|>
<commit_before>/// Generic interface from reading from ostream userdata. // @module ostream #include "OStream.h" #include "Poco/Exception.h" #include <cstring> namespace LuaPoco { const char* POCO_OSTREAM_METATABLE_NAME = "Poco.OStream.metatable"; // userdata methods int OStream::write(lua_State* L) { int rv = 0; OStream* osud = checkPrivateUserdata<OStream>(L, 1); std::ostream& os = osud->ostream(); luaL_checkany(L, 2); try { size_t dataLen = 0; const char* data = lua_tolstring(L, 2, &dataLen); if (data) { os.write(data, dataLen); if (!os.fail()) { lua_pushboolean(L, 1); rv = 1; } else { lua_pushboolean(L, 0); lua_pushstring(L, "write failed."); rv = 2; } } else { lua_pushnil(L); lua_pushstring(L, "cannot convert second argument to string."); rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// Flushes any written data to stream. // @return true or nil. (error) // @return error message. // @function flush int OStream::flush(lua_State* L) { int rv = 0; OStream* osud = checkPrivateUserdata<OStream>(L, 1); std::ostream& os = osud->ostream(); try { std::ostream& os = osud->ostream(); os.flush(); if (!os.fail()) { lua_pushboolean(L, 1); rv = 1; } else { lua_pushboolean(L, 0); lua_pushstring(L, "flush failed."); rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// Sets and gets the file position. // Position is measured in bytes from the beginning of the file, to the position given by offset plus a base specified by the string paramter whence. // @string[opt] whence "set" (default: beginning of file), "cur" (current positition), or "end" (end of file) // @int[opt] offset (default: 0) // @return number representing file position in bytes from the beginning of the file or nil. (error) // @return error message. // @function seek int OStream::seek(lua_State* L) { int rv = 0; OStream* osud = checkPrivateUserdata<OStream>(L, 1); std::ostream& os = osud->ostream(); std::ios_base::seekdir whence = std::ios_base::beg; const char *mode = "set"; size_t offset = 0; if (lua_gettop(L) == 2) { if (lua_isstring(L, 2)) mode = lua_tostring(L, 2); else if (lua_isnumber(L, 2)) offset = static_cast<size_t>(lua_tonumber(L, 2)); else luaL_error(L, "invalid type for parameter 2, %s", lua_typename(L, lua_type(L, 2))); } else if (lua_gettop(L) == 3) { mode = luaL_checkstring(L, 2); offset = static_cast<size_t>(luaL_checknumber(L, 3)); } if (std::strcmp(mode, "cur") == 0) whence = std::ios_base::cur; else if (std::strcmp(mode, "end") == 0) whence = std::ios_base::end; try { os.seekp(offset, whence); if (os.good()) { lua_pushnumber(L, static_cast<lua_Number>(os.tellp())); rv = 1; } else if (os.eof()) { lua_pushnil(L); lua_pushstring(L, "eof"); rv = 2; } else { lua_pushnil(L); lua_pushstring(L, "error"); rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } OStreamUserdata::OStreamUserdata(std::ostream& ostream, int udReference) : mOStream(ostream) , mOStreamReference(udReference) { } OStreamUserdata::~OStreamUserdata() { } std::ostream& OStreamUserdata::ostream() { return mOStream; } // register metatable for this class bool OStreamUserdata::registerOStream(lua_State* L) { struct UserdataMethod methods[] = { { "__gc", metamethod__gc }, { "__tostring", metamethod__tostring }, { "write", write }, { "seek", seek }, { "flush", flush }, { NULL, NULL} }; setupUserdataMetatable(L, POCO_OSTREAM_METATABLE_NAME, methods); return true; } // metamethod infrastructure int OStreamUserdata::metamethod__gc(lua_State* L) { OStreamUserdata* oud = checkPrivateUserdata<OStreamUserdata>(L, 1); if (oud->mOStreamReference != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, oud->mOStreamReference); oud->~OStreamUserdata(); return 0; } int OStreamUserdata::metamethod__tostring(lua_State* L) { OStreamUserdata* oud = checkPrivateUserdata<OStreamUserdata>(L, 1); lua_pushfstring(L, "Poco.OStream (%p)", static_cast<void*>(oud)); return 1; } } // LuaPoco <commit_msg>add ldoc for write function in OStream.<commit_after>/// Generic interface for writing to ostream userdata. // @module ostream #include "OStream.h" #include "Poco/Exception.h" #include <cstring> namespace LuaPoco { const char* POCO_OSTREAM_METATABLE_NAME = "Poco.OStream.metatable"; // userdata methods /// Write bytes to ostream. // @string data string containing bytes to be written to the ostream. // @return true or nil. (error) // @return error message. // @function write int OStream::write(lua_State* L) { int rv = 0; OStream* osud = checkPrivateUserdata<OStream>(L, 1); std::ostream& os = osud->ostream(); luaL_checkany(L, 2); try { size_t dataLen = 0; const char* data = lua_tolstring(L, 2, &dataLen); if (data) { os.write(data, dataLen); if (!os.fail()) { lua_pushboolean(L, 1); rv = 1; } else { lua_pushboolean(L, 0); lua_pushstring(L, "write failed."); rv = 2; } } else { lua_pushnil(L); lua_pushstring(L, "cannot convert second argument to string."); rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// Flushes any written data to stream. // @return true or nil. (error) // @return error message. // @function flush int OStream::flush(lua_State* L) { int rv = 0; OStream* osud = checkPrivateUserdata<OStream>(L, 1); std::ostream& os = osud->ostream(); try { std::ostream& os = osud->ostream(); os.flush(); if (!os.fail()) { lua_pushboolean(L, 1); rv = 1; } else { lua_pushboolean(L, 0); lua_pushstring(L, "flush failed."); rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// Sets and gets the file position. // Position is measured in bytes from the beginning of the file, to the position given by offset plus a base specified by the string paramter whence. // @string[opt] whence "set" (default: beginning of file), "cur" (current positition), or "end" (end of file) // @int[opt] offset (default: 0) // @return number representing file position in bytes from the beginning of the file or nil. (error) // @return error message. // @function seek int OStream::seek(lua_State* L) { int rv = 0; OStream* osud = checkPrivateUserdata<OStream>(L, 1); std::ostream& os = osud->ostream(); std::ios_base::seekdir whence = std::ios_base::beg; const char *mode = "set"; size_t offset = 0; if (lua_gettop(L) == 2) { if (lua_isstring(L, 2)) mode = lua_tostring(L, 2); else if (lua_isnumber(L, 2)) offset = static_cast<size_t>(lua_tonumber(L, 2)); else luaL_error(L, "invalid type for parameter 2, %s", lua_typename(L, lua_type(L, 2))); } else if (lua_gettop(L) == 3) { mode = luaL_checkstring(L, 2); offset = static_cast<size_t>(luaL_checknumber(L, 3)); } if (std::strcmp(mode, "cur") == 0) whence = std::ios_base::cur; else if (std::strcmp(mode, "end") == 0) whence = std::ios_base::end; try { os.seekp(offset, whence); if (os.good()) { lua_pushnumber(L, static_cast<lua_Number>(os.tellp())); rv = 1; } else if (os.eof()) { lua_pushnil(L); lua_pushstring(L, "eof"); rv = 2; } else { lua_pushnil(L); lua_pushstring(L, "error"); rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } OStreamUserdata::OStreamUserdata(std::ostream& ostream, int udReference) : mOStream(ostream) , mOStreamReference(udReference) { } OStreamUserdata::~OStreamUserdata() { } std::ostream& OStreamUserdata::ostream() { return mOStream; } // register metatable for this class bool OStreamUserdata::registerOStream(lua_State* L) { struct UserdataMethod methods[] = { { "__gc", metamethod__gc }, { "__tostring", metamethod__tostring }, { "write", write }, { "seek", seek }, { "flush", flush }, { NULL, NULL} }; setupUserdataMetatable(L, POCO_OSTREAM_METATABLE_NAME, methods); return true; } // metamethod infrastructure int OStreamUserdata::metamethod__gc(lua_State* L) { OStreamUserdata* oud = checkPrivateUserdata<OStreamUserdata>(L, 1); if (oud->mOStreamReference != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, oud->mOStreamReference); oud->~OStreamUserdata(); return 0; } int OStreamUserdata::metamethod__tostring(lua_State* L) { OStreamUserdata* oud = checkPrivateUserdata<OStreamUserdata>(L, 1); lua_pushfstring(L, "Poco.OStream (%p)", static_cast<void*>(oud)); return 1; } } // LuaPoco <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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 <limits.h> #include "main/compiler.h" #include "glsl_types.h" #include "loop_analysis.h" #include "ir_hierarchical_visitor.h" /** * Find an initializer of a variable outside a loop * * Works backwards from the loop to find the pre-loop value of the variable. * This is used, for example, to find the initial value of loop induction * variables. * * \param loop Loop where \c var is an induction variable * \param var Variable whose initializer is to be found * * \return * The \c ir_rvalue assigned to the variable outside the loop. May return * \c NULL if no initializer can be found. */ ir_rvalue * find_initial_value(ir_loop *loop, ir_variable *var) { for (exec_node *node = loop->prev; !node->is_head_sentinel(); node = node->prev) { ir_instruction *ir = (ir_instruction *) node; switch (ir->ir_type) { case ir_type_call: case ir_type_loop: case ir_type_loop_jump: case ir_type_return: case ir_type_if: return NULL; case ir_type_function: case ir_type_function_signature: assert(!"Should not get here."); return NULL; case ir_type_assignment: { ir_assignment *assign = ir->as_assignment(); ir_variable *assignee = assign->lhs->whole_variable_referenced(); if (assignee == var) return (assign->condition != NULL) ? NULL : assign->rhs; break; } default: break; } } return NULL; } int calculate_iterations(ir_rvalue *from, ir_rvalue *to, ir_rvalue *increment, enum ir_expression_operation op) { if (from == NULL || to == NULL || increment == NULL) return -1; void *mem_ctx = ralloc_context(NULL); ir_expression *const sub = new(mem_ctx) ir_expression(ir_binop_sub, from->type, to, from); ir_expression *const div = new(mem_ctx) ir_expression(ir_binop_div, sub->type, sub, increment); ir_constant *iter = div->constant_expression_value(); if (iter == NULL) return -1; if (!iter->type->is_integer()) { ir_rvalue *cast = new(mem_ctx) ir_expression(ir_unop_f2i, glsl_type::int_type, iter, NULL); iter = cast->constant_expression_value(); } int iter_value = iter->get_int_component(0); /* Make sure that the calculated number of iterations satisfies the exit * condition. This is needed to catch off-by-one errors and some types of * ill-formed loops. For example, we need to detect that the following * loop does not have a maximum iteration count. * * for (float x = 0.0; x != 0.9; x += 0.2) * ; */ const int bias[] = { -1, 0, 1 }; bool valid_loop = false; for (unsigned i = 0; i < Elements(bias); i++) { iter = (increment->type->is_integer()) ? new(mem_ctx) ir_constant(iter_value + bias[i]) : new(mem_ctx) ir_constant(float(iter_value + bias[i])); ir_expression *const mul = new(mem_ctx) ir_expression(ir_binop_mul, increment->type, iter, increment); ir_expression *const add = new(mem_ctx) ir_expression(ir_binop_add, mul->type, mul, from); ir_expression *const cmp = new(mem_ctx) ir_expression(op, glsl_type::bool_type, add, to); ir_constant *const cmp_result = cmp->constant_expression_value(); assert(cmp_result != NULL); if (cmp_result->get_bool_component(0)) { iter_value += bias[i]; valid_loop = true; break; } } ralloc_free(mem_ctx); return (valid_loop) ? iter_value : -1; } class loop_control_visitor : public ir_hierarchical_visitor { public: loop_control_visitor(loop_state *state) { this->state = state; this->progress = false; } virtual ir_visitor_status visit_leave(ir_loop *ir); loop_state *state; bool progress; }; ir_visitor_status loop_control_visitor::visit_leave(ir_loop *ir) { loop_variable_state *const ls = this->state->get(ir); /* If we've entered a loop that hasn't been analyzed, something really, * really bad has happened. */ if (ls == NULL) { assert(ls != NULL); return visit_continue; } /* Search the loop terminating conditions for one of the form 'i < c' where * i is a loop induction variable, c is a constant, and < is any relative * operator. */ int max_iterations = ls->max_iterations; if(ir->from && ir->to && ir->increment) max_iterations = calculate_iterations(ir->from, ir->to, ir->increment, (ir_expression_operation)ir->cmp); if(max_iterations < 0) max_iterations = INT_MAX; foreach_list(node, &ls->terminators) { loop_terminator *t = (loop_terminator *) node; ir_if *if_stmt = t->ir; /* If-statements can be either 'if (expr)' or 'if (deref)'. We only care * about the former here. */ ir_expression *cond = if_stmt->condition->as_expression(); if (cond == NULL) continue; switch (cond->operation) { case ir_binop_less: case ir_binop_greater: case ir_binop_lequal: case ir_binop_gequal: { /* The expressions that we care about will either be of the form * 'counter < limit' or 'limit < counter'. Figure out which is * which. */ ir_rvalue *counter = cond->operands[0]->as_dereference_variable(); ir_constant *limit = cond->operands[1]->as_constant(); enum ir_expression_operation cmp = cond->operation; if (limit == NULL) { counter = cond->operands[1]->as_dereference_variable(); limit = cond->operands[0]->as_constant(); switch (cmp) { case ir_binop_less: cmp = ir_binop_gequal; break; case ir_binop_greater: cmp = ir_binop_lequal; break; case ir_binop_lequal: cmp = ir_binop_greater; break; case ir_binop_gequal: cmp = ir_binop_less; break; default: assert(!"Should not get here."); } } if ((counter == NULL) || (limit == NULL)) break; ir_variable *var = counter->variable_referenced(); ir_rvalue *init = find_initial_value(ir, var); foreach_list(iv_node, &ls->induction_variables) { loop_variable *lv = (loop_variable *) iv_node; if (lv->var == var) { const int iterations = calculate_iterations(init, limit, lv->increment, cmp); if (iterations >= 0) { /* If the new iteration count is lower than the previously * believed iteration count, update the loop control values. */ if (iterations < max_iterations) { ir->from = init->clone(ir, NULL); ir->to = limit->clone(ir, NULL); ir->increment = lv->increment->clone(ir, NULL); ir->counter = lv->var; ir->cmp = cmp; max_iterations = iterations; } /* Remove the conditional break statement. The loop * controls are now set such that the exit condition will be * satisfied. */ if_stmt->remove(); assert(ls->num_loop_jumps > 0); ls->num_loop_jumps--; this->progress = true; } break; } } break; } default: break; } } /* If we have proven the one of the loop exit conditions is satisifed before * running the loop once, remove the loop. */ if (max_iterations == 0) ir->remove(); else ls->max_iterations = max_iterations; return visit_continue; } bool set_loop_controls(exec_list *instructions, loop_state *ls) { loop_control_visitor v(ls); v.run(instructions); return v.progress; } <commit_msg>glsl: Fix loop bounds detection.<commit_after>/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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 <limits.h> #include "main/compiler.h" #include "glsl_types.h" #include "loop_analysis.h" #include "ir_hierarchical_visitor.h" /** * Find an initializer of a variable outside a loop * * Works backwards from the loop to find the pre-loop value of the variable. * This is used, for example, to find the initial value of loop induction * variables. * * \param loop Loop where \c var is an induction variable * \param var Variable whose initializer is to be found * * \return * The \c ir_rvalue assigned to the variable outside the loop. May return * \c NULL if no initializer can be found. */ ir_rvalue * find_initial_value(ir_loop *loop, ir_variable *var) { for (exec_node *node = loop->prev; !node->is_head_sentinel(); node = node->prev) { ir_instruction *ir = (ir_instruction *) node; switch (ir->ir_type) { case ir_type_call: case ir_type_loop: case ir_type_loop_jump: case ir_type_return: case ir_type_if: return NULL; case ir_type_function: case ir_type_function_signature: assert(!"Should not get here."); return NULL; case ir_type_assignment: { ir_assignment *assign = ir->as_assignment(); ir_variable *assignee = assign->lhs->whole_variable_referenced(); if (assignee == var) return (assign->condition != NULL) ? NULL : assign->rhs; break; } default: break; } } return NULL; } int calculate_iterations(ir_rvalue *from, ir_rvalue *to, ir_rvalue *increment, enum ir_expression_operation op) { if (from == NULL || to == NULL || increment == NULL) return -1; void *mem_ctx = ralloc_context(NULL); ir_expression *const sub = new(mem_ctx) ir_expression(ir_binop_sub, from->type, to, from); ir_expression *const div = new(mem_ctx) ir_expression(ir_binop_div, sub->type, sub, increment); ir_constant *iter = div->constant_expression_value(); if (iter == NULL) return -1; if (!iter->type->is_integer()) { ir_rvalue *cast = new(mem_ctx) ir_expression(ir_unop_f2i, glsl_type::int_type, iter, NULL); iter = cast->constant_expression_value(); } int iter_value = iter->get_int_component(0); /* Make sure that the calculated number of iterations satisfies the exit * condition. This is needed to catch off-by-one errors and some types of * ill-formed loops. For example, we need to detect that the following * loop does not have a maximum iteration count. * * for (float x = 0.0; x != 0.9; x += 0.2) * ; */ const int bias[] = { -1, 0, 1 }; bool valid_loop = false; for (unsigned i = 0; i < Elements(bias); i++) { iter = (increment->type->is_integer()) ? new(mem_ctx) ir_constant(iter_value + bias[i]) : new(mem_ctx) ir_constant(float(iter_value + bias[i])); ir_expression *const mul = new(mem_ctx) ir_expression(ir_binop_mul, increment->type, iter, increment); ir_expression *const add = new(mem_ctx) ir_expression(ir_binop_add, mul->type, mul, from); ir_expression *const cmp = new(mem_ctx) ir_expression(op, glsl_type::bool_type, add, to); ir_constant *const cmp_result = cmp->constant_expression_value(); assert(cmp_result != NULL); if (cmp_result->get_bool_component(0)) { iter_value += bias[i]; valid_loop = true; break; } } ralloc_free(mem_ctx); return (valid_loop) ? iter_value : -1; } class loop_control_visitor : public ir_hierarchical_visitor { public: loop_control_visitor(loop_state *state) { this->state = state; this->progress = false; } virtual ir_visitor_status visit_leave(ir_loop *ir); loop_state *state; bool progress; }; ir_visitor_status loop_control_visitor::visit_leave(ir_loop *ir) { loop_variable_state *const ls = this->state->get(ir); /* If we've entered a loop that hasn't been analyzed, something really, * really bad has happened. */ if (ls == NULL) { assert(ls != NULL); return visit_continue; } /* Search the loop terminating conditions for one of the form 'i < c' where * i is a loop induction variable, c is a constant, and < is any relative * operator. */ int max_iterations = ls->max_iterations; if(ir->from && ir->to && ir->increment) max_iterations = calculate_iterations(ir->from, ir->to, ir->increment, (ir_expression_operation)ir->cmp); if(max_iterations < 0) max_iterations = INT_MAX; foreach_list(node, &ls->terminators) { loop_terminator *t = (loop_terminator *) node; ir_if *if_stmt = t->ir; /* If-statements can be either 'if (expr)' or 'if (deref)'. We only care * about the former here. */ ir_expression *cond = if_stmt->condition->as_expression(); if (cond == NULL) continue; switch (cond->operation) { case ir_binop_less: case ir_binop_greater: case ir_binop_lequal: case ir_binop_gequal: { /* The expressions that we care about will either be of the form * 'counter < limit' or 'limit < counter'. Figure out which is * which. */ ir_rvalue *counter = cond->operands[0]->as_dereference_variable(); ir_constant *limit = cond->operands[1]->as_constant(); enum ir_expression_operation cmp = cond->operation; if (limit == NULL) { counter = cond->operands[1]->as_dereference_variable(); limit = cond->operands[0]->as_constant(); switch (cmp) { case ir_binop_less: cmp = ir_binop_greater; break; case ir_binop_greater: cmp = ir_binop_less; break; case ir_binop_lequal: cmp = ir_binop_gequal; break; case ir_binop_gequal: cmp = ir_binop_lequal; break; default: assert(!"Should not get here."); } } if ((counter == NULL) || (limit == NULL)) break; ir_variable *var = counter->variable_referenced(); ir_rvalue *init = find_initial_value(ir, var); foreach_list(iv_node, &ls->induction_variables) { loop_variable *lv = (loop_variable *) iv_node; if (lv->var == var) { const int iterations = calculate_iterations(init, limit, lv->increment, cmp); if (iterations >= 0) { /* If the new iteration count is lower than the previously * believed iteration count, update the loop control values. */ if (iterations < max_iterations) { ir->from = init->clone(ir, NULL); ir->to = limit->clone(ir, NULL); ir->increment = lv->increment->clone(ir, NULL); ir->counter = lv->var; ir->cmp = cmp; max_iterations = iterations; } /* Remove the conditional break statement. The loop * controls are now set such that the exit condition will be * satisfied. */ if_stmt->remove(); assert(ls->num_loop_jumps > 0); ls->num_loop_jumps--; this->progress = true; } break; } } break; } default: break; } } /* If we have proven the one of the loop exit conditions is satisifed before * running the loop once, remove the loop. */ if (max_iterations == 0) ir->remove(); else ls->max_iterations = max_iterations; return visit_continue; } bool set_loop_controls(exec_list *instructions, loop_state *ls) { loop_control_visitor v(ls); v.run(instructions); return v.progress; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013-2014 Nick Guletskii * * 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 "OSDInstance.hpp" #include "Colour.hpp" #include "ConfigurationManager.hpp" #include "FontRenderer.hpp" #include "GLAttribState.hpp" #include "GLLoader.hpp" #include "GLXOSD.hpp" #include "Utils.hpp" #include <algorithm> #include <map> #include <sstream> #include <string> #include <vector> #include <GL/gl.h> #include <boost/any.hpp> #include <boost/lexical_cast.hpp> #include <sys/time.h> namespace glxosd { OSDInstance::OSDInstance() : osdText("Gathering data...") { const ConfigurationManager &configurationManager = GLXOSD::instance()->getConfigurationManager(); std::string fontName = configurationManager.getProperty<std::string>( "font_name"); int fontSize = configurationManager.getProperty<int>("font_size_int"); int fontColourR = configurationManager.getProperty<int>( "font_colour_r_int"); int fontColourG = configurationManager.getProperty<int>( "font_colour_g_int"); int fontColourB = configurationManager.getProperty<int>( "font_colour_b_int"); int fontColourA = configurationManager.getProperty<int>( "font_colour_a_int"); int fontOutlineColourR = configurationManager.getProperty<int>( "font_outline_colour_r_int"); int fontOutlineColourG = configurationManager.getProperty<int>( "font_outline_colour_g_int"); int fontOutlineColourB = configurationManager.getProperty<int>( "font_outline_colour_b_int"); int fontOutlineColourA = configurationManager.getProperty<int>( "font_outline_colour_a_int"); float outlineWidth = configurationManager.getProperty<bool>("show_text_outline_bool") ? configurationManager.getProperty<float>( "font_outline_width_float") : 0; int horizontalDPI = configurationManager.getProperty<int>( "font_dpi_horizontal_int"); int verticalDPI = configurationManager.getProperty<int>( "font_dpi_vertical_int"); int textPositionX = configurationManager.getProperty<int>("text_pos_x_int"); int textPositionY = configurationManager.getProperty<int>("text_pos_y_int"); float textSpacingY = configurationManager.getProperty<float>( "text_spacing_y_float"); float textSpacingX = configurationManager.getProperty<float>( "text_spacing_x_float"); fpsFormat = configurationManager.getProperty<boost::format>("fps_format"); frameLoggingMessage = configurationManager.getProperty<std::string>( "frame_logging_message_string"); renderer = new FontRenderer(fontName, fontSize, horizontalDPI, verticalDPI, outlineWidth); renderer->setFontColour( ColourRGBA(fontColourR, fontColourG, fontColourB, fontColourA)); renderer->setFontOutlineColour( ColourRGBA(fontOutlineColourR, fontOutlineColourG, fontOutlineColourB, fontOutlineColourA)); renderer->setTextPositionX(textPositionX); renderer->setTextPositionY(textPositionY); renderer->setTextSpacingX(textSpacingX); renderer->setTextSpacingY(textSpacingY); currentFrameCount = 0; framesPerSecond = 0; //Set the time for the first time. previousTime = getMonotonicTimeNanoseconds() / 1000000ULL; } void OSDInstance::update(long currentMilliseconds) { framesPerSecond = 1000.0 * currentFrameCount / (currentMilliseconds - previousTime); previousTime = currentMilliseconds; previousTime = currentMilliseconds; currentFrameCount = 0; std::stringstream osdTextBuilder; osdTextBuilder << boost::format(fpsFormat) % framesPerSecond; std::vector<PluginDataProvider>* dataProviders = GLXOSD::instance()->getPluginDataProviders(); std::for_each(dataProviders->begin(), dataProviders->end(), [&osdTextBuilder](PluginDataProvider &sensorDataProvider) { std::string* strPtr = sensorDataProvider(GLXOSD::instance()); osdTextBuilder << *strPtr; delete strPtr; // Prevent memory leak. Goddamn C ABI forcing me to use pointers!! // The weird thing is: it gets deleted even without the delete. How and why? }); osdText = osdTextBuilder.str(); } void OSDInstance::renderText(unsigned int width, unsigned int height) { std::stringstream osd_text_reader; osd_text_reader << osdText; if (GLXOSD::instance()->isFrameLoggingEnabled()) { osd_text_reader << std::endl << frameLoggingMessage; } std::string str = osd_text_reader.str(); std::transform(str.begin(), str.end(), str.begin(), ::toupper); renderer->render(width, height, str); } void OSDInstance::render(unsigned int width, unsigned int height) { currentFrameCount++; long currentTimeMilliseconds = getMonotonicTimeNanoseconds() / 1000000ULL; //Refresh the info every 500 milliseconds if (currentTimeMilliseconds - previousTime >= 500) { update(currentTimeMilliseconds); } // Memorise misc. settings GLint program; { glGetIntegerv(GL_CURRENT_PROGRAM, &program); glUseProgram(0); } glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); GLint frontFace; { glGetIntegerv(GL_FRONT_FACE, &frontFace); glFrontFace(GL_CCW); } GLfloat blendColour[4]; { glGetFloatv(GL_BLEND_COLOR, blendColour); glBlendColor(0, 0, 0, 0); } GLboolean colourMask[4]; { glGetBooleanv(GL_COLOR_WRITEMASK, colourMask); glColorMask(1, 1, 1, 1); } GLint blendSrc; GLint blendDst; { glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc); glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } GLint depthFunc; { glGetIntegerv(GL_DEPTH_FUNC, &depthFunc); glDepthFunc(GL_LESS); } //Equivalent to glPushAttrib -> glEnable/Disable -> glPopAttrib GLAttribState attribState(glEnable, glDisable, glIsEnabled); GLAttribState clientAttribState(glEnableClientState, glDisableClientState, glIsEnabled); { attribState.set(GL_ALPHA_TEST, GL_FALSE); attribState.set(GL_AUTO_NORMAL, GL_FALSE); attribState.set(GL_CULL_FACE, GL_FALSE); attribState.set(GL_COLOR_LOGIC_OP, GL_FALSE); attribState.set(GL_COLOR_TABLE, GL_FALSE); attribState.set(GL_CONVOLUTION_1D, GL_FALSE); attribState.set(GL_CONVOLUTION_2D, GL_FALSE); attribState.set(GL_CULL_FACE, GL_FALSE); attribState.set(GL_DEPTH_TEST, GL_FALSE); attribState.set(GL_DITHER, GL_FALSE); attribState.set(GL_FOG, GL_FALSE); attribState.set(GL_HISTOGRAM, GL_FALSE); attribState.set(GL_INDEX_LOGIC_OP, GL_FALSE); attribState.set(GL_LIGHTING, GL_FALSE); attribState.set(GL_NORMALIZE, GL_FALSE); attribState.set(GL_MINMAX, GL_FALSE); attribState.set(GL_SEPARABLE_2D, GL_FALSE); attribState.set(GL_SCISSOR_TEST, GL_FALSE); attribState.set(GL_STENCIL_TEST, GL_FALSE); attribState.set(GL_SAMPLE_ALPHA_TO_COVERAGE, GL_FALSE); attribState.set(GL_COLOR_LOGIC_OP, GL_FALSE); attribState.set(GL_CULL_FACE, GL_FALSE); attribState.set(GL_DEPTH_TEST, GL_FALSE); attribState.set(GL_MULTISAMPLE, GL_FALSE); attribState.set(GL_POLYGON_OFFSET_POINT, GL_FALSE); attribState.set(GL_POLYGON_OFFSET_LINE, GL_FALSE); attribState.set(GL_POLYGON_OFFSET_FILL, GL_FALSE); attribState.set(GL_SAMPLE_COVERAGE, GL_FALSE); attribState.set(GL_SCISSOR_TEST, GL_FALSE); attribState.set(GL_STENCIL_TEST, GL_FALSE); attribState.set(GL_TEXTURE_GEN_Q, GL_FALSE); attribState.set(GL_TEXTURE_GEN_R, GL_FALSE); attribState.set(GL_TEXTURE_GEN_S, GL_FALSE); attribState.set(GL_TEXTURE_GEN_T, GL_FALSE); clientAttribState.set(GL_COLOR_ARRAY, GL_FALSE); clientAttribState.set(GL_EDGE_FLAG_ARRAY, GL_FALSE); clientAttribState.set(GL_INDEX_ARRAY, GL_FALSE); clientAttribState.set(GL_NORMAL_ARRAY, GL_FALSE); clientAttribState.set(GL_TEXTURE_COORD_ARRAY, GL_TRUE); clientAttribState.set(GL_VERTEX_ARRAY, GL_TRUE); } { attribState.set(GL_TEXTURE_CUBE_MAP, GL_FALSE); attribState.set(GL_VERTEX_PROGRAM_ARB, GL_FALSE); attribState.set(GL_FRAGMENT_PROGRAM_ARB, GL_FALSE); attribState.set(GL_BLEND, GL_TRUE); attribState.set(GL_TEXTURE_2D, GL_TRUE); } //Memorise buffer states GLint pixelUnpackBufferBinding = 0, arrayBufferBinding = 0, activeTexture = 0, textureBinding2D = 0, vertexArrayBinding = 0; glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &pixelUnpackBufferBinding); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &arrayBufferBinding); glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTexture); glGetIntegerv(GL_TEXTURE_BINDING_2D, &textureBinding2D); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &vertexArrayBinding); renderText(width, height); //Revert buffer states glActiveTexture(activeTexture); glBindTexture(GL_TEXTURE_2D, textureBinding2D); glBindVertexArray(vertexArrayBinding); glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pixelUnpackBufferBinding); glBindBuffer(GL_ARRAY_BUFFER, arrayBufferBinding); //Revert misc settings glDepthFunc(depthFunc); glBlendColor(blendColour[0], blendColour[1], blendColour[2], blendColour[3]); glColorMask(colourMask[0], colourMask[1], colourMask[2], colourMask[3]); glFrontFace(frontFace); glBlendFunc(blendSrc, blendDst); glUseProgram(program); } OSDInstance::~OSDInstance() { } } <commit_msg>Fix texture parameters not being backed up and reverted<commit_after>/* * Copyright (C) 2013-2014 Nick Guletskii * * 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 "OSDInstance.hpp" #include "Colour.hpp" #include "ConfigurationManager.hpp" #include "FontRenderer.hpp" #include "GLAttribState.hpp" #include "GLLoader.hpp" #include "GLXOSD.hpp" #include "Utils.hpp" #include <algorithm> #include <map> #include <sstream> #include <string> #include <vector> #include <GL/gl.h> #include <boost/any.hpp> #include <boost/lexical_cast.hpp> #include <sys/time.h> namespace glxosd { OSDInstance::OSDInstance() : osdText("Gathering data...") { const ConfigurationManager &configurationManager = GLXOSD::instance()->getConfigurationManager(); std::string fontName = configurationManager.getProperty<std::string>( "font_name"); int fontSize = configurationManager.getProperty<int>("font_size_int"); int fontColourR = configurationManager.getProperty<int>( "font_colour_r_int"); int fontColourG = configurationManager.getProperty<int>( "font_colour_g_int"); int fontColourB = configurationManager.getProperty<int>( "font_colour_b_int"); int fontColourA = configurationManager.getProperty<int>( "font_colour_a_int"); int fontOutlineColourR = configurationManager.getProperty<int>( "font_outline_colour_r_int"); int fontOutlineColourG = configurationManager.getProperty<int>( "font_outline_colour_g_int"); int fontOutlineColourB = configurationManager.getProperty<int>( "font_outline_colour_b_int"); int fontOutlineColourA = configurationManager.getProperty<int>( "font_outline_colour_a_int"); float outlineWidth = configurationManager.getProperty<bool>("show_text_outline_bool") ? configurationManager.getProperty<float>( "font_outline_width_float") : 0; int horizontalDPI = configurationManager.getProperty<int>( "font_dpi_horizontal_int"); int verticalDPI = configurationManager.getProperty<int>( "font_dpi_vertical_int"); int textPositionX = configurationManager.getProperty<int>("text_pos_x_int"); int textPositionY = configurationManager.getProperty<int>("text_pos_y_int"); float textSpacingY = configurationManager.getProperty<float>( "text_spacing_y_float"); float textSpacingX = configurationManager.getProperty<float>( "text_spacing_x_float"); fpsFormat = configurationManager.getProperty<boost::format>("fps_format"); frameLoggingMessage = configurationManager.getProperty<std::string>( "frame_logging_message_string"); renderer = new FontRenderer(fontName, fontSize, horizontalDPI, verticalDPI, outlineWidth); renderer->setFontColour( ColourRGBA(fontColourR, fontColourG, fontColourB, fontColourA)); renderer->setFontOutlineColour( ColourRGBA(fontOutlineColourR, fontOutlineColourG, fontOutlineColourB, fontOutlineColourA)); renderer->setTextPositionX(textPositionX); renderer->setTextPositionY(textPositionY); renderer->setTextSpacingX(textSpacingX); renderer->setTextSpacingY(textSpacingY); currentFrameCount = 0; framesPerSecond = 0; //Set the time for the first time. previousTime = getMonotonicTimeNanoseconds() / 1000000ULL; } void OSDInstance::update(long currentMilliseconds) { framesPerSecond = 1000.0 * currentFrameCount / (currentMilliseconds - previousTime); previousTime = currentMilliseconds; previousTime = currentMilliseconds; currentFrameCount = 0; std::stringstream osdTextBuilder; osdTextBuilder << boost::format(fpsFormat) % framesPerSecond; std::vector<PluginDataProvider>* dataProviders = GLXOSD::instance()->getPluginDataProviders(); std::for_each(dataProviders->begin(), dataProviders->end(), [&osdTextBuilder](PluginDataProvider &sensorDataProvider) { std::string* strPtr = sensorDataProvider(GLXOSD::instance()); osdTextBuilder << *strPtr; delete strPtr; // Prevent memory leak. Goddamn C ABI forcing me to use pointers!! // The weird thing is: it gets deleted even without the delete. How and why? }); osdText = osdTextBuilder.str(); } void OSDInstance::renderText(unsigned int width, unsigned int height) { std::stringstream osd_text_reader; osd_text_reader << osdText; if (GLXOSD::instance()->isFrameLoggingEnabled()) { osd_text_reader << std::endl << frameLoggingMessage; } std::string str = osd_text_reader.str(); std::transform(str.begin(), str.end(), str.begin(), ::toupper); renderer->render(width, height, str); } void OSDInstance::render(unsigned int width, unsigned int height) { currentFrameCount++; long currentTimeMilliseconds = getMonotonicTimeNanoseconds() / 1000000ULL; //Refresh the info every 500 milliseconds if (currentTimeMilliseconds - previousTime >= 500) { update(currentTimeMilliseconds); } // Memorise misc. settings GLint program; { glGetIntegerv(GL_CURRENT_PROGRAM, &program); glUseProgram(0); } glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); GLint frontFace; { glGetIntegerv(GL_FRONT_FACE, &frontFace); glFrontFace(GL_CCW); } GLint blendSrc; GLint blendDst; { glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc); glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst); } GLfloat blendColour[4]; { glGetFloatv(GL_BLEND_COLOR, blendColour); } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendColor(0, 0, 0, 0); GLboolean colourMask[4]; { glGetBooleanv(GL_COLOR_WRITEMASK, colourMask); glColorMask(1, 1, 1, 1); } GLint depthFunc; { glGetIntegerv(GL_DEPTH_FUNC, &depthFunc); glDepthFunc(GL_LESS); } //Equivalent to glPushAttrib -> glEnable/Disable -> glPopAttrib GLAttribState attribState(glEnable, glDisable, glIsEnabled); GLAttribState clientAttribState(glEnableClientState, glDisableClientState, glIsEnabled); { attribState.set(GL_ALPHA_TEST, GL_FALSE); attribState.set(GL_AUTO_NORMAL, GL_FALSE); attribState.set(GL_CULL_FACE, GL_FALSE); attribState.set(GL_COLOR_LOGIC_OP, GL_FALSE); attribState.set(GL_COLOR_TABLE, GL_FALSE); attribState.set(GL_CONVOLUTION_1D, GL_FALSE); attribState.set(GL_CONVOLUTION_2D, GL_FALSE); attribState.set(GL_CULL_FACE, GL_FALSE); attribState.set(GL_DEPTH_TEST, GL_FALSE); attribState.set(GL_DITHER, GL_FALSE); attribState.set(GL_FOG, GL_FALSE); attribState.set(GL_HISTOGRAM, GL_FALSE); attribState.set(GL_INDEX_LOGIC_OP, GL_FALSE); attribState.set(GL_LIGHTING, GL_FALSE); attribState.set(GL_NORMALIZE, GL_FALSE); attribState.set(GL_MINMAX, GL_FALSE); attribState.set(GL_SEPARABLE_2D, GL_FALSE); attribState.set(GL_SCISSOR_TEST, GL_FALSE); attribState.set(GL_STENCIL_TEST, GL_FALSE); attribState.set(GL_SAMPLE_ALPHA_TO_COVERAGE, GL_FALSE); attribState.set(GL_COLOR_LOGIC_OP, GL_FALSE); attribState.set(GL_CULL_FACE, GL_FALSE); attribState.set(GL_DEPTH_TEST, GL_FALSE); attribState.set(GL_MULTISAMPLE, GL_FALSE); attribState.set(GL_POLYGON_OFFSET_POINT, GL_FALSE); attribState.set(GL_POLYGON_OFFSET_LINE, GL_FALSE); attribState.set(GL_POLYGON_OFFSET_FILL, GL_FALSE); attribState.set(GL_SAMPLE_COVERAGE, GL_FALSE); attribState.set(GL_SCISSOR_TEST, GL_FALSE); attribState.set(GL_STENCIL_TEST, GL_FALSE); attribState.set(GL_TEXTURE_GEN_Q, GL_FALSE); attribState.set(GL_TEXTURE_GEN_R, GL_FALSE); attribState.set(GL_TEXTURE_GEN_S, GL_FALSE); attribState.set(GL_TEXTURE_GEN_T, GL_FALSE); clientAttribState.set(GL_COLOR_ARRAY, GL_FALSE); clientAttribState.set(GL_EDGE_FLAG_ARRAY, GL_FALSE); clientAttribState.set(GL_INDEX_ARRAY, GL_FALSE); clientAttribState.set(GL_NORMAL_ARRAY, GL_FALSE); clientAttribState.set(GL_TEXTURE_COORD_ARRAY, GL_TRUE); clientAttribState.set(GL_VERTEX_ARRAY, GL_TRUE); } { attribState.set(GL_TEXTURE_CUBE_MAP, GL_FALSE); attribState.set(GL_VERTEX_PROGRAM_ARB, GL_FALSE); attribState.set(GL_FRAGMENT_PROGRAM_ARB, GL_FALSE); attribState.set(GL_BLEND, GL_TRUE); attribState.set(GL_TEXTURE_2D, GL_TRUE); } GLint pixelUnpackBufferBinding = 0, arrayBufferBinding = 0, activeTexture = 0, textureBinding2D = 0, vertexArrayBinding = 0, textureMinFilter = 0, textureMagFilter = 0, textureWrapS = 0, textureWrapT = 0; //Memorise buffer states glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &pixelUnpackBufferBinding); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &arrayBufferBinding); glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTexture); glGetIntegerv(GL_TEXTURE_BINDING_2D, &textureBinding2D); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &vertexArrayBinding); //Memorise texture parameters glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, &textureMinFilter); glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, &textureMagFilter); glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, &textureWrapS); glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, &textureWrapT); renderText(width, height); //Revert texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, textureMinFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, textureMagFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureWrapS); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureWrapT); //Revert buffer states glActiveTexture(activeTexture); glBindTexture(GL_TEXTURE_2D, textureBinding2D); glBindVertexArray(vertexArrayBinding); glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pixelUnpackBufferBinding); glBindBuffer(GL_ARRAY_BUFFER, arrayBufferBinding); //Revert misc settings glDepthFunc(depthFunc); glBlendFunc(blendSrc, blendDst); glBlendColor(blendColour[0], blendColour[1], blendColour[2], blendColour[3]); glColorMask(colourMask[0], colourMask[1], colourMask[2], colourMask[3]); glFrontFace(frontFace); glUseProgram(program); } OSDInstance::~OSDInstance() { } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include "snowman.hpp" int main(int argc, char *argv[]) { Snowman sm = Snowman(); std::string VERSION_STRING = "v" + std::to_string(Snowman::MAJOR_VERSION) + "." + std::to_string(Snowman::MINOR_VERSION) + "." + std::to_string(Snowman::PATCH_VERSION); // parse arguments std::string filename; for (int i = 1; i < argc; ++i) { std::string arg(argv[i]); if (arg[0] == '-') { char argid; if (arg.length() >= 2 && arg[1] == '-') { // no switch on strings :( if (arg == "--help") argid = 'h'; else if (arg == "--interactive") argid = 'i'; else if (arg == "--debug") argid = 'd'; else if (arg == "--evaluate") argid = 'e'; else { std::cerr << "Unknown long argument `" << arg << "'" << std::endl; return 1; } } else { if (arg.length() != 2) { std::cerr << "Invalid syntax for argument `" << arg << "'" << std::endl; return 1; } else { argid = arg[1]; } } switch (argid) { case 'h': std::cout << "Usage: " << argv[0] << " [OPTION]... [FILENAME]\n" << "Options:\n" " -h, --help: (without filename) display this message\n" " -i, --interactive: (without filename) start a REPL\n" " -d, --debug: include debug output\n" " -e, --evaluate: takes one parameter, runs as Snowman" "code\n" "Snowman will read from STDIN if you do not specify a " "file name or the -h or -i options.\n" "Snowman version: " << VERSION_STRING << "\n"; return 0; case 'i': { std::cout << "Snowman REPL, version " << VERSION_STRING << std::endl; std::cout << ">> "; std::string line; while (std::getline(std::cin, line)) { sm.run(line); std::cout << sm.debug(); std::cout << ">> "; } } case 'd': sm.debugOutput = true; break; case 'e': if ((++i) == argc) { std::cerr << "Argument `" << arg << "' requires a" "parameter" << std::endl; return 1; } sm.run(std::string(argv[i])); return 0; default: std::cerr << "Unknown argument `" << arg << "'" << std::endl; return 1; } } else if (filename == "") { filename = arg; } else { std::cerr << "Multiple filenames specified (" << filename << ", " << arg << ")" << std::endl; return 1; } } // retrieve code to run std::string code; if (filename == "") { std::string line; while (std::getline(std::cin, line) && line != "__END__") code += line; } else { std::ifstream infile(filename.c_str()); if (infile.good()) { std::stringstream buf; buf << infile.rdbuf() << std::endl; code = buf.str(); } else { std::cerr << "Could not read file " << filename << std::endl; return 1; } } // run code sm.run(code); } <commit_msg>fix a few output things<commit_after>#include <iostream> #include <fstream> #include <sstream> #include "snowman.hpp" int main(int argc, char *argv[]) { Snowman sm = Snowman(); std::string VERSION_STRING = "v" + std::to_string(Snowman::MAJOR_VERSION) + "." + std::to_string(Snowman::MINOR_VERSION) + "." + std::to_string(Snowman::PATCH_VERSION); // parse arguments std::string filename; for (int i = 1; i < argc; ++i) { std::string arg(argv[i]); if (arg[0] == '-') { char argid; if (arg.length() >= 2 && arg[1] == '-') { // no switch on strings :( if (arg == "--help") argid = 'h'; else if (arg == "--interactive") argid = 'i'; else if (arg == "--debug") argid = 'd'; else if (arg == "--evaluate") argid = 'e'; else { std::cerr << "Unknown long argument `" << arg << "'" << std::endl; return 1; } } else { if (arg.length() != 2) { std::cerr << "Invalid syntax for argument `" << arg << "'" << std::endl; return 1; } else { argid = arg[1]; } } switch (argid) { case 'h': std::cout << "Usage: " << argv[0] << " [OPTION]... [FILENAME]\n" << "Options:\n" " -h, --help: (without filename) display this message\n" " -i, --interactive: (without filename) start a REPL\n" " -e, --evaluate: (without filename) takes one " "parameter, runs as Snowman code\n" " -d, --debug: include debug output\n" "Snowman will read from STDIN if you do not specify a " "file name or the -h or -i options.\n" "Snowman version: " << VERSION_STRING << "\n"; return 0; case 'i': { std::cout << "Snowman REPL, " << VERSION_STRING << std::endl; std::cout << ">> "; std::string line; while (std::getline(std::cin, line)) { sm.run(line); std::cout << sm.debug(); std::cout << ">> "; } } case 'd': sm.debugOutput = true; break; case 'e': if ((++i) == argc) { std::cerr << "Argument `" << arg << "' requires a" "parameter" << std::endl; return 1; } sm.run(std::string(argv[i])); return 0; default: std::cerr << "Unknown argument `" << arg << "'" << std::endl; return 1; } } else if (filename == "") { filename = arg; } else { std::cerr << "Multiple filenames specified (" << filename << ", " << arg << ")" << std::endl; return 1; } } // retrieve code to run std::string code; if (filename == "") { std::string line; while (std::getline(std::cin, line) && line != "__END__") code += line; } else { std::ifstream infile(filename.c_str()); if (infile.good()) { std::stringstream buf; buf << infile.rdbuf() << std::endl; code = buf.str(); } else { std::cerr << "Could not read file " << filename << std::endl; return 1; } } // run code sm.run(code); } <|endoftext|>
<commit_before>/** * pugixml parser - version 1.0 * -------------------------------------------------------- * Copyright (C) 2006-2010, by Arseny Kapoulkine ([email protected]) * Report bugs and download new versions at http://pugixml.org/ * * This library is distributed under the MIT License. See notice at the end * of this file. * * This work is based on the pugxml parser, which is: * Copyright (C) 2003, by Kristen Wegner ([email protected]) */ #ifndef HEADER_PUGICONFIG_HPP #define HEADER_PUGICONFIG_HPP // Uncomment this to enable wchar_t mode // #define PUGIXML_WCHAR_MODE // Uncomment this to disable XPath // #define PUGIXML_NO_XPATH // Uncomment this to disable STL // Note: you can't use XPath with PUGIXML_NO_STL // #define PUGIXML_NO_STL // Uncomment this to disable exceptions // Note: you can't use XPath with PUGIXML_NO_EXCEPTIONS // #define PUGIXML_NO_EXCEPTIONS // Set this to control attributes for public classes/functions, i.e.: // #define PUGIXML_API __declspec(dllexport) // to export all public symbols from DLL // #define PUGIXML_CLASS __declspec(dllimport) // to import all classes from DLL // #define PUGIXML_FUNCTION __fastcall // to set calling conventions to all public functions to fastcall // In absence of PUGIXML_CLASS/PUGIXML_FUNCTION definitions PUGIXML_API is used instead #endif /** * Copyright (c) 2006-2010 Arseny Kapoulkine * * 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. */ <commit_msg>Export pugixml symbols from windows DLL.<commit_after>/** * pugixml parser - version 1.0 * -------------------------------------------------------- * Copyright (C) 2006-2010, by Arseny Kapoulkine ([email protected]) * Report bugs and download new versions at http://pugixml.org/ * * This library is distributed under the MIT License. See notice at the end * of this file. * * This work is based on the pugxml parser, which is: * Copyright (C) 2003, by Kristen Wegner ([email protected]) */ #ifndef HEADER_PUGICONFIG_HPP #define HEADER_PUGICONFIG_HPP // Uncomment this to enable wchar_t mode // #define PUGIXML_WCHAR_MODE // Uncomment this to disable XPath // #define PUGIXML_NO_XPATH // Uncomment this to disable STL // Note: you can't use XPath with PUGIXML_NO_STL // #define PUGIXML_NO_STL // Uncomment this to disable exceptions // Note: you can't use XPath with PUGIXML_NO_EXCEPTIONS // #define PUGIXML_NO_EXCEPTIONS // Set this to control attributes for public classes/functions, i.e.: // #define PUGIXML_API __declspec(dllexport) // to export all public symbols from DLL // #define PUGIXML_CLASS __declspec(dllimport) // to import all classes from DLL // #define PUGIXML_FUNCTION __fastcall // to set calling conventions to all public functions to fastcall // In absence of PUGIXML_CLASS/PUGIXML_FUNCTION definitions PUGIXML_API is used instead // OIIO: use already defined DLLPUBLIC #include "export.h" #define PUGIXML_API DLLPUBLIC #endif /** * Copyright (c) 2006-2010 Arseny Kapoulkine * * 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. */ <|endoftext|>
<commit_before>/* * $Id: sample.h,v 1.6 2006/09/18 06:23:39 nathanst Exp $ * * Driver.h * hog * * Created by Thayne Walker on 3/17/17. * Copyright 2017 Thayne Walker, University of Denver. All rights reserved. * * This file is part of HOG. * * HOG 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. * * HOG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HOG; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <memory> #include <iostream> #include <unordered_set> #include <unordered_map> #include "Map2DEnvironment.h" int maxDepth; struct Hashable{ virtual uint64_t Hash()const=0; }; struct NodePtrComp { bool operator()(const Hashable* lhs, const Hashable* rhs) const { return lhs->Hash()<rhs->Hash(); } }; namespace std { template <> struct hash<Hashable> { size_t operator()(Hashable* const & x) const noexcept { return x->Hash(); } }; } struct Node : public Hashable{ static MapEnvironment* env; Node(){} Node(xyLoc a, int d):n(a),depth(d),optimal(false){} xyLoc n; uint16_t depth; bool optimal; bool connected()const{return parents.size()+successors.size();} std::unordered_set<Node*> parents; std::unordered_set<Node*> successors; virtual uint64_t Hash()const{return (env->GetStateHash(n)<<16) | depth;} }; typedef std::vector<std::unordered_set<Node*>> MDD; typedef std::unordered_map<uint64_t,Node> DAG; std::ostream& operator << (std::ostream& ss, Node const& n){ ss << std::string(n.depth,' ')<<n.n; return ss; } std::ostream& operator << (std::ostream& ss, Node const* n){ ss << std::string(n->depth,' ')<<n->n << n->successors.size()<< "\n"; for(auto const m: n->successors) ss << m; return ss; } MapEnvironment* Node::env=nullptr; bool LimitedDFS(xyLoc const& start, xyLoc const& end, DAG& dag, MDD& mdd, int depth, int maxDepth){ //std::cout << start << " g:" << (maxDepth-depth) << " h:" << Node::env->HCost(start,end) << " f:" << ((maxDepth-depth)+Node::env->HCost(start,end)) << "\n"; if(depth<0 || (maxDepth-depth)+Node::env->HCost(start,end)>maxDepth){ // Note - this only works for a perfect heuristic. //std::cout << "pruned\n"; return false; } if(Node::env->GoalTest(end,start)){ Node n(start,depth); uint64_t hash(n.Hash()); dag[hash]=n; std::unordered_set<Node*>& s=mdd[maxDepth-(depth)]; s.insert(&dag[hash]); //std::cout << "found " << start << "\n"; return true; } std::vector<xyLoc> successors; Node::env->GetSuccessors(start,successors); bool result(false); for(auto const& node: successors){ if(LimitedDFS(node,end,dag,mdd,depth-1,maxDepth)){ Node n(start,depth); uint64_t hash(n.Hash()); if(dag.find(hash)==dag.end()){ dag[hash]=n; std::unordered_set<Node*>& s=mdd[maxDepth-(depth)]; s.insert(&dag[hash]); }else if(dag[hash].optimal){ return true; // Already found a solution from search at this depth } Node* parent(&dag[hash]); //std::cout << "found " << start << "\n"; std::unique_ptr<Node> c(new Node(node,depth-1)); Node* current(dag.find(c->Hash())==dag.end()?c.release():&dag[c->Hash()]); current->optimal = result = true; //std::cout << *parent << " parent of " << *current << "\n"; dag[current->Hash()].parents.insert(parent); //std::cout << *current << " child of " << *parent << "\n"; dag[parent->Hash()].successors.insert(current); } } return result; } void GetMDD(xyLoc const& start, xyLoc const& end, MDD& mdd, int depth){ // TODO: make this contain pointers or maybe combine into a structure with MDD. // as-is, memory will be deallocated when this function exits. DAG dag; mdd.resize(depth+1); LimitedDFS(start,end,dag,mdd,depth,depth); for(auto const& a: mdd){ for(auto const& n: a){ std::cout << *n; } std::cout << "\n"; } } void eraseDown(Node* n){ // If no parent points here, then we must disconnect this node if(n->parents.empty()){ // Erase children's parent pointers terminating at this node for(auto& m: n->successors){ auto p(m->parents.find(n)); if(p!=m->parents.end()){ m->parents.erase(p); } // recurse eraseDown(m); } n->successors.clear(); } } void eraseUp(Node* n){ // If this node has no successors, it cannot connect us to the goal if(n->successors.empty()){ // Erase parent's successor pointers terminating at this node for(auto& m: n->parents){ auto p(m->successors.find(n)); if(p!=m->successors.end()){ m->successors.erase(p); } // recurse eraseUp(m); } n->parents.clear(); } } void disconnect(Node* n){ // Erase edges pointing to parents, and their edges pointing at me. for(auto& m: n->parents){ auto p(m->successors.find(n)); if(p!=m->successors.end()){ m->successors.erase(p); } eraseUp(m); } n->parents.clear(); // Erase edges to/from successors for(auto& m: n->successors){ auto p(m->parents.find(n)); if(p!=m->parents.end()){ m->parents.erase(p); } // recurse eraseDown(m); } n->successors.clear(); } struct ICTSNode{ ICTSNode(int agents):mdd(agents){} std::vector<MDD> mdd; // Returns true and sets a1, a2 on conflict bool CheckConflicts(int** a1, int** a2){ // Check all pairs for(int i(0); i<mdd.size(); ++i){ for(int j(i+1); j<mdd.size(); ++j){ // Check all times for(int t(0); t<std::min(mdd[i].size(),mdd[j].size()); ++t){ // Check for node and edge conflicts // Finally, check for severed connectivity by checking across a time slice. If all nodes have no parents or children, then this ICTS node is rendered infeasible for(auto const& m: mdd[i][t]){ if(!m->connected()) continue; // Can't get here for(auto const& n: mdd[j][t]){ if(!n->connected()) continue; // Can't get here if(m->Hash() == n->Hash()){ //TODO Use iterator and "erase in place" //1. Erase parent's pointers to me and my pointers to parents //2. Erase children's pointers to me and my pointers to children //3. Call eraser subroutine } if(t!=0){ // Check edges for(auto& mp: m->parents){ for(auto& np: n->parents){ if(mp->n==n->n || np->n==m->n){ // Same edge traversal //TODO Use iterator and "erase in place" //1. Erase parent's pointer to me and my pointer to parent //2. Call eraser subroutine } } } } } } } } } return true; } }; void testErasers(){ Node a(xyLoc(1,1),1); Node b(xyLoc(2,1),2); Node c(xyLoc(3,1),2); Node d(xyLoc(4,1),2); Node b1(xyLoc(5,1),3); Node c1(xyLoc(6,1),3); Node d1(xyLoc(7,1),3); Node e(xyLoc(8,1),4); a.successors.insert(&b); a.successors.insert(&c); a.successors.insert(&d); b.parents.insert(&a); c.parents.insert(&a); d.parents.insert(&a); b.successors.insert(&b1); c.successors.insert(&c1); d.successors.insert(&d1); b1.parents.insert(&b); c1.parents.insert(&c); d1.parents.insert(&d); b1.successors.insert(&e); c1.successors.insert(&e); d1.successors.insert(&e); e.parents.insert(&b1); e.parents.insert(&c1); e.parents.insert(&d1); std::cout << &a << "\n"; // Disconnect b disconnect(&b); std::cout << &a << "\n"; std::cout << "b " << b.connected() << "\n"; std::cout << "b1 " << b1.connected() << "\n"; } int main(){ MapEnvironment env(new Map(8,8)); env.SetFiveConnected(); Node::env=&env; //testErasers(); xyLoc s(1,1); xyLoc e(5,5); int sdepth(Node::env->HCost(s,e)); int agents(1); ICTSNode n(agents); GetMDD(s,e,n.mdd[0],sdepth); MDD mdd2; GetMDD(s,e,mdd2,sdepth+1); MDD mdd3; GetMDD(s,e,mdd3,sdepth+2); //std::cout << &dag[Node(s,sdepth).Hash()]; //std::cout << dag[Node(s,sdepth).Hash()].successors.size(); return 0; } <commit_msg>Conflict detection logic<commit_after>/* * $Id: sample.h,v 1.6 2006/09/18 06:23:39 nathanst Exp $ * * Driver.h * hog * * Created by Thayne Walker on 3/17/17. * Copyright 2017 Thayne Walker, University of Denver. All rights reserved. * * This file is part of HOG. * * HOG 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. * * HOG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HOG; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <memory> #include <iostream> #include <unordered_set> #include <unordered_map> #include "Map2DEnvironment.h" int maxDepth; struct Hashable{ virtual uint64_t Hash()const=0; }; struct NodePtrComp { bool operator()(const Hashable* lhs, const Hashable* rhs) const { return lhs->Hash()<rhs->Hash(); } }; namespace std { template <> struct hash<Hashable> { size_t operator()(Hashable* const & x) const noexcept { return x->Hash(); } }; } struct Node : public Hashable{ static MapEnvironment* env; Node(){} Node(xyLoc a, int d):n(a),depth(d),optimal(false){} xyLoc n; uint16_t depth; bool optimal; bool connected()const{return parents.size()+successors.size();} std::unordered_set<Node*> parents; std::unordered_set<Node*> successors; virtual uint64_t Hash()const{return (env->GetStateHash(n)<<16) | depth;} }; typedef std::vector<std::unordered_set<Node*>> MDD; typedef std::unordered_map<uint64_t,Node> DAG; std::ostream& operator << (std::ostream& ss, Node const& n){ ss << std::string(n.depth,' ')<<n.n; return ss; } std::ostream& operator << (std::ostream& ss, Node const* n){ ss << std::string(n->depth,' ')<<n->n << n->successors.size()<< "\n"; for(auto const m: n->successors) ss << m; return ss; } MapEnvironment* Node::env=nullptr; bool LimitedDFS(xyLoc const& start, xyLoc const& end, DAG& dag, MDD& mdd, int depth, int maxDepth){ //std::cout << start << " g:" << (maxDepth-depth) << " h:" << Node::env->HCost(start,end) << " f:" << ((maxDepth-depth)+Node::env->HCost(start,end)) << "\n"; if(depth<0 || (maxDepth-depth)+Node::env->HCost(start,end)>maxDepth){ // Note - this only works for a perfect heuristic. //std::cout << "pruned\n"; return false; } if(Node::env->GoalTest(end,start)){ Node n(start,depth); uint64_t hash(n.Hash()); dag[hash]=n; std::unordered_set<Node*>& s=mdd[maxDepth-(depth)]; s.insert(&dag[hash]); //std::cout << "found " << start << "\n"; return true; } std::vector<xyLoc> successors; Node::env->GetSuccessors(start,successors); bool result(false); for(auto const& node: successors){ if(LimitedDFS(node,end,dag,mdd,depth-1,maxDepth)){ Node n(start,depth); uint64_t hash(n.Hash()); if(dag.find(hash)==dag.end()){ dag[hash]=n; std::unordered_set<Node*>& s=mdd[maxDepth-(depth)]; s.insert(&dag[hash]); }else if(dag[hash].optimal){ return true; // Already found a solution from search at this depth } Node* parent(&dag[hash]); //std::cout << "found " << start << "\n"; std::unique_ptr<Node> c(new Node(node,depth-1)); Node* current(dag.find(c->Hash())==dag.end()?c.release():&dag[c->Hash()]); current->optimal = result = true; //std::cout << *parent << " parent of " << *current << "\n"; dag[current->Hash()].parents.insert(parent); //std::cout << *current << " child of " << *parent << "\n"; dag[parent->Hash()].successors.insert(current); } } return result; } void GetMDD(xyLoc const& start, xyLoc const& end, MDD& mdd, int depth){ // TODO: make this contain pointers or maybe combine into a structure with MDD. // as-is, memory will be deallocated when this function exits. DAG* dag=new DAG(); mdd.resize(depth+1); LimitedDFS(start,end,*dag,mdd,depth,depth); for(auto const& a: mdd){ for(auto const& n: a){ std::cout << *n; } std::cout << "\n"; } } void eraseDown(Node* n){ // If no parent points here, then we must disconnect this node if(n->parents.empty()){ // Erase children's parent pointers terminating at this node for(auto& m: n->successors){ auto p(m->parents.find(n)); if(p!=m->parents.end()){ m->parents.erase(p); } // recurse eraseDown(m); } n->successors.clear(); } } void eraseUp(Node* n){ // If this node has no successors, it cannot connect us to the goal if(n->successors.empty()){ // Erase parent's successor pointers terminating at this node for(auto& m: n->parents){ auto p(m->successors.find(n)); if(p!=m->successors.end()){ m->successors.erase(p); } // recurse eraseUp(m); } n->parents.clear(); } } void disconnect(Node* n){ // Erase edges pointing to parents, and their edges pointing at me. for(auto& m: n->parents){ auto p(m->successors.find(n)); if(p!=m->successors.end()){ m->successors.erase(p); } eraseUp(m); } n->parents.clear(); // Erase edges to/from successors for(auto& m: n->successors){ auto p(m->parents.find(n)); if(p!=m->parents.end()){ m->parents.erase(p); } // recurse eraseDown(m); } n->successors.clear(); } struct ICTSNode{ ICTSNode(int agents):mdd(agents){} std::vector<MDD> mdd; // Returns true and sets a1, a2 on conflict bool CheckConflicts(int& a1, int& a2){ std::vector<MDD> temp(mdd); // Check all pairs for(int i(0); i<temp.size(); ++i){ for(int j(i+1); j<temp.size(); ++j){ // Check all times for(int t(0); t<std::min(temp[i].size(),temp[j].size()); ++t){ // Check for node and edge conflicts for(auto const m: temp[i][t]){ if(!m->connected()) continue; // Can't get here for(auto const n: temp[j][t]){ if(!n->connected()) continue; // Can't get here if(m->Hash() == n->Hash()){ disconnect(m); disconnect(n); continue; } if(t!=0){ // Check edges for(auto mp(m->parents.begin()); mp!=m->parents.end();/*++mp*/){ bool conflict(false); for(auto np(n->parents.begin()); np!=n->parents.end();/*++np*/){ if((*mp)->n==n->n && (*np)->n==m->n){ // Same edge traversal // Remove edge // 1. Erase my pointer to parent n->parents.erase(np); // 2. Erase parent's pointer to me auto p((*np)->successors.find(n)); if(p!=(*np)->successors.end()){ (*np)->successors.erase(p); } eraseUp(*np); // If severed, propagate eraseDown(n); conflict=true; break; }else{ ++np; } } if(conflict){ m->parents.erase(mp); auto p((*mp)->successors.find(m)); if(p!=(*mp)->successors.end()){ (*mp)->successors.erase(p); } // recurse eraseUp(*mp); // If severed, propagate eraseDown(m); }else{ ++mp; } } } } } // Finally, check for severed connectivity by checking across this time slice. // If all nodes have no parents or children, then this ICTS node is rendered infeasible bool connected(false); for(auto const& m: temp[i][t]){ connected|=m->connected(); } if(!connected){ a1=i; a2=j; return false; } connected=false; for(auto const& n: temp[j][t]){ connected|=n->connected(); } if(!connected){ a1=i; a2=j; return false; } } } } a1=-1; a2=-1; return true; } }; void testErasers(){ Node a(xyLoc(1,1),1); Node b(xyLoc(2,1),2); Node c(xyLoc(3,1),2); Node d(xyLoc(4,1),2); Node b1(xyLoc(5,1),3); Node c1(xyLoc(6,1),3); Node d1(xyLoc(7,1),3); Node e(xyLoc(8,1),4); a.successors.insert(&b); a.successors.insert(&c); a.successors.insert(&d); b.parents.insert(&a); c.parents.insert(&a); d.parents.insert(&a); b.successors.insert(&b1); c.successors.insert(&c1); d.successors.insert(&d1); b1.parents.insert(&b); c1.parents.insert(&c); d1.parents.insert(&d); b1.successors.insert(&e); c1.successors.insert(&e); d1.successors.insert(&e); e.parents.insert(&b1); e.parents.insert(&c1); e.parents.insert(&d1); std::cout << &a << "\n"; // Disconnect b disconnect(&b); std::cout << &a << "\n"; std::cout << "b " << b.connected() << "\n"; std::cout << "b1 " << b1.connected() << "\n"; } int main(){ MapEnvironment env(new Map(8,8)); env.SetFiveConnected(); Node::env=&env; //testErasers(); xyLoc s1(1,1); xyLoc e1(1,4); xyLoc s2(1,4); xyLoc e2(3,1); int agents(2); ICTSNode n(agents); GetMDD(s1,e1,n.mdd[0],Node::env->HCost(s1,e1)); GetMDD(s2,e2,n.mdd[1],Node::env->HCost(s2,e2)); //std::cout << &(n.mdd[0][0]) << "\n"; //std::cout << &(n.mdd[1][0]) << "\n"; int a1(-1); int a2(-1); std::cout << "satisfiable=" << (n.CheckConflicts(a1,a2)?"true":"false") << "\n"; return 0; } <|endoftext|>
<commit_before>#include "kernel.h" #include "ilwisdata.h" #include "errorobject.h" #include "symboltable.h" #include "mastercatalog.h" #include "astnode.h" using namespace Ilwis; NodeValue::NodeValue() : _content(ctUNKNOW){ } NodeValue::NodeValue(const QVariant& v, ContentType tp) : _content(tp) { push_back(v); if ( tp == ctID) _ids.push_back(v.toString()); } NodeValue::NodeValue(const QVariant &v, const QString &nid, NodeValue::ContentType tp) : _content(tp) { push_back(v); _ids.push_back(nid); } NodeValue& NodeValue::operator=(const QVariant& a) { clear(); push_back(a); _content = ctUNKNOW; return *this; } NodeValue& NodeValue::operator=(const NodeValue& a) { clear(); _ids.clear(); for(auto var : a) push_back(var); _content = a._content; for(auto id : a._ids) _ids.push_back(id); return *this; } void NodeValue::setContentType(ContentType tp) { _content = tp; } NodeValue::ContentType NodeValue::content() const { return _content; } QString NodeValue::id(int index) const { if ( index < _ids.size()) return _ids[index]; return sUNDEF; } QString NodeValue::toString() const { if ( _content == ctMethod || _content == ctID){ QString res; for(auto var : _ids){ if ( res.size() != 0) res += ","; res += var; } return res; } QString res; for(auto var : *this){ if ( res.size() != 0) res += ","; res += var.toString(); } return res; } bool NodeValue::canConvert(int index, int targetTypeId) const { if ( index < size()) { return at(index).canConvert(targetTypeId); } return false; } qint64 NodeValue::toLongLong(int index, bool *ok) const { if ( index < size()) { return at(index).toLongLong(ok); } return i64UNDEF; } qint64 NodeValue::toBool(int index) const { if ( index < size()) { return at(index).toBool(); } return false; } double NodeValue::toDouble(int index, bool *ok) const { if ( index < size()) { return at(index).toDouble(ok); } return rUNDEF; } int NodeValue::toInt(int index, bool *ok) const { if ( index < size()) { return at(index).toInt(ok); } return iUNDEF; } QString NodeValue::toString(int index) const { if ( index < size()) { return at(index).toString(); } return sUNDEF; } QVariant NodeValue::value(int index) const { if ( index < size()) { return at(index); } return QVariant(); } //-------------------------------------------------------------- ASTNode::ASTNode() : _evaluated(false), _type("astnode") { } bool ASTNode::addChild(ASTNode *n) { _childeren.push_back(QSharedPointer<ASTNode>(n)); return true; } bool ASTNode::evaluate(SymbolTable& symbols, int scope, ExecutionContext* ctx) { foreach(QSharedPointer<ASTNode> node, _childeren) { if (!node->evaluate(symbols, scope, ctx)) { return false; } } return true; } NodeValue ASTNode::value() const { return _value; } bool ASTNode::isValid() const { return true; } int ASTNode::noOfChilderen() const { return _childeren.size(); } QSharedPointer<ASTNode> ASTNode::child(int i) const { if ( i < _childeren.size()) return _childeren[i]; return QSharedPointer<ASTNode>(); } QVariant ASTNode::resolveValue(int index, const NodeValue &val, SymbolTable &symbols) { if ( index>= val.size()) return QVariant(); QVariant var = val[index]; if ( val.content() == NodeValue::ctID) { Symbol sym = symbols.getSymbol(var.toString()); if(!sym.isValid()) { quint64 id = mastercatalog()->name2id(var.toString()); if ( id == i64UNDEF) throw ScriptError(QString(TR(ERR_ILLEGAL_VALUE_2)).arg("parameter").arg(var.toString())); } else{ QString tp = sym._var.typeName(); if ( tp == "QVariantList"){ QVariantList lst = sym._var.value<QVariantList>(); var = lst[0]; } else var = sym._var; } } return var; } <commit_msg>removed piece of unneeded code<commit_after>#include "kernel.h" #include "ilwisdata.h" #include "errorobject.h" #include "symboltable.h" #include "mastercatalog.h" #include "astnode.h" using namespace Ilwis; NodeValue::NodeValue() : _content(ctUNKNOW){ } NodeValue::NodeValue(const QVariant& v, ContentType tp) : _content(tp) { push_back(v); if ( tp == ctID) _ids.push_back(v.toString()); } NodeValue::NodeValue(const QVariant &v, const QString &nid, NodeValue::ContentType tp) : _content(tp) { push_back(v); _ids.push_back(nid); } NodeValue& NodeValue::operator=(const QVariant& a) { clear(); push_back(a); _content = ctUNKNOW; return *this; } NodeValue& NodeValue::operator=(const NodeValue& a) { clear(); _ids.clear(); for(auto var : a) push_back(var); _content = a._content; for(auto id : a._ids) _ids.push_back(id); return *this; } void NodeValue::setContentType(ContentType tp) { _content = tp; } NodeValue::ContentType NodeValue::content() const { return _content; } QString NodeValue::id(int index) const { if ( index < _ids.size()) return _ids[index]; return sUNDEF; } QString NodeValue::toString() const { if ( _content == ctMethod || _content == ctID){ QString res; for(auto var : _ids){ if ( res.size() != 0) res += ","; res += var; } return res; } QString res; for(auto var : *this){ if ( res.size() != 0) res += ","; res += var.toString(); } return res; } bool NodeValue::canConvert(int index, int targetTypeId) const { if ( index < size()) { return at(index).canConvert(targetTypeId); } return false; } qint64 NodeValue::toLongLong(int index, bool *ok) const { if ( index < size()) { return at(index).toLongLong(ok); } return i64UNDEF; } qint64 NodeValue::toBool(int index) const { if ( index < size()) { return at(index).toBool(); } return false; } double NodeValue::toDouble(int index, bool *ok) const { if ( index < size()) { return at(index).toDouble(ok); } return rUNDEF; } int NodeValue::toInt(int index, bool *ok) const { if ( index < size()) { return at(index).toInt(ok); } return iUNDEF; } QString NodeValue::toString(int index) const { if ( index < size()) { return at(index).toString(); } return sUNDEF; } QVariant NodeValue::value(int index) const { if ( index < size()) { return at(index); } return QVariant(); } //-------------------------------------------------------------- ASTNode::ASTNode() : _evaluated(false), _type("astnode") { } bool ASTNode::addChild(ASTNode *n) { _childeren.push_back(QSharedPointer<ASTNode>(n)); return true; } bool ASTNode::evaluate(SymbolTable& symbols, int scope, ExecutionContext* ctx) { foreach(QSharedPointer<ASTNode> node, _childeren) { if (!node->evaluate(symbols, scope, ctx)) { return false; } } return true; } NodeValue ASTNode::value() const { return _value; } bool ASTNode::isValid() const { return true; } int ASTNode::noOfChilderen() const { return _childeren.size(); } QSharedPointer<ASTNode> ASTNode::child(int i) const { if ( i < _childeren.size()) return _childeren[i]; return QSharedPointer<ASTNode>(); } QVariant ASTNode::resolveValue(int index, const NodeValue &val, SymbolTable &symbols) { if ( index>= val.size()) return QVariant(); QVariant var = val[index]; if ( val.content() == NodeValue::ctID) { Symbol sym = symbols.getSymbol(var.toString()); if(sym.isValid()) { QString tp = sym._var.typeName(); if ( tp == "QVariantList"){ QVariantList lst = sym._var.value<QVariantList>(); var = lst[0]; } else var = sym._var; } } return var; } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016-2019 Inviwo Foundation * 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. * *********************************************************************************/ #include <modules/brushingandlinking/ports/brushingandlinkingports.h> namespace inviwo { BrushingAndLinkingInport::BrushingAndLinkingInport(std::string identifier) : DataInport<BrushingAndLinkingManager>(identifier) { setOptional(true); onConnect([&]() { sendFilterEvent(filterCache_); sendSelectionEvent(selectionCache_); }); } void BrushingAndLinkingInport::sendFilterEvent(const std::unordered_set<size_t> &indices) { if (filterCache_.size() == 0 && indices.size() == 0) return; filterCache_ = indices; FilteringEvent event(this, filterCache_); getProcessor()->propagateEvent(&event, nullptr); } void BrushingAndLinkingInport::sendSelectionEvent(const std::unordered_set<size_t> &indices) { if (selectionCache_.size() == 0 && indices.size() == 0) return; selectionCache_ = indices; SelectionEvent event(this, selectionCache_); getProcessor()->propagateEvent(&event, nullptr); } void BrushingAndLinkingInport::sendColumnSelectionEvent(const std::unordered_set<size_t> &indices) { if (selectionColumnCache_.size() == 0 && indices.size() == 0) return; selectionColumnCache_ = indices; ColumnSelectionEvent event(this, selectionColumnCache_); getProcessor()->propagateEvent(&event, nullptr); } bool BrushingAndLinkingInport::isFiltered(size_t idx) const { if (isConnected()) { return getData()->isFiltered(idx); } else { return filterCache_.find(idx) != filterCache_.end(); } } bool BrushingAndLinkingInport::isSelected(size_t idx) const { if (isConnected()) { return getData()->isSelected(idx); } else { return selectionCache_.find(idx) != selectionCache_.end(); } } bool BrushingAndLinkingInport::isColumnSelected(size_t idx) const { if (isConnected()) { return getData()->isColumnSelected(idx); } else { return selectionColumnCache_.find(idx) != selectionColumnCache_.end(); } } const std::unordered_set<size_t> &BrushingAndLinkingInport::getSelectedIndices() const { if (isConnected()) { return getData()->getSelectedIndices(); } else { return selectionCache_; } } const std::unordered_set<size_t> &BrushingAndLinkingInport::getFilteredIndices() const { if (isConnected()) { return getData()->getFilteredIndices(); } else { return filterCache_; } } std::string BrushingAndLinkingInport::getClassIdentifier() const { return PortTraits<BrushingAndLinkingInport>::classIdentifier(); } BrushingAndLinkingOutport::BrushingAndLinkingOutport(std::string identifier) : DataOutport<BrushingAndLinkingManager>(identifier) {} std::string BrushingAndLinkingOutport::getClassIdentifier() const { return PortTraits<BrushingAndLinkingOutport>::classIdentifier(); } } // namespace inviwo <commit_msg>PlottingGL: A change in brushing suggested by Peter.<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016-2019 Inviwo Foundation * 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. * *********************************************************************************/ #include <modules/brushingandlinking/ports/brushingandlinkingports.h> namespace inviwo { BrushingAndLinkingInport::BrushingAndLinkingInport(std::string identifier) : DataInport<BrushingAndLinkingManager>(identifier) { setOptional(true); onConnect([&]() { sendFilterEvent(filterCache_); sendSelectionEvent(selectionCache_); }); } void BrushingAndLinkingInport::sendFilterEvent(const std::unordered_set<size_t> &indices) { if (filterCache_.size() == 0 && indices.size() == 0) return; filterCache_ = indices; FilteringEvent event(this, filterCache_); propagateEvent(&event, nullptr); } void BrushingAndLinkingInport::sendSelectionEvent(const std::unordered_set<size_t> &indices) { if (selectionCache_.size() == 0 && indices.size() == 0) return; selectionCache_ = indices; SelectionEvent event(this, selectionCache_); propagateEvent(&event, nullptr); } void BrushingAndLinkingInport::sendColumnSelectionEvent(const std::unordered_set<size_t> &indices) { if (selectionColumnCache_.size() == 0 && indices.size() == 0) return; selectionColumnCache_ = indices; ColumnSelectionEvent event(this, selectionColumnCache_); propagateEvent(&event, nullptr); } bool BrushingAndLinkingInport::isFiltered(size_t idx) const { if (isConnected()) { return getData()->isFiltered(idx); } else { return filterCache_.find(idx) != filterCache_.end(); } } bool BrushingAndLinkingInport::isSelected(size_t idx) const { if (isConnected()) { return getData()->isSelected(idx); } else { return selectionCache_.find(idx) != selectionCache_.end(); } } bool BrushingAndLinkingInport::isColumnSelected(size_t idx) const { if (isConnected()) { return getData()->isColumnSelected(idx); } else { return selectionColumnCache_.find(idx) != selectionColumnCache_.end(); } } const std::unordered_set<size_t> &BrushingAndLinkingInport::getSelectedIndices() const { if (isConnected()) { return getData()->getSelectedIndices(); } else { return selectionCache_; } } const std::unordered_set<size_t> &BrushingAndLinkingInport::getFilteredIndices() const { if (isConnected()) { return getData()->getFilteredIndices(); } else { return filterCache_; } } const std::unordered_set<size_t> &BrushingAndLinkingInport::getSelectedColumns() const { if (isConnected()) { return getData()->getSelectedColumns(); } else { return selectionColumnCache_; } } std::string BrushingAndLinkingInport::getClassIdentifier() const { return PortTraits<BrushingAndLinkingInport>::classIdentifier(); } BrushingAndLinkingOutport::BrushingAndLinkingOutport(std::string identifier) : DataOutport<BrushingAndLinkingManager>(identifier) {} std::string BrushingAndLinkingOutport::getClassIdentifier() const { return PortTraits<BrushingAndLinkingOutport>::classIdentifier(); } } // namespace inviwo <|endoftext|>
<commit_before>#include "transit/experimental/transit_types_experimental.hpp" #include <tuple> namespace transit { namespace experimental { std::string GetTranslation(Translations const & titles) { CHECK(!titles.empty(), ()); // If there is only one language we return title in this only translation. if (titles.size() == 1) return titles.begin()->second; // Otherwise we try to extract default language for this region. auto it = titles.find("default"); if (it != titles.end()) return it->second; // If there is no default language we return one of the represented translations. return titles.begin()->second; } // SingleMwmSegment -------------------------------------------------------------------------------- SingleMwmSegment::SingleMwmSegment(FeatureId featureId, uint32_t segmentIdx, bool forward) : m_featureId(featureId), m_segmentIdx(segmentIdx), m_forward(forward) { } // IdBundle ---------------------------------------------------------------------------------------- IdBundle::IdBundle(bool serializeFeatureIdOnly) : m_serializeFeatureIdOnly(serializeFeatureIdOnly) { } IdBundle::IdBundle(FeatureId featureId, OsmId osmId, bool serializeFeatureIdOnly) : m_featureId(featureId), m_osmId(osmId), m_serializeFeatureIdOnly(serializeFeatureIdOnly) { } bool IdBundle::operator<(IdBundle const & rhs) const { CHECK_EQUAL(m_serializeFeatureIdOnly, rhs.m_serializeFeatureIdOnly, ()); if (m_serializeFeatureIdOnly) return m_featureId < rhs.m_featureId; if (m_featureId != rhs.m_featureId) return m_featureId < rhs.m_featureId; return m_osmId < rhs.m_osmId; } bool IdBundle::operator==(IdBundle const & rhs) const { CHECK_EQUAL(m_serializeFeatureIdOnly, rhs.m_serializeFeatureIdOnly, ()); return m_serializeFeatureIdOnly ? m_featureId == rhs.m_featureId : m_featureId == rhs.m_featureId && m_osmId == rhs.m_osmId; } bool IdBundle::operator!=(IdBundle const & rhs) const { return !(*this == rhs); } bool IdBundle::IsValid() const { return m_serializeFeatureIdOnly ? m_featureId != kInvalidFeatureId : m_featureId != kInvalidFeatureId && m_osmId != kInvalidOsmId; } void IdBundle::SetOsmId(OsmId osmId) { m_osmId = osmId; } void IdBundle::SetFeatureId(FeatureId featureId) { m_featureId = featureId; } OsmId IdBundle::GetOsmId() const { return m_osmId; } FeatureId IdBundle::GetFeatureId() const { return m_featureId; } bool IdBundle::SerializeFeatureIdOnly() const { return m_serializeFeatureIdOnly; } // Network ----------------------------------------------------------------------------------------- Network::Network(TransitId id, Translations const & title) : m_id(id), m_title(title) {} Network::Network(TransitId id) : m_id(id), m_title{} {} bool Network::operator<(Network const & rhs) const { return m_id < rhs.m_id; } bool Network::operator==(Network const & rhs) const { return m_id == rhs.m_id; } bool Network::IsValid() const { return m_id != kInvalidTransitId; } TransitId Network::GetId() const { return m_id; } std::string const Network::GetTitle() const { return GetTranslation(m_title); } // Route ------------------------------------------------------------------------------------------- Route::Route(TransitId id, TransitId networkId, std::string const & routeType, Translations const & title, std::string const & color) : m_id(id), m_networkId(networkId), m_routeType(routeType), m_title(title), m_color(color) { } bool Route::operator<(Route const & rhs) const { return m_id < rhs.m_id; } bool Route::operator==(Route const & rhs) const { return m_id == rhs.m_id; } bool Route::IsValid() const { return m_id != kInvalidTransitId && m_networkId != kInvalidTransitId && !m_routeType.empty(); } TransitId Route::GetId() const { return m_id; } std::string const Route::GetTitle() const { return GetTranslation(m_title); } std::string const & Route::GetType() const { return m_routeType; } std::string const & Route::GetColor() const { return m_color; } TransitId Route::GetNetworkId() const { return m_networkId; } // Line -------------------------------------------------------------------------------------------- Line::Line(TransitId id, TransitId routeId, ShapeLink shapeLink, Translations const & title, Translations const & number, IdList stopIds, std::vector<LineInterval> const & intervals, osmoh::OpeningHours const & serviceDays) : m_id(id) , m_routeId(routeId) , m_shapeLink(shapeLink) , m_title(title) , m_number(number) , m_stopIds(stopIds) , m_intervals(intervals) , m_serviceDays(serviceDays) { } bool Line::operator<(Line const & rhs) const { return m_id < rhs.m_id; } bool Line::operator==(Line const & rhs) const { return m_id == rhs.m_id; } bool Line::IsValid() const { return m_id != kInvalidTransitId && m_routeId != kInvalidTransitId && m_shapeLink.m_shapeId != kInvalidTransitId && !m_stopIds.empty(); } TransitId Line::GetId() const { return m_id; } std::string Line::GetNumber() const { return GetTranslation(m_number); } std::string Line::GetTitle() const { return GetTranslation(m_title); } TransitId Line::GetRouteId() const { return m_routeId; } ShapeLink const & Line::GetShapeLink() const { return m_shapeLink; } IdList const & Line::GetStopIds() const { return m_stopIds; } std::vector<LineInterval> Line::GetIntervals() const { return m_intervals; } osmoh::OpeningHours Line::GetServiceDays() const { return m_serviceDays; } // Stop -------------------------------------------------------------------------------------------- Stop::Stop() : m_ids(true /* serializeFeatureIdOnly */) {} Stop::Stop(TransitId id, FeatureId featureId, OsmId osmId, Translations const & title, TimeTable const & timetable, m2::PointD const & point) : m_id(id) , m_ids(featureId, osmId, true /* serializeFeatureIdOnly */) , m_title(title) , m_timetable(timetable) , m_point(point) { } Stop::Stop(TransitId id) : m_id(id), m_ids(true /* serializeFeatureIdOnly */) {} bool Stop::operator<(Stop const & rhs) const { if (m_id != kInvalidTransitId || rhs.m_id != kInvalidTransitId) return m_id < rhs.m_id; return m_ids.GetFeatureId() < rhs.m_ids.GetFeatureId(); } bool Stop::operator==(Stop const & rhs) const { if (m_id != kInvalidTransitId || rhs.m_id != kInvalidTransitId) return m_id == rhs.m_id; return m_ids.GetFeatureId() == rhs.m_ids.GetFeatureId(); } bool Stop::IsValid() const { return ((m_id != kInvalidTransitId) || (m_ids.GetOsmId() != kInvalidOsmId)) && !m_timetable.empty() && !m_title.empty(); } FeatureId Stop::GetId() const { return m_id; } FeatureId Stop::GetFeatureId() const { return m_ids.GetFeatureId(); } OsmId Stop::GetOsmId() const { return m_ids.GetOsmId(); } std::string Stop::GetTitle() const { return GetTranslation(m_title); } TimeTable const & Stop::GetTimeTable() const { return m_timetable; } m2::PointD const & Stop::GetPoint() const { return m_point; } // Gate -------------------------------------------------------------------------------------------- Gate::Gate() : m_ids(false /* serializeFeatureIdOnly */) {} Gate::Gate(TransitId id, FeatureId featureId, OsmId osmId, bool entrance, bool exit, std::vector<TimeFromGateToStop> const & weights, m2::PointD const & point) : m_id(id) , m_ids(featureId, osmId, false /* serializeFeatureIdOnly */) , m_entrance(entrance) , m_exit(exit) , m_weights(weights) , m_point(point) { } bool Gate::operator<(Gate const & rhs) const { return std::tie(m_id, m_ids, m_entrance, m_exit) < std::tie(rhs.m_id, rhs.m_ids, rhs.m_entrance, rhs.m_exit); } bool Gate::operator==(Gate const & rhs) const { return std::tie(m_id, m_ids, m_entrance, m_exit) == std::tie(rhs.m_id, rhs.m_ids, rhs.m_entrance, rhs.m_exit); } bool Gate::IsValid() const { return ((m_id != kInvalidTransitId) || (m_ids.GetOsmId() != kInvalidOsmId)) && (m_entrance || m_exit) && !m_weights.empty(); } void Gate::SetBestPedestrianSegment(SingleMwmSegment const & s) { m_bestPedestrianSegment = s; }; FeatureId Gate::GetFeatureId() const { return m_ids.GetFeatureId(); } OsmId Gate::GetOsmId() const { return m_ids.GetOsmId(); } SingleMwmSegment const & Gate::GetBestPedestrianSegment() const { return m_bestPedestrianSegment; } bool Gate::IsEntrance() const { return m_entrance; } bool Gate::IsExit() const { return m_exit; } std::vector<TimeFromGateToStop> const & Gate::GetStopsWithWeight() const { return m_weights; } m2::PointD const & Gate::GetPoint() const { return m_point; } // Edge -------------------------------------------------------------------------------------------- Edge::Edge(TransitId stop1Id, TransitId stop2Id, EdgeWeight weight, TransitId lineId, bool transfer, ShapeLink const & shapeLink) : m_stop1Id(stop1Id) , m_stop2Id(stop2Id) , m_weight(weight) , m_isTransfer(transfer) , m_lineId(lineId) , m_shapeLink(shapeLink) { } bool Edge::operator<(Edge const & rhs) const { return std::tie(m_stop1Id, m_stop2Id, m_lineId) < std::tie(rhs.m_stop1Id, rhs.m_stop2Id, rhs.m_lineId); } bool Edge::operator==(Edge const & rhs) const { return std::tie(m_stop1Id, m_stop2Id, m_lineId) == std::tie(rhs.m_stop1Id, rhs.m_stop2Id, rhs.m_lineId); } bool Edge::operator!=(Edge const & rhs) const { return !(*this == rhs); } bool Edge::IsValid() const { if (m_isTransfer && (m_lineId != kInvalidTransitId || m_shapeLink.m_shapeId != kInvalidTransitId)) return false; if (!m_isTransfer && m_lineId == kInvalidTransitId) return false; return m_stop1Id != kInvalidTransitId && m_stop2Id != kInvalidTransitId; } void Edge::SetWeight(EdgeWeight weight) { m_weight = weight; } TransitId Edge::GetStop1Id() const { return m_stop1Id; } TransitId Edge::GetStop2Id() const { return m_stop2Id; } EdgeWeight Edge::GetWeight() const { return m_weight; } TransitId Edge::GetLineId() const { return m_lineId; } bool Edge::IsTransfer() const { return m_isTransfer; } ShapeLink const & Edge::GetShapeLink() const { return m_shapeLink; } // Transfer ---------------------------------------------------------------------------------------- Transfer::Transfer(TransitId id, m2::PointD const & point, IdList const & stopIds) : m_id(id), m_point(point), m_stopIds(stopIds) { } bool Transfer::operator<(Transfer const & rhs) const { return m_id < rhs.m_id; } bool Transfer::operator==(Transfer const & rhs) const { return m_id == rhs.m_id; } bool Transfer::IsValid() const { return m_id != kInvalidTransitId && m_stopIds.size() > 1; } TransitId Transfer::GetId() const { return m_id; } m2::PointD const & Transfer::GetPoint() const { return m_point; } IdList const & Transfer::GetStopIds() const { return m_stopIds; } // Shape ------------------------------------------------------------------------------------------- Shape::Shape(TransitId id, std::vector<m2::PointD> const & polyline) : m_id(id), m_polyline(polyline) { } bool Shape::operator<(Shape const & rhs) const { return m_id < rhs.m_id; } bool Shape::operator==(Shape const & rhs) const { return m_id == rhs.m_id; } bool Shape::IsValid() const { return m_id != kInvalidTransitId && m_polyline.size() > 1; } TransitId Shape::GetId() const { return m_id; } std::vector<m2::PointD> const & Shape::GetPolyline() const { return m_polyline; } } // namespace experimental } // namespace transit <commit_msg>m_timetable can be empty in stop<commit_after>#include "transit/experimental/transit_types_experimental.hpp" #include <tuple> namespace transit { namespace experimental { std::string GetTranslation(Translations const & titles) { CHECK(!titles.empty(), ()); // If there is only one language we return title in this only translation. if (titles.size() == 1) return titles.begin()->second; // Otherwise we try to extract default language for this region. auto it = titles.find("default"); if (it != titles.end()) return it->second; // If there is no default language we return one of the represented translations. return titles.begin()->second; } // SingleMwmSegment -------------------------------------------------------------------------------- SingleMwmSegment::SingleMwmSegment(FeatureId featureId, uint32_t segmentIdx, bool forward) : m_featureId(featureId), m_segmentIdx(segmentIdx), m_forward(forward) { } // IdBundle ---------------------------------------------------------------------------------------- IdBundle::IdBundle(bool serializeFeatureIdOnly) : m_serializeFeatureIdOnly(serializeFeatureIdOnly) { } IdBundle::IdBundle(FeatureId featureId, OsmId osmId, bool serializeFeatureIdOnly) : m_featureId(featureId), m_osmId(osmId), m_serializeFeatureIdOnly(serializeFeatureIdOnly) { } bool IdBundle::operator<(IdBundle const & rhs) const { CHECK_EQUAL(m_serializeFeatureIdOnly, rhs.m_serializeFeatureIdOnly, ()); if (m_serializeFeatureIdOnly) return m_featureId < rhs.m_featureId; return std::tie(m_featureId, m_osmId) < std::tie(rhs.m_featureId, rhs.m_osmId); } bool IdBundle::operator==(IdBundle const & rhs) const { CHECK_EQUAL(m_serializeFeatureIdOnly, rhs.m_serializeFeatureIdOnly, ()); return m_serializeFeatureIdOnly ? m_featureId == rhs.m_featureId : m_featureId == rhs.m_featureId && m_osmId == rhs.m_osmId; } bool IdBundle::operator!=(IdBundle const & rhs) const { return !(*this == rhs); } bool IdBundle::IsValid() const { return m_serializeFeatureIdOnly ? m_featureId != kInvalidFeatureId : m_featureId != kInvalidFeatureId && m_osmId != kInvalidOsmId; } void IdBundle::SetOsmId(OsmId osmId) { m_osmId = osmId; } void IdBundle::SetFeatureId(FeatureId featureId) { m_featureId = featureId; } OsmId IdBundle::GetOsmId() const { return m_osmId; } FeatureId IdBundle::GetFeatureId() const { return m_featureId; } bool IdBundle::SerializeFeatureIdOnly() const { return m_serializeFeatureIdOnly; } // Network ----------------------------------------------------------------------------------------- Network::Network(TransitId id, Translations const & title) : m_id(id), m_title(title) {} Network::Network(TransitId id) : m_id(id), m_title{} {} bool Network::operator<(Network const & rhs) const { return m_id < rhs.m_id; } bool Network::operator==(Network const & rhs) const { return m_id == rhs.m_id; } bool Network::IsValid() const { return m_id != kInvalidTransitId; } TransitId Network::GetId() const { return m_id; } std::string const Network::GetTitle() const { return GetTranslation(m_title); } // Route ------------------------------------------------------------------------------------------- Route::Route(TransitId id, TransitId networkId, std::string const & routeType, Translations const & title, std::string const & color) : m_id(id), m_networkId(networkId), m_routeType(routeType), m_title(title), m_color(color) { } bool Route::operator<(Route const & rhs) const { return m_id < rhs.m_id; } bool Route::operator==(Route const & rhs) const { return m_id == rhs.m_id; } bool Route::IsValid() const { return m_id != kInvalidTransitId && m_networkId != kInvalidTransitId && !m_routeType.empty(); } TransitId Route::GetId() const { return m_id; } std::string const Route::GetTitle() const { return GetTranslation(m_title); } std::string const & Route::GetType() const { return m_routeType; } std::string const & Route::GetColor() const { return m_color; } TransitId Route::GetNetworkId() const { return m_networkId; } // Line -------------------------------------------------------------------------------------------- Line::Line(TransitId id, TransitId routeId, ShapeLink shapeLink, Translations const & title, Translations const & number, IdList stopIds, std::vector<LineInterval> const & intervals, osmoh::OpeningHours const & serviceDays) : m_id(id) , m_routeId(routeId) , m_shapeLink(shapeLink) , m_title(title) , m_number(number) , m_stopIds(stopIds) , m_intervals(intervals) , m_serviceDays(serviceDays) { } bool Line::operator<(Line const & rhs) const { return m_id < rhs.m_id; } bool Line::operator==(Line const & rhs) const { return m_id == rhs.m_id; } bool Line::IsValid() const { return m_id != kInvalidTransitId && m_routeId != kInvalidTransitId && m_shapeLink.m_shapeId != kInvalidTransitId && !m_stopIds.empty(); } TransitId Line::GetId() const { return m_id; } std::string Line::GetNumber() const { return GetTranslation(m_number); } std::string Line::GetTitle() const { return GetTranslation(m_title); } TransitId Line::GetRouteId() const { return m_routeId; } ShapeLink const & Line::GetShapeLink() const { return m_shapeLink; } IdList const & Line::GetStopIds() const { return m_stopIds; } std::vector<LineInterval> Line::GetIntervals() const { return m_intervals; } osmoh::OpeningHours Line::GetServiceDays() const { return m_serviceDays; } // Stop -------------------------------------------------------------------------------------------- Stop::Stop() : m_ids(true /* serializeFeatureIdOnly */) {} Stop::Stop(TransitId id, FeatureId featureId, OsmId osmId, Translations const & title, TimeTable const & timetable, m2::PointD const & point) : m_id(id) , m_ids(featureId, osmId, true /* serializeFeatureIdOnly */) , m_title(title) , m_timetable(timetable) , m_point(point) { } Stop::Stop(TransitId id) : m_id(id), m_ids(true /* serializeFeatureIdOnly */) {} bool Stop::operator<(Stop const & rhs) const { if (m_id != kInvalidTransitId || rhs.m_id != kInvalidTransitId) return m_id < rhs.m_id; return m_ids.GetFeatureId() < rhs.m_ids.GetFeatureId(); } bool Stop::operator==(Stop const & rhs) const { if (m_id != kInvalidTransitId || rhs.m_id != kInvalidTransitId) return m_id == rhs.m_id; return m_ids.GetFeatureId() == rhs.m_ids.GetFeatureId(); } bool Stop::IsValid() const { return ((m_id != kInvalidTransitId) || (m_ids.GetOsmId() != kInvalidOsmId)) && !m_title.empty(); } FeatureId Stop::GetId() const { return m_id; } FeatureId Stop::GetFeatureId() const { return m_ids.GetFeatureId(); } OsmId Stop::GetOsmId() const { return m_ids.GetOsmId(); } std::string Stop::GetTitle() const { return GetTranslation(m_title); } TimeTable const & Stop::GetTimeTable() const { return m_timetable; } m2::PointD const & Stop::GetPoint() const { return m_point; } // Gate -------------------------------------------------------------------------------------------- Gate::Gate() : m_ids(false /* serializeFeatureIdOnly */) {} Gate::Gate(TransitId id, FeatureId featureId, OsmId osmId, bool entrance, bool exit, std::vector<TimeFromGateToStop> const & weights, m2::PointD const & point) : m_id(id) , m_ids(featureId, osmId, false /* serializeFeatureIdOnly */) , m_entrance(entrance) , m_exit(exit) , m_weights(weights) , m_point(point) { } bool Gate::operator<(Gate const & rhs) const { return std::tie(m_id, m_ids, m_entrance, m_exit) < std::tie(rhs.m_id, rhs.m_ids, rhs.m_entrance, rhs.m_exit); } bool Gate::operator==(Gate const & rhs) const { return std::tie(m_id, m_ids, m_entrance, m_exit) == std::tie(rhs.m_id, rhs.m_ids, rhs.m_entrance, rhs.m_exit); } bool Gate::IsValid() const { return ((m_id != kInvalidTransitId) || (m_ids.GetOsmId() != kInvalidOsmId)) && (m_entrance || m_exit) && !m_weights.empty(); } void Gate::SetBestPedestrianSegment(SingleMwmSegment const & s) { m_bestPedestrianSegment = s; }; FeatureId Gate::GetFeatureId() const { return m_ids.GetFeatureId(); } OsmId Gate::GetOsmId() const { return m_ids.GetOsmId(); } SingleMwmSegment const & Gate::GetBestPedestrianSegment() const { return m_bestPedestrianSegment; } bool Gate::IsEntrance() const { return m_entrance; } bool Gate::IsExit() const { return m_exit; } std::vector<TimeFromGateToStop> const & Gate::GetStopsWithWeight() const { return m_weights; } m2::PointD const & Gate::GetPoint() const { return m_point; } // Edge -------------------------------------------------------------------------------------------- Edge::Edge(TransitId stop1Id, TransitId stop2Id, EdgeWeight weight, TransitId lineId, bool transfer, ShapeLink const & shapeLink) : m_stop1Id(stop1Id) , m_stop2Id(stop2Id) , m_weight(weight) , m_isTransfer(transfer) , m_lineId(lineId) , m_shapeLink(shapeLink) { } bool Edge::operator<(Edge const & rhs) const { return std::tie(m_stop1Id, m_stop2Id, m_lineId) < std::tie(rhs.m_stop1Id, rhs.m_stop2Id, rhs.m_lineId); } bool Edge::operator==(Edge const & rhs) const { return std::tie(m_stop1Id, m_stop2Id, m_lineId) == std::tie(rhs.m_stop1Id, rhs.m_stop2Id, rhs.m_lineId); } bool Edge::operator!=(Edge const & rhs) const { return !(*this == rhs); } bool Edge::IsValid() const { if (m_isTransfer && (m_lineId != kInvalidTransitId || m_shapeLink.m_shapeId != kInvalidTransitId)) return false; if (!m_isTransfer && m_lineId == kInvalidTransitId) return false; return m_stop1Id != kInvalidTransitId && m_stop2Id != kInvalidTransitId; } void Edge::SetWeight(EdgeWeight weight) { m_weight = weight; } TransitId Edge::GetStop1Id() const { return m_stop1Id; } TransitId Edge::GetStop2Id() const { return m_stop2Id; } EdgeWeight Edge::GetWeight() const { return m_weight; } TransitId Edge::GetLineId() const { return m_lineId; } bool Edge::IsTransfer() const { return m_isTransfer; } ShapeLink const & Edge::GetShapeLink() const { return m_shapeLink; } // Transfer ---------------------------------------------------------------------------------------- Transfer::Transfer(TransitId id, m2::PointD const & point, IdList const & stopIds) : m_id(id), m_point(point), m_stopIds(stopIds) { } bool Transfer::operator<(Transfer const & rhs) const { return m_id < rhs.m_id; } bool Transfer::operator==(Transfer const & rhs) const { return m_id == rhs.m_id; } bool Transfer::IsValid() const { return m_id != kInvalidTransitId && m_stopIds.size() > 1; } TransitId Transfer::GetId() const { return m_id; } m2::PointD const & Transfer::GetPoint() const { return m_point; } IdList const & Transfer::GetStopIds() const { return m_stopIds; } // Shape ------------------------------------------------------------------------------------------- Shape::Shape(TransitId id, std::vector<m2::PointD> const & polyline) : m_id(id), m_polyline(polyline) { } bool Shape::operator<(Shape const & rhs) const { return m_id < rhs.m_id; } bool Shape::operator==(Shape const & rhs) const { return m_id == rhs.m_id; } bool Shape::IsValid() const { return m_id != kInvalidTransitId && m_polyline.size() > 1; } TransitId Shape::GetId() const { return m_id; } std::vector<m2::PointD> const & Shape::GetPolyline() const { return m_polyline; } } // namespace experimental } // namespace transit <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <string> #include <vector> #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "base/strings/utf_string_conversions.h" #include "native_mate/arguments.h" #include "native_mate/dictionary.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/gfx/image/image.h" #include "atom/common/node_includes.h" namespace { ui::ClipboardType GetClipboardType(mate::Arguments* args) { std::string type; if (args->GetNext(&type) && type == "selection") return ui::CLIPBOARD_TYPE_SELECTION; else return ui::CLIPBOARD_TYPE_COPY_PASTE; } std::vector<base::string16> AvailableFormats(mate::Arguments* args) { std::vector<base::string16> format_types; bool ignore; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore); return format_types; } bool Has(const std::string& format_string, mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); return clipboard->IsFormatAvailable(format, GetClipboardType(args)); } std::string Read(const std::string& format_string, mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); std::string data; clipboard->ReadData(format, &data); return data; } void Write(const mate::Dictionary& data, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); base::string16 text, html; gfx::Image image; if (data.Get("text", &text)) writer.WriteText(text); if (data.Get("rtf", &text)) { std::string rtf = base::UTF16ToUTF8(text); writer.WriteRTF(rtf); } if (data.Get("html", &html)) writer.WriteHTML(html, std::string()); if (data.Get("image", &image)) writer.WriteImage(image.AsBitmap()); } base::string16 ReadText(mate::Arguments* args) { base::string16 data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); auto type = GetClipboardType(args); if (clipboard->IsFormatAvailable( ui::Clipboard::GetPlainTextWFormatType(), type)) { clipboard->ReadText(type, &data); } else if (clipboard->IsFormatAvailable( ui::Clipboard::GetPlainTextFormatType(), type)) { std::string result; clipboard->ReadAsciiText(type, &result); data = base::ASCIIToUTF16(result); } return data; } void WriteText(const base::string16& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteText(text); } base::string16 ReadRtf(mate::Arguments* args) { std::string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadRTF(GetClipboardType(args), &data); return base::UTF8ToUTF16(data); } void WriteRtf(const std::string& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteRTF(text); } base::string16 ReadHtml(mate::Arguments* args) { base::string16 data; base::string16 html; std::string url; uint32_t start; uint32_t end; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end); data = html.substr(start, end - start); return data; } void WriteHtml(const base::string16& html, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteHTML(html, std::string()); } gfx::Image ReadImage(mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args)); return gfx::Image::CreateFrom1xBitmap(bitmap); } void WriteImage(const gfx::Image& image, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteImage(image.AsBitmap()); } void Clear(mate::Arguments* args) { ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args)); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("availableFormats", &AvailableFormats); dict.SetMethod("has", &Has); dict.SetMethod("read", &Read); dict.SetMethod("write", &Write); dict.SetMethod("readText", &ReadText); dict.SetMethod("writeText", &WriteText); dict.SetMethod("readRTF", &ReadRtf); dict.SetMethod("writeRTF", &WriteRtf); dict.SetMethod("readHTML", &ReadHtml); dict.SetMethod("writeHTML", &WriteHtml); dict.SetMethod("readImage", &ReadImage); dict.SetMethod("writeImage", &WriteImage); dict.SetMethod("clear", &Clear); // TODO Remove in 2.0, deprecate before then with warnings dict.SetMethod("readRtf", &ReadRtf); dict.SetMethod("writeRtf", &WriteRtf); dict.SetMethod("readHtml", &ReadHtml); dict.SetMethod("writeHtml", &WriteHtml); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_clipboard, Initialize) <commit_msg>Use correct TODO format<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <string> #include <vector> #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "base/strings/utf_string_conversions.h" #include "native_mate/arguments.h" #include "native_mate/dictionary.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/gfx/image/image.h" #include "atom/common/node_includes.h" namespace { ui::ClipboardType GetClipboardType(mate::Arguments* args) { std::string type; if (args->GetNext(&type) && type == "selection") return ui::CLIPBOARD_TYPE_SELECTION; else return ui::CLIPBOARD_TYPE_COPY_PASTE; } std::vector<base::string16> AvailableFormats(mate::Arguments* args) { std::vector<base::string16> format_types; bool ignore; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore); return format_types; } bool Has(const std::string& format_string, mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); return clipboard->IsFormatAvailable(format, GetClipboardType(args)); } std::string Read(const std::string& format_string, mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); std::string data; clipboard->ReadData(format, &data); return data; } void Write(const mate::Dictionary& data, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); base::string16 text, html; gfx::Image image; if (data.Get("text", &text)) writer.WriteText(text); if (data.Get("rtf", &text)) { std::string rtf = base::UTF16ToUTF8(text); writer.WriteRTF(rtf); } if (data.Get("html", &html)) writer.WriteHTML(html, std::string()); if (data.Get("image", &image)) writer.WriteImage(image.AsBitmap()); } base::string16 ReadText(mate::Arguments* args) { base::string16 data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); auto type = GetClipboardType(args); if (clipboard->IsFormatAvailable( ui::Clipboard::GetPlainTextWFormatType(), type)) { clipboard->ReadText(type, &data); } else if (clipboard->IsFormatAvailable( ui::Clipboard::GetPlainTextFormatType(), type)) { std::string result; clipboard->ReadAsciiText(type, &result); data = base::ASCIIToUTF16(result); } return data; } void WriteText(const base::string16& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteText(text); } base::string16 ReadRtf(mate::Arguments* args) { std::string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadRTF(GetClipboardType(args), &data); return base::UTF8ToUTF16(data); } void WriteRtf(const std::string& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteRTF(text); } base::string16 ReadHtml(mate::Arguments* args) { base::string16 data; base::string16 html; std::string url; uint32_t start; uint32_t end; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end); data = html.substr(start, end - start); return data; } void WriteHtml(const base::string16& html, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteHTML(html, std::string()); } gfx::Image ReadImage(mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args)); return gfx::Image::CreateFrom1xBitmap(bitmap); } void WriteImage(const gfx::Image& image, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteImage(image.AsBitmap()); } void Clear(mate::Arguments* args) { ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args)); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("availableFormats", &AvailableFormats); dict.SetMethod("has", &Has); dict.SetMethod("read", &Read); dict.SetMethod("write", &Write); dict.SetMethod("readText", &ReadText); dict.SetMethod("writeText", &WriteText); dict.SetMethod("readRTF", &ReadRtf); dict.SetMethod("writeRTF", &WriteRtf); dict.SetMethod("readHTML", &ReadHtml); dict.SetMethod("writeHTML", &WriteHtml); dict.SetMethod("readImage", &ReadImage); dict.SetMethod("writeImage", &WriteImage); dict.SetMethod("clear", &Clear); // TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings dict.SetMethod("readRtf", &ReadRtf); dict.SetMethod("writeRtf", &WriteRtf); dict.SetMethod("readHtml", &ReadHtml); dict.SetMethod("writeHtml", &WriteHtml); } } // namespace NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_clipboard, Initialize) <|endoftext|>
<commit_before>/// HEADER #include <csapex/signal/slot.h> /// COMPONENT #include <csapex/signal/event.h> #include <csapex/utility/assert.h> #include <csapex/msg/any_message.h> #include <csapex/msg/no_message.h> #include <csapex/model/connection.h> /// SYSTEM #include <iostream> using namespace csapex; Slot::Slot(std::function<void()> callback, const UUID &uuid, bool active) : Input(uuid), callback_([callback](const TokenConstPtr&){callback();}), active_(active), guard_(-1) { setType(connection_types::makeEmpty<connection_types::AnyMessage>()); } Slot::Slot(std::function<void(const TokenPtr&)> callback, const UUID &uuid, bool active) : Input(uuid), callback_(callback), active_(active), guard_(-1) { setType(connection_types::makeEmpty<connection_types::AnyMessage>()); } Slot::~Slot() { guard_ = 0xDEADBEEF; } void Slot::reset() { setSequenceNumber(0); } void Slot::disable() { Connectable::disable(); notifyMessageProcessed(); } void Slot::setToken(TokenPtr token) { apex_assert_hard(getType()->canConnectTo(token->getTokenData().get())); Input::setToken(token); token_set(token); apex_assert_hard(guard_ == -1); triggered(); } void Slot::notifyMessageAvailable(Connection* connection) { message_available(connection); std::unique_lock<std::recursive_mutex> lock(available_connections_mutex_); available_connections_.push_back(connection); if(!message_) { TokenPtr token = available_connections_.front()->readToken(); lock.unlock(); setToken(token); } } void Slot::notifyMessageProcessed() { messageProcessed(this); Connection* front = nullptr; { std::unique_lock<std::recursive_mutex> lock(available_connections_mutex_); if(!available_connections_.empty()) { front = available_connections_.front(); available_connections_.pop_front(); } } if(front) { front->setTokenProcessed(); } if(isEnabled() || isActive()) { std::unique_lock<std::recursive_mutex> lock(available_connections_mutex_); if(!available_connections_.empty()) { TokenPtr token = available_connections_.front()->readToken(); lock.unlock(); setToken(token); } } } void Slot::handleEvent() { apex_assert_hard(message_); // do the work if(isEnabled() || isActive()) { if(!std::dynamic_pointer_cast<connection_types::NoMessage const>(message_->getTokenData())) { apex_assert_hard(guard_ == -1); callback_(message_); } } message_.reset(); notifyMessageProcessed(); } bool Slot::isActive() const { return active_; } bool Slot::canConnectTo(Connectable* other_side, bool move) const { return Connectable::canConnectTo(other_side, move); } <commit_msg>minor<commit_after>/// HEADER #include <csapex/signal/slot.h> /// COMPONENT #include <csapex/signal/event.h> #include <csapex/utility/assert.h> #include <csapex/msg/any_message.h> #include <csapex/msg/no_message.h> #include <csapex/model/connection.h> /// SYSTEM #include <iostream> using namespace csapex; Slot::Slot(std::function<void()> callback, const UUID &uuid, bool active) : Input(uuid), callback_([callback](const TokenConstPtr&){callback();}), active_(active), guard_(-1) { setType(connection_types::makeEmpty<connection_types::AnyMessage>()); } Slot::Slot(std::function<void(const TokenPtr&)> callback, const UUID &uuid, bool active) : Input(uuid), callback_(callback), active_(active), guard_(-1) { setType(connection_types::makeEmpty<connection_types::AnyMessage>()); } Slot::~Slot() { guard_ = 0xDEADBEEF; } void Slot::reset() { setSequenceNumber(0); } void Slot::disable() { Connectable::disable(); notifyMessageProcessed(); } void Slot::setToken(TokenPtr token) { apex_assert_hard(getType()->canConnectTo(token->getTokenData().get())); Input::setToken(token); token_set(token); apex_assert_hard(guard_ == -1); triggered(); } void Slot::notifyMessageAvailable(Connection* connection) { message_available(connection); std::unique_lock<std::recursive_mutex> lock(available_connections_mutex_); available_connections_.push_back(connection); if(!message_) { TokenPtr token = available_connections_.front()->readToken(); lock.unlock(); setToken(token); } } void Slot::notifyMessageProcessed() { messageProcessed(this); Connection* front = nullptr; { std::unique_lock<std::recursive_mutex> lock(available_connections_mutex_); if(!available_connections_.empty()) { front = available_connections_.front(); available_connections_.pop_front(); } } if(front) { front->setTokenProcessed(); } if(isEnabled() || isActive()) { std::unique_lock<std::recursive_mutex> lock(available_connections_mutex_); if(!available_connections_.empty()) { TokenPtr token = available_connections_.front()->readToken(); lock.unlock(); setToken(token); } } } void Slot::handleEvent() { apex_assert_hard(message_); // do the work if(isEnabled() || isActive()) { if(!std::dynamic_pointer_cast<connection_types::NoMessage const>(message_->getTokenData())) { apex_assert_hard(guard_ == -1); try { callback_(message_); } catch(const std::exception& e) { std::cerr << "slot " << getUUID() << " has thrown an exception: " << e.what() << std::endl; } } } message_.reset(); notifyMessageProcessed(); } bool Slot::isActive() const { return active_; } bool Slot::canConnectTo(Connectable* other_side, bool move) const { return Connectable::canConnectTo(other_side, move); } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_api_clipboard.h" #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "base/strings/utf_string_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkPixmap.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "atom/common/node_includes.h" namespace atom { namespace api { ui::ClipboardType Clipboard::GetClipboardType(mate::Arguments* args) { std::string type; if (args->GetNext(&type) && type == "selection") return ui::CLIPBOARD_TYPE_SELECTION; else return ui::CLIPBOARD_TYPE_COPY_PASTE; } std::vector<base::string16> Clipboard::AvailableFormats(mate::Arguments* args) { std::vector<base::string16> format_types; bool ignore; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore); return format_types; } bool Clipboard::Has(const std::string& format_string, mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); return clipboard->IsFormatAvailable(format, GetClipboardType(args)); } std::string Clipboard::Read(const std::string& format_string) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string)); std::string data; clipboard->ReadData(format, &data); return data; } v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string, mate::Arguments* args) { std::string data = Read(format_string); return node::Buffer::Copy(args->isolate(), data.data(), data.length()) .ToLocalChecked(); } void Clipboard::WriteBuffer(const std::string& format, const v8::Local<v8::Value> buffer, mate::Arguments* args) { if (!node::Buffer::HasInstance(buffer)) { args->ThrowError("buffer must be a node Buffer"); return; } ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteData( ui::Clipboard::GetFormatType(format).Serialize(), std::string(node::Buffer::Data(buffer), node::Buffer::Length(buffer))); } void Clipboard::Write(const mate::Dictionary& data, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); base::string16 text, html, bookmark; gfx::Image image; if (data.Get("text", &text)) { writer.WriteText(text); if (data.Get("bookmark", &bookmark)) writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text)); } if (data.Get("rtf", &text)) { std::string rtf = base::UTF16ToUTF8(text); writer.WriteRTF(rtf); } if (data.Get("html", &html)) writer.WriteHTML(html, std::string()); if (data.Get("image", &image)) writer.WriteImage(image.AsBitmap()); } base::string16 Clipboard::ReadText(mate::Arguments* args) { base::string16 data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); auto type = GetClipboardType(args); if (clipboard->IsFormatAvailable(ui::Clipboard::GetPlainTextWFormatType(), type)) { clipboard->ReadText(type, &data); } else if (clipboard->IsFormatAvailable( ui::Clipboard::GetPlainTextFormatType(), type)) { std::string result; clipboard->ReadAsciiText(type, &result); data = base::ASCIIToUTF16(result); } return data; } void Clipboard::WriteText(const base::string16& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteText(text); } base::string16 Clipboard::ReadRTF(mate::Arguments* args) { std::string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadRTF(GetClipboardType(args), &data); return base::UTF8ToUTF16(data); } void Clipboard::WriteRTF(const std::string& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteRTF(text); } base::string16 Clipboard::ReadHTML(mate::Arguments* args) { base::string16 data; base::string16 html; std::string url; uint32_t start; uint32_t end; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end); data = html.substr(start, end - start); return data; } void Clipboard::WriteHTML(const base::string16& html, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteHTML(html, std::string()); } v8::Local<v8::Value> Clipboard::ReadBookmark(mate::Arguments* args) { base::string16 title; std::string url; mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate()); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadBookmark(&title, &url); dict.Set("title", title); dict.Set("url", url); return dict.GetHandle(); } void Clipboard::WriteBookmark(const base::string16& title, const std::string& url, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteBookmark(title, url); } gfx::Image Clipboard::ReadImage(mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args)); return gfx::Image::CreateFrom1xBitmap(bitmap); } void Clipboard::WriteImage(const gfx::Image& image, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); SkBitmap orig = image.AsBitmap(); SkBitmap bmp; if (bmp.tryAllocPixels(orig.info()) && orig.readPixels(bmp.info(), bmp.getPixels(), bmp.rowBytes(), 0, 0)) { writer.WriteImage(bmp); } } #if !defined(OS_MACOSX) void Clipboard::WriteFindText(const base::string16& text) {} base::string16 Clipboard::ReadFindText() { return base::string16(); } #endif void Clipboard::Clear(mate::Arguments* args) { ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args)); } } // namespace api } // namespace atom namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("availableFormats", &atom::api::Clipboard::AvailableFormats); dict.SetMethod("has", &atom::api::Clipboard::Has); dict.SetMethod("read", &atom::api::Clipboard::Read); dict.SetMethod("write", &atom::api::Clipboard::Write); dict.SetMethod("readText", &atom::api::Clipboard::ReadText); dict.SetMethod("writeText", &atom::api::Clipboard::WriteText); dict.SetMethod("readRTF", &atom::api::Clipboard::ReadRTF); dict.SetMethod("writeRTF", &atom::api::Clipboard::WriteRTF); dict.SetMethod("readHTML", &atom::api::Clipboard::ReadHTML); dict.SetMethod("writeHTML", &atom::api::Clipboard::WriteHTML); dict.SetMethod("readBookmark", &atom::api::Clipboard::ReadBookmark); dict.SetMethod("writeBookmark", &atom::api::Clipboard::WriteBookmark); dict.SetMethod("readImage", &atom::api::Clipboard::ReadImage); dict.SetMethod("writeImage", &atom::api::Clipboard::WriteImage); dict.SetMethod("readFindText", &atom::api::Clipboard::ReadFindText); dict.SetMethod("writeFindText", &atom::api::Clipboard::WriteFindText); dict.SetMethod("readBuffer", &atom::api::Clipboard::ReadBuffer); dict.SetMethod("writeBuffer", &atom::api::Clipboard::WriteBuffer); dict.SetMethod("clear", &atom::api::Clipboard::Clear); } } // namespace NODE_BUILTIN_MODULE_CONTEXT_AWARE(atom_common_clipboard, Initialize) <commit_msg>ui/base: move clipboard to own folder.<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_api_clipboard.h" #include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "base/strings/utf_string_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkPixmap.h" #include "ui/base/clipboard/clipboard_format_type.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "atom/common/node_includes.h" namespace atom { namespace api { ui::ClipboardType Clipboard::GetClipboardType(mate::Arguments* args) { std::string type; if (args->GetNext(&type) && type == "selection") return ui::CLIPBOARD_TYPE_SELECTION; else return ui::CLIPBOARD_TYPE_COPY_PASTE; } std::vector<base::string16> Clipboard::AvailableFormats(mate::Arguments* args) { std::vector<base::string16> format_types; bool ignore; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadAvailableTypes(GetClipboardType(args), &format_types, &ignore); return format_types; } bool Clipboard::Has(const std::string& format_string, mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::ClipboardFormatType format( ui::ClipboardFormatType::GetType(format_string)); return clipboard->IsFormatAvailable(format, GetClipboardType(args)); } std::string Clipboard::Read(const std::string& format_string) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::ClipboardFormatType format( ui::ClipboardFormatType::GetType(format_string)); std::string data; clipboard->ReadData(format, &data); return data; } v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string, mate::Arguments* args) { std::string data = Read(format_string); return node::Buffer::Copy(args->isolate(), data.data(), data.length()) .ToLocalChecked(); } void Clipboard::WriteBuffer(const std::string& format, const v8::Local<v8::Value> buffer, mate::Arguments* args) { if (!node::Buffer::HasInstance(buffer)) { args->ThrowError("buffer must be a node Buffer"); return; } ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteData( ui::ClipboardFormatType::GetType(format).Serialize(), std::string(node::Buffer::Data(buffer), node::Buffer::Length(buffer))); } void Clipboard::Write(const mate::Dictionary& data, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); base::string16 text, html, bookmark; gfx::Image image; if (data.Get("text", &text)) { writer.WriteText(text); if (data.Get("bookmark", &bookmark)) writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text)); } if (data.Get("rtf", &text)) { std::string rtf = base::UTF16ToUTF8(text); writer.WriteRTF(rtf); } if (data.Get("html", &html)) writer.WriteHTML(html, std::string()); if (data.Get("image", &image)) writer.WriteImage(image.AsBitmap()); } base::string16 Clipboard::ReadText(mate::Arguments* args) { base::string16 data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); auto type = GetClipboardType(args); if (clipboard->IsFormatAvailable(ui::ClipboardFormatType::GetPlainTextWType(), type)) { clipboard->ReadText(type, &data); } else if (clipboard->IsFormatAvailable( ui::ClipboardFormatType::GetPlainTextType(), type)) { std::string result; clipboard->ReadAsciiText(type, &result); data = base::ASCIIToUTF16(result); } return data; } void Clipboard::WriteText(const base::string16& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteText(text); } base::string16 Clipboard::ReadRTF(mate::Arguments* args) { std::string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadRTF(GetClipboardType(args), &data); return base::UTF8ToUTF16(data); } void Clipboard::WriteRTF(const std::string& text, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteRTF(text); } base::string16 Clipboard::ReadHTML(mate::Arguments* args) { base::string16 data; base::string16 html; std::string url; uint32_t start; uint32_t end; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadHTML(GetClipboardType(args), &html, &url, &start, &end); data = html.substr(start, end - start); return data; } void Clipboard::WriteHTML(const base::string16& html, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteHTML(html, std::string()); } v8::Local<v8::Value> Clipboard::ReadBookmark(mate::Arguments* args) { base::string16 title; std::string url; mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate()); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadBookmark(&title, &url); dict.Set("title", title); dict.Set("url", url); return dict.GetHandle(); } void Clipboard::WriteBookmark(const base::string16& title, const std::string& url, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); writer.WriteBookmark(title, url); } gfx::Image Clipboard::ReadImage(mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args)); return gfx::Image::CreateFrom1xBitmap(bitmap); } void Clipboard::WriteImage(const gfx::Image& image, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); SkBitmap orig = image.AsBitmap(); SkBitmap bmp; if (bmp.tryAllocPixels(orig.info()) && orig.readPixels(bmp.info(), bmp.getPixels(), bmp.rowBytes(), 0, 0)) { writer.WriteImage(bmp); } } #if !defined(OS_MACOSX) void Clipboard::WriteFindText(const base::string16& text) {} base::string16 Clipboard::ReadFindText() { return base::string16(); } #endif void Clipboard::Clear(mate::Arguments* args) { ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args)); } } // namespace api } // namespace atom namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("availableFormats", &atom::api::Clipboard::AvailableFormats); dict.SetMethod("has", &atom::api::Clipboard::Has); dict.SetMethod("read", &atom::api::Clipboard::Read); dict.SetMethod("write", &atom::api::Clipboard::Write); dict.SetMethod("readText", &atom::api::Clipboard::ReadText); dict.SetMethod("writeText", &atom::api::Clipboard::WriteText); dict.SetMethod("readRTF", &atom::api::Clipboard::ReadRTF); dict.SetMethod("writeRTF", &atom::api::Clipboard::WriteRTF); dict.SetMethod("readHTML", &atom::api::Clipboard::ReadHTML); dict.SetMethod("writeHTML", &atom::api::Clipboard::WriteHTML); dict.SetMethod("readBookmark", &atom::api::Clipboard::ReadBookmark); dict.SetMethod("writeBookmark", &atom::api::Clipboard::WriteBookmark); dict.SetMethod("readImage", &atom::api::Clipboard::ReadImage); dict.SetMethod("writeImage", &atom::api::Clipboard::WriteImage); dict.SetMethod("readFindText", &atom::api::Clipboard::ReadFindText); dict.SetMethod("writeFindText", &atom::api::Clipboard::WriteFindText); dict.SetMethod("readBuffer", &atom::api::Clipboard::ReadBuffer); dict.SetMethod("writeBuffer", &atom::api::Clipboard::WriteBuffer); dict.SetMethod("clear", &atom::api::Clipboard::Clear); } } // namespace NODE_BUILTIN_MODULE_CONTEXT_AWARE(atom_common_clipboard, Initialize) <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <typeindex> // class type_index // bool operator< (const type_index& rhs) const; // bool operator<=(const type_index& rhs) const; // bool operator> (const type_index& rhs) const; // bool operator>=(const type_index& rhs) const; #include <typeindex> #include <cassert> int main() { std::type_index t1 = typeid(int); std::type_index t2 = typeid(int); std::type_index t3 = typeid(long); assert(!(t1 < t2)); assert( (t1 <= t2)); assert(!(t1 > t2)); assert( (t1 >= t2)); assert(!(t1 < t3)); assert(!(t1 <= t3)); assert( (t1 > t3)); assert( (t1 >= t3)); } <commit_msg>Fixing up some ABI issues<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <typeindex> // class type_index // bool operator< (const type_index& rhs) const; // bool operator<=(const type_index& rhs) const; // bool operator> (const type_index& rhs) const; // bool operator>=(const type_index& rhs) const; #include <typeindex> #include <cassert> int main() { std::type_index t1 = typeid(int); std::type_index t2 = typeid(int); std::type_index t3 = typeid(long); assert(!(t1 < t2)); assert( (t1 <= t2)); assert(!(t1 > t2)); assert( (t1 >= t2)); if (t1 < t3) { assert( (t1 < t3)); assert( (t1 <= t3)); assert(!(t1 > t3)); assert(!(t1 >= t3)); } else { assert(!(t1 < t3)); assert(!(t1 <= t3)); assert( (t1 > t3)); assert( (t1 >= t3)); } } <|endoftext|>
<commit_before>#include "Crypto.h" #include "Elligator.h" namespace i2p { namespace crypto { Elligator2::Elligator2 () { // TODO: share with Ed22519 p = BN_new (); // 2^255-19 BN_set_bit (p, 255); // 2^255 BN_sub_word (p, 19); p38 = BN_dup (p); BN_add_word (p38, 3); BN_div_word (p38, 8); // (p+3)/8 p12 = BN_dup (p); BN_sub_word (p12, 1); BN_div_word (p12, 2); // (p-1)/2 p14 = BN_dup (p); BN_sub_word (p14, 1); BN_div_word (p14, 4); // (p-1)/4 auto A = BN_new (); BN_set_word (A, 486662); nA = BN_new (); BN_sub (nA, p, A); BN_CTX * ctx = BN_CTX_new (); // calculate sqrt(-1) sqrtn1 = BN_new (); BN_set_word (sqrtn1, 2); BN_mod_exp (sqrtn1, sqrtn1, p14, p, ctx); // 2^((p-1)/4 u = BN_new (); BN_set_word (u, 2); iu = BN_new (); BN_mod_inverse (iu, u, p, ctx); //printf ("%s\n", BN_bn2hex (iu)); BN_CTX_free (ctx); } Elligator2::~Elligator2 () { BN_free (p); BN_free (p38); BN_free (p12); BN_free (p14); BN_free (sqrtn1); BN_free (A); BN_free (nA); BN_free (u); BN_free (iu); } bool Elligator2::Encode (const uint8_t * key, uint8_t * encoded) const { bool ret = true; BN_CTX * ctx = BN_CTX_new (); BN_CTX_start (ctx); uint8_t key1[32]; for (size_t i = 0; i < 16; i++) // from Little Endian { key1[i] = key[15 - i]; key1[15 - i] = key[i]; } BIGNUM * x = BN_CTX_get (ctx); BN_bin2bn (key1, 32, x); BIGNUM * xA = BN_CTX_get (ctx); BN_add (xA, x, A); // x + A BN_sub (xA, p, xA); // p - (x + A) BIGNUM * uxxA = BN_CTX_get (ctx); // u*x*xA BN_mod_mul (uxxA, u, x, p, ctx); BN_mod_mul (uxxA, uxxA, xA, p, ctx); if (Legendre (uxxA, ctx) != -1) { BIGNUM * r = BN_CTX_get (ctx); BN_mod_inverse (r, xA, p, ctx); BN_mod_mul (r, r, x, p, ctx); BN_mod_mul (r, r, iu, p, ctx); SquareRoot (r, r, ctx); bn2buf (r, encoded, 32); for (size_t i = 0; i < 16; i++) // To Little Endian { uint8_t tmp = encoded[i]; encoded[i] = encoded[15 - i]; encoded[15 - i] = tmp; } } else ret = false; BN_CTX_end (ctx); BN_CTX_free (ctx); return ret; } bool Elligator2::Decode (const uint8_t * encoded, uint8_t * key) const { bool ret = true; BN_CTX * ctx = BN_CTX_new (); BN_CTX_start (ctx); uint8_t encoded1[32]; for (size_t i = 0; i < 16; i++) // from Little Endian { encoded1[i] = encoded[15 - i]; encoded1[15 - i] = encoded[i]; } BIGNUM * r = BN_CTX_get (ctx); BN_bin2bn (encoded1, 32, r); if (BN_cmp (r, p12) < 0) // r < (p-1)/2 { // v = -A/(1+u*r^2) BIGNUM * v = BN_CTX_get (ctx); BN_mod_sqr (v, r, p, ctx); BN_mod_mul (v, v, u, p, ctx); BN_add_word (v, 1); BN_mod_inverse (v, v, p, ctx); BN_mod_mul (v, v, nA, p, ctx); BIGNUM * vpA = BN_CTX_get (ctx); BN_add (vpA, v, A); // v + A // t = v^3+A*v^2+v = v^2*(v+A)+v BIGNUM * t = BN_CTX_get (ctx); BN_mod_sqr (t, v, p, ctx); BN_mod_mul (t, t, vpA, p, ctx); BN_mod_add (t, t, v, p, ctx); int legendre = Legendre (t, ctx); BIGNUM * x = BN_CTX_get (ctx); if (legendre == 1) BN_copy (x, v); else { BN_sub (x, p, v); BN_mod_sub (x, x, A, p, ctx); } bn2buf (x, key, 32); for (size_t i = 0; i < 16; i++) // To Little Endian { uint8_t tmp = key[i]; key[i] = key[15 - i]; key[15 - i] = tmp; } } else ret = false; BN_CTX_end (ctx); BN_CTX_free (ctx); return ret; } void Elligator2::SquareRoot (const BIGNUM * x, BIGNUM * r, BN_CTX * ctx) const { BIGNUM * t = BN_CTX_get (ctx); BN_mod_exp (t, x, p14, p, ctx); // t = x^((p-1)/4) BN_mod_exp (r, x, p38, p, ctx); // r = x^((p+3)/8) BN_add_word (t, 1); if (!BN_cmp (t, p)) BN_mod_mul (r, r, sqrtn1, p, ctx); if (BN_cmp (r, p12) > 0) // r > (p-1)/2 BN_sub (r, p, r); } int Elligator2::Legendre (const BIGNUM * a, BN_CTX * ctx) const { // assume a < p, so don't check for a % p = 0 BIGNUM * r = BN_CTX_get (ctx); BN_mod_exp (r, a, p12, p, ctx); // r = a^((p-1)/2) mod p if (BN_is_word(r, 1)) return 1; else if (BN_is_zero(r)) return 0; return -1; } static std::unique_ptr<Elligator2> g_Elligator; std::unique_ptr<Elligator2>& GetElligator () { if (!g_Elligator) { auto el = new Elligator2(); if (!g_Elligator) // make sure it was not created already g_Elligator.reset (el); else delete el; } return g_Elligator; } } } <commit_msg>check a for 0 in Legendre<commit_after>#include "Crypto.h" #include "Elligator.h" namespace i2p { namespace crypto { Elligator2::Elligator2 () { // TODO: share with Ed22519 p = BN_new (); // 2^255-19 BN_set_bit (p, 255); // 2^255 BN_sub_word (p, 19); p38 = BN_dup (p); BN_add_word (p38, 3); BN_div_word (p38, 8); // (p+3)/8 p12 = BN_dup (p); BN_sub_word (p12, 1); BN_div_word (p12, 2); // (p-1)/2 p14 = BN_dup (p); BN_sub_word (p14, 1); BN_div_word (p14, 4); // (p-1)/4 auto A = BN_new (); BN_set_word (A, 486662); nA = BN_new (); BN_sub (nA, p, A); BN_CTX * ctx = BN_CTX_new (); // calculate sqrt(-1) sqrtn1 = BN_new (); BN_set_word (sqrtn1, 2); BN_mod_exp (sqrtn1, sqrtn1, p14, p, ctx); // 2^((p-1)/4 u = BN_new (); BN_set_word (u, 2); iu = BN_new (); BN_mod_inverse (iu, u, p, ctx); //printf ("%s\n", BN_bn2hex (iu)); BN_CTX_free (ctx); } Elligator2::~Elligator2 () { BN_free (p); BN_free (p38); BN_free (p12); BN_free (p14); BN_free (sqrtn1); BN_free (A); BN_free (nA); BN_free (u); BN_free (iu); } bool Elligator2::Encode (const uint8_t * key, uint8_t * encoded) const { bool ret = true; BN_CTX * ctx = BN_CTX_new (); BN_CTX_start (ctx); uint8_t key1[32]; for (size_t i = 0; i < 16; i++) // from Little Endian { key1[i] = key[15 - i]; key1[15 - i] = key[i]; } BIGNUM * x = BN_CTX_get (ctx); BN_bin2bn (key1, 32, x); BIGNUM * xA = BN_CTX_get (ctx); BN_add (xA, x, A); // x + A BN_sub (xA, p, xA); // p - (x + A) BIGNUM * uxxA = BN_CTX_get (ctx); // u*x*xA BN_mod_mul (uxxA, u, x, p, ctx); BN_mod_mul (uxxA, uxxA, xA, p, ctx); if (Legendre (uxxA, ctx) != -1) { BIGNUM * r = BN_CTX_get (ctx); BN_mod_inverse (r, xA, p, ctx); BN_mod_mul (r, r, x, p, ctx); BN_mod_mul (r, r, iu, p, ctx); SquareRoot (r, r, ctx); bn2buf (r, encoded, 32); for (size_t i = 0; i < 16; i++) // To Little Endian { uint8_t tmp = encoded[i]; encoded[i] = encoded[15 - i]; encoded[15 - i] = tmp; } } else ret = false; BN_CTX_end (ctx); BN_CTX_free (ctx); return ret; } bool Elligator2::Decode (const uint8_t * encoded, uint8_t * key) const { bool ret = true; BN_CTX * ctx = BN_CTX_new (); BN_CTX_start (ctx); uint8_t encoded1[32]; for (size_t i = 0; i < 16; i++) // from Little Endian { encoded1[i] = encoded[15 - i]; encoded1[15 - i] = encoded[i]; } BIGNUM * r = BN_CTX_get (ctx); BN_bin2bn (encoded1, 32, r); if (BN_cmp (r, p12) < 0) // r < (p-1)/2 { // v = -A/(1+u*r^2) BIGNUM * v = BN_CTX_get (ctx); BN_mod_sqr (v, r, p, ctx); BN_mod_mul (v, v, u, p, ctx); BN_add_word (v, 1); BN_mod_inverse (v, v, p, ctx); BN_mod_mul (v, v, nA, p, ctx); BIGNUM * vpA = BN_CTX_get (ctx); BN_add (vpA, v, A); // v + A // t = v^3+A*v^2+v = v^2*(v+A)+v BIGNUM * t = BN_CTX_get (ctx); BN_mod_sqr (t, v, p, ctx); BN_mod_mul (t, t, vpA, p, ctx); BN_mod_add (t, t, v, p, ctx); int legendre = Legendre (t, ctx); BIGNUM * x = BN_CTX_get (ctx); if (legendre == 1) BN_copy (x, v); else { BN_sub (x, p, v); BN_mod_sub (x, x, A, p, ctx); } bn2buf (x, key, 32); for (size_t i = 0; i < 16; i++) // To Little Endian { uint8_t tmp = key[i]; key[i] = key[15 - i]; key[15 - i] = tmp; } } else ret = false; BN_CTX_end (ctx); BN_CTX_free (ctx); return ret; } void Elligator2::SquareRoot (const BIGNUM * x, BIGNUM * r, BN_CTX * ctx) const { BIGNUM * t = BN_CTX_get (ctx); BN_mod_exp (t, x, p14, p, ctx); // t = x^((p-1)/4) BN_mod_exp (r, x, p38, p, ctx); // r = x^((p+3)/8) BN_add_word (t, 1); if (!BN_cmp (t, p)) BN_mod_mul (r, r, sqrtn1, p, ctx); if (BN_cmp (r, p12) > 0) // r > (p-1)/2 BN_sub (r, p, r); } int Elligator2::Legendre (const BIGNUM * a, BN_CTX * ctx) const { // assume a < p, so don't check for a % p = 0, but a = 0 only if (BN_is_zero(a)) return 0; BIGNUM * r = BN_CTX_get (ctx); BN_mod_exp (r, a, p12, p, ctx); // r = a^((p-1)/2) mod p if (BN_is_word(r, 1)) return 1; else if (BN_is_zero(r)) return 0; return -1; } static std::unique_ptr<Elligator2> g_Elligator; std::unique_ptr<Elligator2>& GetElligator () { if (!g_Elligator) { auto el = new Elligator2(); if (!g_Elligator) // make sure it was not created already g_Elligator.reset (el); else delete el; } return g_Elligator; } } } <|endoftext|>
<commit_before>// Copyright 2017-2020 The Verible Authors. // // 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 "verilog/analysis/checkers/token_stream_lint_rule.h" #include <algorithm> #include <set> #include <string> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "common/analysis/citation.h" #include "common/analysis/lint_rule_status.h" #include "common/analysis/matcher/bound_symbol_manager.h" #include "common/analysis/matcher/matcher.h" #include "common/text/symbol.h" #include "common/text/syntax_tree_context.h" #include "verilog/CST/verilog_matchers.h" // IWYU pragma: keep #include "verilog/analysis/descriptions.h" #include "verilog/analysis/lint_rule_registry.h" namespace verilog { namespace analysis { using verible::GetStyleGuideCitation; using verible::LintRuleStatus; using verible::LintViolation; using verible::SyntaxTreeContext; using verible::matcher::Matcher; // Register TokenStreamLintRule VERILOG_REGISTER_LINT_RULE(TokenStreamLintRule); absl::string_view TokenStreamLintRule::Name() { return "forbid-line-continuations"; } const char TokenStreamLintRule::kTopic[] = "forbid-line-continuations"; const char TokenStreamLintRule::kMessage[] = "The lines can't be continued with \'\\\', use concatenation operator with " "braces"; std::string TokenStreamLintRule::GetDescription( DescriptionType description_type) { return absl::StrCat("Checks that there are no occurrences of ", Codify("\'\\\'", description_type), " when breaking the string literal line. ", "Use concatenation operator with braces instead. See ", GetStyleGuideCitation(kTopic), "."); } static const Matcher& StringLiteralMatcher() { static const Matcher matcher(StringLiteralKeyword()); return matcher; } void TokenStreamLintRule::HandleSymbol(const verible::Symbol& symbol, const SyntaxTreeContext& context) { verible::matcher::BoundSymbolManager manager; if (!StringLiteralMatcher().Matches(symbol, &manager)) { return; } const auto& string_node = SymbolCastToNode(symbol); const auto& node_children = string_node.children(); const auto& literal = std::find_if(node_children.begin(), node_children.end(), [](const verible::SymbolPtr& p) { return p.get()->Tag().tag == TK_StringLiteral; }); const auto& string_literal = SymbolCastToLeaf(*literal->get()); if (absl::StrContains(string_literal.get().text(), "\\\n")) { violations_.insert(LintViolation(string_literal, kMessage, context)); } } LintRuleStatus TokenStreamLintRule::Report() const { return LintRuleStatus(violations_, Name(), GetStyleGuideCitation(kTopic)); } } // namespace analysis } // namespace verilog <commit_msg>Avoid unnecessary get() on smartpointers.<commit_after>// Copyright 2017-2020 The Verible Authors. // // 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 "verilog/analysis/checkers/token_stream_lint_rule.h" #include <algorithm> #include <set> #include <string> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "common/analysis/citation.h" #include "common/analysis/lint_rule_status.h" #include "common/analysis/matcher/bound_symbol_manager.h" #include "common/analysis/matcher/matcher.h" #include "common/text/symbol.h" #include "common/text/syntax_tree_context.h" #include "verilog/CST/verilog_matchers.h" // IWYU pragma: keep #include "verilog/analysis/descriptions.h" #include "verilog/analysis/lint_rule_registry.h" namespace verilog { namespace analysis { using verible::GetStyleGuideCitation; using verible::LintRuleStatus; using verible::LintViolation; using verible::SyntaxTreeContext; using verible::matcher::Matcher; // Register TokenStreamLintRule VERILOG_REGISTER_LINT_RULE(TokenStreamLintRule); absl::string_view TokenStreamLintRule::Name() { return "forbid-line-continuations"; } const char TokenStreamLintRule::kTopic[] = "forbid-line-continuations"; const char TokenStreamLintRule::kMessage[] = "The lines can't be continued with \'\\\', use concatenation operator with " "braces"; std::string TokenStreamLintRule::GetDescription( DescriptionType description_type) { return absl::StrCat("Checks that there are no occurrences of ", Codify("\'\\\'", description_type), " when breaking the string literal line. ", "Use concatenation operator with braces instead. See ", GetStyleGuideCitation(kTopic), "."); } static const Matcher& StringLiteralMatcher() { static const Matcher matcher(StringLiteralKeyword()); return matcher; } void TokenStreamLintRule::HandleSymbol(const verible::Symbol& symbol, const SyntaxTreeContext& context) { verible::matcher::BoundSymbolManager manager; if (!StringLiteralMatcher().Matches(symbol, &manager)) { return; } const auto& string_node = SymbolCastToNode(symbol); const auto& node_children = string_node.children(); const auto& literal = std::find_if(node_children.begin(), node_children.end(), [](const verible::SymbolPtr& p) { return p->Tag().tag == TK_StringLiteral; }); const auto& string_literal = SymbolCastToLeaf(**literal); if (absl::StrContains(string_literal.get().text(), "\\\n")) { violations_.insert(LintViolation(string_literal, kMessage, context)); } } LintRuleStatus TokenStreamLintRule::Report() const { return LintRuleStatus(violations_, Name(), GetStyleGuideCitation(kTopic)); } } // namespace analysis } // namespace verilog <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include <date/date.h> #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/time.hpp" #include "vast/concept/printable/std/chrono.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/time.hpp" #define SUITE time #include "vast/test/test.hpp" using namespace vast; using namespace std::chrono; using namespace std::chrono_literals; using namespace date; namespace { template <class Input, class T> void check_timespan(const Input& str, T x) { timespan t; CHECK(parsers::timespan(str, t)); CHECK_EQUAL(t, duration_cast<timespan>(x)); } } // namespace <anonymous> TEST(positive durations) { MESSAGE("nanoseconds"); check_timespan("42 nsecs", 42ns); check_timespan("42nsec", 42ns); check_timespan("42ns", 42ns); check_timespan("42ns", 42ns); MESSAGE("microseconds"); MESSAGE("nanoseconds"); check_timespan("42 usecs", 42us); check_timespan("42usec", 42us); check_timespan("42us", 42us); MESSAGE("milliseconds"); check_timespan("42 msecs", 42ms); check_timespan("42msec", 42ms); check_timespan("42ms", 42ms); MESSAGE("seconds"); check_timespan("42 secs", 42s); check_timespan("42sec", 42s); check_timespan("42s", 42s); MESSAGE("minutes"); check_timespan("42 mins", 42min); check_timespan("42min", 42min); check_timespan("42m", 42min); MESSAGE("hours"); check_timespan("42 hours", 42h); check_timespan("42hour", 42h); check_timespan("42h", 42h); } TEST(negative durations) { check_timespan("-42ns", -42ns); check_timespan("-42h", -42h); } TEST(fractional durations) { check_timespan("3.54s", 3540ms); check_timespan("-42.001ms", -42001us); } TEST_DISABLED(compound durations) { check_timespan("3m42s10ms", 3min + 42s + 10ms); } TEST(ymdshms timestamp parser) { timestamp ts; MESSAGE("YYYY-MM-DD+HH:MM:SS.ssss"); CHECK(parsers::timestamp("2012-08-12+23:55:04.001234", ts)); auto sd = floor<days>(ts); auto t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{55}); CHECK(t.seconds() == seconds{4}); CHECK(duration_cast<microseconds>(t.subseconds()) == microseconds{1234}); MESSAGE("YYYY-MM-DD+HH:MM:SS"); CHECK(parsers::timestamp("2012-08-12+23:55:04", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{55}); CHECK(t.seconds() == seconds{4}); MESSAGE("YYYY-MM-DD+HH:MM"); CHECK(parsers::timestamp("2012-08-12+23:55", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{55}); CHECK(t.seconds() == seconds{0}); MESSAGE("YYYY-MM-DD+HH"); CHECK(parsers::timestamp("2012-08-12+23", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{0}); CHECK(t.seconds() == seconds{0}); MESSAGE("YYYY-MM-DD"); CHECK(parsers::timestamp("2012-08-12", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{0}); CHECK(t.minutes() == minutes{0}); CHECK(t.seconds() == seconds{0}); MESSAGE("YYYY-MM"); CHECK(parsers::timestamp("2012-08", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/1); CHECK(t.hours() == hours{0}); CHECK(t.minutes() == minutes{0}); CHECK(t.seconds() == seconds{0}); } TEST(unix epoch timestamp parser) { timestamp ts; CHECK(parsers::timestamp("@1444040673", ts)); CHECK(ts.time_since_epoch() == 1444040673s); CHECK(parsers::timestamp("@1398933902.686337", ts)); CHECK(ts.time_since_epoch() == double_seconds{1398933902.686337}); } TEST(now timestamp parser) { timestamp ts; CHECK(parsers::timestamp("now", ts)); CHECK(ts > timestamp::clock::now() - minutes{1}); CHECK(ts < timestamp::clock::now() + minutes{1}); CHECK(parsers::timestamp("now - 1m", ts)); CHECK(ts < timestamp::clock::now()); CHECK(parsers::timestamp("now + 1m", ts)); CHECK(ts > timestamp::clock::now()); } TEST(ago timestamp parser) { timestamp ts; CHECK(parsers::timestamp("10 days ago", ts)); CHECK(ts < timestamp::clock::now()); } TEST(in timestamp parser) { timestamp ts; CHECK(parsers::timestamp("in 1 year", ts)); CHECK(ts > timestamp::clock::now()); } <commit_msg>Remove stray unit test output<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include <date/date.h> #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/time.hpp" #include "vast/concept/printable/std/chrono.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/time.hpp" #define SUITE time #include "vast/test/test.hpp" using namespace vast; using namespace std::chrono; using namespace std::chrono_literals; using namespace date; namespace { template <class Input, class T> void check_timespan(const Input& str, T x) { timespan t; CHECK(parsers::timespan(str, t)); CHECK_EQUAL(t, duration_cast<timespan>(x)); } } // namespace <anonymous> TEST(positive durations) { MESSAGE("nanoseconds"); check_timespan("42 nsecs", 42ns); check_timespan("42nsec", 42ns); check_timespan("42ns", 42ns); check_timespan("42ns", 42ns); MESSAGE("microseconds"); check_timespan("42 usecs", 42us); check_timespan("42usec", 42us); check_timespan("42us", 42us); MESSAGE("milliseconds"); check_timespan("42 msecs", 42ms); check_timespan("42msec", 42ms); check_timespan("42ms", 42ms); MESSAGE("seconds"); check_timespan("42 secs", 42s); check_timespan("42sec", 42s); check_timespan("42s", 42s); MESSAGE("minutes"); check_timespan("42 mins", 42min); check_timespan("42min", 42min); check_timespan("42m", 42min); MESSAGE("hours"); check_timespan("42 hours", 42h); check_timespan("42hour", 42h); check_timespan("42h", 42h); } TEST(negative durations) { check_timespan("-42ns", -42ns); check_timespan("-42h", -42h); } TEST(fractional durations) { check_timespan("3.54s", 3540ms); check_timespan("-42.001ms", -42001us); } TEST_DISABLED(compound durations) { check_timespan("3m42s10ms", 3min + 42s + 10ms); } TEST(ymdshms timestamp parser) { timestamp ts; MESSAGE("YYYY-MM-DD+HH:MM:SS.ssss"); CHECK(parsers::timestamp("2012-08-12+23:55:04.001234", ts)); auto sd = floor<days>(ts); auto t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{55}); CHECK(t.seconds() == seconds{4}); CHECK(duration_cast<microseconds>(t.subseconds()) == microseconds{1234}); MESSAGE("YYYY-MM-DD+HH:MM:SS"); CHECK(parsers::timestamp("2012-08-12+23:55:04", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{55}); CHECK(t.seconds() == seconds{4}); MESSAGE("YYYY-MM-DD+HH:MM"); CHECK(parsers::timestamp("2012-08-12+23:55", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{55}); CHECK(t.seconds() == seconds{0}); MESSAGE("YYYY-MM-DD+HH"); CHECK(parsers::timestamp("2012-08-12+23", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{23}); CHECK(t.minutes() == minutes{0}); CHECK(t.seconds() == seconds{0}); MESSAGE("YYYY-MM-DD"); CHECK(parsers::timestamp("2012-08-12", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/12); CHECK(t.hours() == hours{0}); CHECK(t.minutes() == minutes{0}); CHECK(t.seconds() == seconds{0}); MESSAGE("YYYY-MM"); CHECK(parsers::timestamp("2012-08", ts)); sd = floor<days>(ts); t = make_time(ts - sd); CHECK(sd == 2012_y/8/1); CHECK(t.hours() == hours{0}); CHECK(t.minutes() == minutes{0}); CHECK(t.seconds() == seconds{0}); } TEST(unix epoch timestamp parser) { timestamp ts; CHECK(parsers::timestamp("@1444040673", ts)); CHECK(ts.time_since_epoch() == 1444040673s); CHECK(parsers::timestamp("@1398933902.686337", ts)); CHECK(ts.time_since_epoch() == double_seconds{1398933902.686337}); } TEST(now timestamp parser) { timestamp ts; CHECK(parsers::timestamp("now", ts)); CHECK(ts > timestamp::clock::now() - minutes{1}); CHECK(ts < timestamp::clock::now() + minutes{1}); CHECK(parsers::timestamp("now - 1m", ts)); CHECK(ts < timestamp::clock::now()); CHECK(parsers::timestamp("now + 1m", ts)); CHECK(ts > timestamp::clock::now()); } TEST(ago timestamp parser) { timestamp ts; CHECK(parsers::timestamp("10 days ago", ts)); CHECK(ts < timestamp::clock::now()); } TEST(in timestamp parser) { timestamp ts; CHECK(parsers::timestamp("in 1 year", ts)); CHECK(ts > timestamp::clock::now()); } <|endoftext|>
<commit_before>/** @file ***************************************************************************** Implementation of interfaces for a ppzkSNARK for the NP statement "Pour". See zerocash_pour_ppzksnark.hpp . ***************************************************************************** * @author This file is part of libzerocash, developed by the Zerocash * project and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef ZEROCASH_POUR_PPZKSNARK_TCC_ #define ZEROCASH_POUR_PPZKSNARK_TCC_ #include "zerocash_pour_ppzksnark/zerocash_pour_gadget.hpp" #include "common/profiling.hpp" namespace libzerocash { template<typename ppzksnark_ppT> bool zerocash_pour_proving_key<ppzksnark_ppT>::operator==(const zerocash_pour_proving_key<ppzksnark_ppT> &other) const { return (this->num_old_coins == other.num_old_coins && this->num_new_coins == other.num_new_coins && this->tree_depth == other.tree_depth && this->r1cs_pk == other.r1cs_pk); } template<typename ppzksnark_ppT> std::ostream& operator<<(std::ostream &out, const zerocash_pour_proving_key<ppzksnark_ppT> &pk) { out << pk.num_old_coins << "\n"; out << pk.num_new_coins << "\n"; out << pk.tree_depth << "\n"; out << pk.r1cs_pk; return out; } template<typename ppzksnark_ppT> std::istream& operator>>(std::istream &in, zerocash_pour_proving_key<ppzksnark_ppT> &pk) { in >> pk.num_old_coins; consume_newline(in); in >> pk.num_new_coins; consume_newline(in); in >> pk.tree_depth; consume_newline(in); in >> pk.r1cs_pk; return in; } template<typename ppzksnark_ppT> bool zerocash_pour_verification_key<ppzksnark_ppT>::operator==(const zerocash_pour_verification_key<ppzksnark_ppT> &other) const { return (this->num_old_coins == other.num_old_coins && this->num_new_coins == other.num_new_coins && this->r1cs_vk == other.r1cs_vk); } template<typename ppzksnark_ppT> std::ostream& operator<<(std::ostream &out, const zerocash_pour_verification_key<ppzksnark_ppT> &vk) { out << vk.num_old_coins << "\n"; out << vk.num_new_coins << "\n"; out << vk.r1cs_vk; return out; } template<typename ppzksnark_ppT> std::istream& operator>>(std::istream &in, zerocash_pour_verification_key<ppzksnark_ppT> &vk) { in >> vk.num_old_coins; consume_newline(in); in >> vk.num_new_coins; consume_newline(in); in >> vk.r1cs_vk; return in; } template<typename ppzksnark_ppT> bool zerocash_pour_keypair<ppzksnark_ppT>::operator==(const zerocash_pour_keypair<ppzksnark_ppT> &other) const { return (this->pk == other.pk && this->vk == other.vk); } template<typename ppzksnark_ppT> std::ostream& operator<<(std::ostream &out, const zerocash_pour_keypair<ppzksnark_ppT> &kp) { out << kp.pk; out << kp.vk; return out; } template<typename ppzksnark_ppT> std::istream& operator>>(std::istream &in, zerocash_pour_keypair<ppzksnark_ppT> &kp) { in >> kp.pk; in >> kp.vk; return in; } template<typename ppzksnark_ppT> zerocash_pour_keypair<ppzksnark_ppT> zerocash_pour_ppzksnark_generator(const size_t num_old_coins, const size_t num_new_coins, const size_t tree_depth) { typedef Fr<ppzksnark_ppT> FieldT; enter_block("Call to zerocash_pour_ppzksnark_generator"); protoboard<FieldT> pb; zerocash_pour_gadget<FieldT> g(pb, num_old_coins, num_new_coins, tree_depth, "zerocash_pour"); g.generate_r1cs_constraints(); const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system(); r1cs_ppzksnark_keypair<ppzksnark_ppT> ppzksnark_keypair = r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system); leave_block("Call to zerocash_pour_ppzksnark_generator"); zerocash_pour_proving_key<ppzksnark_ppT> zerocash_pour_pk(num_old_coins, num_new_coins, tree_depth, std::move(ppzksnark_keypair.pk)); zerocash_pour_verification_key<ppzksnark_ppT> zerocash_pour_vk(num_old_coins, num_new_coins, std::move(ppzksnark_keypair.vk)); return zerocash_pour_keypair<ppzksnark_ppT>(std::move(zerocash_pour_pk), std::move(zerocash_pour_vk)); } template<typename ppzksnark_ppT> zerocash_pour_proof<ppzksnark_ppT> zerocash_pour_ppzksnark_prover(const zerocash_pour_proving_key<ppzksnark_ppT> &pk, const std::vector<merkle_authentication_path> &old_coin_authentication_paths, const std::vector<size_t> &old_coin_merkle_tree_positions, const bit_vector &merkle_tree_root, const std::vector<bit_vector> &new_address_public_keys, const std::vector<bit_vector> &old_address_secret_keys, const std::vector<bit_vector> &new_address_commitment_nonces, const std::vector<bit_vector> &old_address_commitment_nonces, const std::vector<bit_vector> &new_coin_serial_number_nonces, const std::vector<bit_vector> &old_coin_serial_number_nonces, const std::vector<bit_vector> &new_coin_values, const bit_vector &public_value, const std::vector<bit_vector> &old_coin_values, const bit_vector &signature_public_key_hash) { typedef Fr<ppzksnark_ppT> FieldT; enter_block("Call to zerocash_pour_ppzksnark_prover"); protoboard<FieldT> pb; zerocash_pour_gadget<FieldT > g(pb, pk.num_old_coins, pk.num_new_coins, pk.tree_depth, "zerocash_pour"); g.generate_r1cs_constraints(); g.generate_r1cs_witness(old_coin_authentication_paths, old_coin_merkle_tree_positions, merkle_tree_root, new_address_public_keys, old_address_secret_keys, new_address_commitment_nonces, old_address_commitment_nonces, new_coin_serial_number_nonces, old_coin_serial_number_nonces, new_coin_values, public_value, old_coin_values, signature_public_key_hash); assert(pb.is_satisfied()); zerocash_pour_proof<ppzksnark_ppT> proof = r1cs_ppzksnark_prover<ppzksnark_ppT>(pk.r1cs_pk, pb.primary_input(), pb.auxiliary_input()); leave_block("Call to zerocash_pour_ppzksnark_prover"); return proof; } template<typename ppzksnark_ppT> bool zerocash_pour_ppzksnark_verifier(const zerocash_pour_verification_key<ppzksnark_ppT> &vk, const bit_vector &merkle_tree_root, const std::vector<bit_vector> &old_coin_serial_numbers, const std::vector<bit_vector> &new_coin_commitments, const bit_vector &public_value, const bit_vector &signature_public_key_hash, const std::vector<bit_vector> &signature_public_key_hash_macs, const zerocash_pour_proof<ppzksnark_ppT> &proof) { typedef Fr<ppzksnark_ppT> FieldT; enter_block("Call to zerocash_pour_ppzksnark_verifier"); const r1cs_primary_input<FieldT> input = zerocash_pour_input_map<FieldT>(vk.num_old_coins, vk.num_new_coins, merkle_tree_root, old_coin_serial_numbers, new_coin_commitments, public_value, signature_public_key_hash, signature_public_key_hash_macs); const bool ans = r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(vk.r1cs_vk, input, proof); leave_block("Call to zerocash_pour_ppzksnark_verifier"); return ans; } } // libzerocash #endif // ZEROCASH_POUR_PPZKSNARK_TCC_ <commit_msg>zerocash_pour_ppzksnark: reduce memory consumption, and more profiling<commit_after>/** @file ***************************************************************************** Implementation of interfaces for a ppzkSNARK for the NP statement "Pour". See zerocash_pour_ppzksnark.hpp . ***************************************************************************** * @author This file is part of libzerocash, developed by the Zerocash * project and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef ZEROCASH_POUR_PPZKSNARK_TCC_ #define ZEROCASH_POUR_PPZKSNARK_TCC_ #include "zerocash_pour_ppzksnark/zerocash_pour_gadget.hpp" #include "common/profiling.hpp" namespace libzerocash { template<typename ppzksnark_ppT> bool zerocash_pour_proving_key<ppzksnark_ppT>::operator==(const zerocash_pour_proving_key<ppzksnark_ppT> &other) const { return (this->num_old_coins == other.num_old_coins && this->num_new_coins == other.num_new_coins && this->tree_depth == other.tree_depth && this->r1cs_pk == other.r1cs_pk); } template<typename ppzksnark_ppT> std::ostream& operator<<(std::ostream &out, const zerocash_pour_proving_key<ppzksnark_ppT> &pk) { out << pk.num_old_coins << "\n"; out << pk.num_new_coins << "\n"; out << pk.tree_depth << "\n"; out << pk.r1cs_pk; return out; } template<typename ppzksnark_ppT> std::istream& operator>>(std::istream &in, zerocash_pour_proving_key<ppzksnark_ppT> &pk) { in >> pk.num_old_coins; consume_newline(in); in >> pk.num_new_coins; consume_newline(in); in >> pk.tree_depth; consume_newline(in); in >> pk.r1cs_pk; return in; } template<typename ppzksnark_ppT> bool zerocash_pour_verification_key<ppzksnark_ppT>::operator==(const zerocash_pour_verification_key<ppzksnark_ppT> &other) const { return (this->num_old_coins == other.num_old_coins && this->num_new_coins == other.num_new_coins && this->r1cs_vk == other.r1cs_vk); } template<typename ppzksnark_ppT> std::ostream& operator<<(std::ostream &out, const zerocash_pour_verification_key<ppzksnark_ppT> &vk) { out << vk.num_old_coins << "\n"; out << vk.num_new_coins << "\n"; out << vk.r1cs_vk; return out; } template<typename ppzksnark_ppT> std::istream& operator>>(std::istream &in, zerocash_pour_verification_key<ppzksnark_ppT> &vk) { in >> vk.num_old_coins; consume_newline(in); in >> vk.num_new_coins; consume_newline(in); in >> vk.r1cs_vk; return in; } template<typename ppzksnark_ppT> bool zerocash_pour_keypair<ppzksnark_ppT>::operator==(const zerocash_pour_keypair<ppzksnark_ppT> &other) const { return (this->pk == other.pk && this->vk == other.vk); } template<typename ppzksnark_ppT> std::ostream& operator<<(std::ostream &out, const zerocash_pour_keypair<ppzksnark_ppT> &kp) { out << kp.pk; out << kp.vk; return out; } template<typename ppzksnark_ppT> std::istream& operator>>(std::istream &in, zerocash_pour_keypair<ppzksnark_ppT> &kp) { in >> kp.pk; in >> kp.vk; return in; } template<typename ppzksnark_ppT> zerocash_pour_keypair<ppzksnark_ppT> zerocash_pour_ppzksnark_generator(const size_t num_old_coins, const size_t num_new_coins, const size_t tree_depth) { typedef Fr<ppzksnark_ppT> FieldT; enter_block("Call to zerocash_pour_ppzksnark_generator"); r1cs_constraint_system<FieldT> constraint_system; { enter_block("Generating Pour constraint system"); protoboard<FieldT> pb; print_indent(); print_mem("before constructing the Pour gadget"); zerocash_pour_gadget<FieldT> g(pb, num_old_coins, num_new_coins, tree_depth, "zerocash_pour"); print_indent(); print_mem("after constructing the Pour gadget"); g.generate_r1cs_constraints(); print_indent(); print_mem("after generating the Pour constraints"); constraint_system = pb.get_constraint_system(); // and now we can forget the pb and gadget print_indent(); print_mem("after converting to R1CS"); leave_block("Generating Pour constraint system"); } r1cs_ppzksnark_keypair<ppzksnark_ppT> ppzksnark_keypair = r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system); zerocash_pour_proving_key<ppzksnark_ppT> zerocash_pour_pk(num_old_coins, num_new_coins, tree_depth, std::move(ppzksnark_keypair.pk)); zerocash_pour_verification_key<ppzksnark_ppT> zerocash_pour_vk(num_old_coins, num_new_coins, std::move(ppzksnark_keypair.vk)); leave_block("Call to zerocash_pour_ppzksnark_generator"); return zerocash_pour_keypair<ppzksnark_ppT>(std::move(zerocash_pour_pk), std::move(zerocash_pour_vk)); } template<typename ppzksnark_ppT> zerocash_pour_proof<ppzksnark_ppT> zerocash_pour_ppzksnark_prover(const zerocash_pour_proving_key<ppzksnark_ppT> &pk, const std::vector<merkle_authentication_path> &old_coin_authentication_paths, const std::vector<size_t> &old_coin_merkle_tree_positions, const bit_vector &merkle_tree_root, const std::vector<bit_vector> &new_address_public_keys, const std::vector<bit_vector> &old_address_secret_keys, const std::vector<bit_vector> &new_address_commitment_nonces, const std::vector<bit_vector> &old_address_commitment_nonces, const std::vector<bit_vector> &new_coin_serial_number_nonces, const std::vector<bit_vector> &old_coin_serial_number_nonces, const std::vector<bit_vector> &new_coin_values, const bit_vector &public_value, const std::vector<bit_vector> &old_coin_values, const bit_vector &signature_public_key_hash) { typedef Fr<ppzksnark_ppT> FieldT; enter_block("Call to zerocash_pour_ppzksnark_prover"); protoboard<FieldT> pb; zerocash_pour_gadget<FieldT > g(pb, pk.num_old_coins, pk.num_new_coins, pk.tree_depth, "zerocash_pour"); g.generate_r1cs_constraints(); g.generate_r1cs_witness(old_coin_authentication_paths, old_coin_merkle_tree_positions, merkle_tree_root, new_address_public_keys, old_address_secret_keys, new_address_commitment_nonces, old_address_commitment_nonces, new_coin_serial_number_nonces, old_coin_serial_number_nonces, new_coin_values, public_value, old_coin_values, signature_public_key_hash); assert(pb.is_satisfied()); zerocash_pour_proof<ppzksnark_ppT> proof = r1cs_ppzksnark_prover<ppzksnark_ppT>(pk.r1cs_pk, pb.primary_input(), pb.auxiliary_input()); leave_block("Call to zerocash_pour_ppzksnark_prover"); return proof; } template<typename ppzksnark_ppT> bool zerocash_pour_ppzksnark_verifier(const zerocash_pour_verification_key<ppzksnark_ppT> &vk, const bit_vector &merkle_tree_root, const std::vector<bit_vector> &old_coin_serial_numbers, const std::vector<bit_vector> &new_coin_commitments, const bit_vector &public_value, const bit_vector &signature_public_key_hash, const std::vector<bit_vector> &signature_public_key_hash_macs, const zerocash_pour_proof<ppzksnark_ppT> &proof) { typedef Fr<ppzksnark_ppT> FieldT; enter_block("Call to zerocash_pour_ppzksnark_verifier"); const r1cs_primary_input<FieldT> input = zerocash_pour_input_map<FieldT>(vk.num_old_coins, vk.num_new_coins, merkle_tree_root, old_coin_serial_numbers, new_coin_commitments, public_value, signature_public_key_hash, signature_public_key_hash_macs); const bool ans = r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(vk.r1cs_vk, input, proof); leave_block("Call to zerocash_pour_ppzksnark_verifier"); return ans; } } // libzerocash #endif // ZEROCASH_POUR_PPZKSNARK_TCC_ <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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. */ // // Created by sancar koyunlu on 5/3/13. #include "hazelcast/util/Util.h" #include "hazelcast/util/TimeUtil.h" #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <string.h> #include <algorithm> #include <stdio.h> #include <stdarg.h> #include <stdint.h> #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #define WIN32_LEAN_AND_MEAN #include <Windows.h> #else #include <sys/time.h> #include <unistd.h> #include <pthread.h> #endif namespace hazelcast { namespace util { int64_t getCurrentThreadId() { #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) return (int64_t) GetCurrentThreadId(); #else int64_t threadId = 0; pthread_t thread = pthread_self(); memcpy(&threadId, &thread, std::min(sizeof(threadId), sizeof(thread))); return threadId; #endif } void sleep(int seconds){ sleepmillis((unsigned long)(1000 * seconds)); } void sleepmillis(uint64_t milliseconds){ #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) Sleep((DWORD) milliseconds); #else ::usleep((useconds_t)(1000 * milliseconds)); #endif } char *strtok(char *str, const char *sep, char **context) { #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) return strtok_s(str, sep, context); #else return strtok_r(str, sep, context); #endif } int localtime(const time_t *clock, struct tm *result) { int returnCode = -1; #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) returnCode = localtime_s(result, clock); #else if (NULL != localtime_r(clock, result)) { returnCode = 0; } #endif return returnCode; } int hz_snprintf(char *str, size_t len, const char *format, ...) { va_list args; va_start(args, format); #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) int result = vsnprintf_s(str, len, _TRUNCATE, format, args); if (result < 0) { return len > 0 ? len - 1 : 0; } return result; #else return vsnprintf(str, len, format, args); #endif } void gitDateToHazelcastLogDate(std::string &date) { // convert the date string from "2016-04-20" to 20160420 date.erase(std::remove(date.begin(), date.end(), '"'), date.end()); if (date != "NOT_FOUND") { date.erase(std::remove(date.begin(), date.end(), '-'), date.end()); } } int64_t currentTimeMillis() { boost::posix_time::time_duration diff = TimeUtil::getDurationSinceEpoch(); return diff.total_milliseconds(); } int64_t currentTimeNanos() { boost::posix_time::time_duration diff = TimeUtil::getDurationSinceEpoch(); return diff.total_nanoseconds(); } int strerror_s(int errnum, char *strerrbuf, size_t buflen, const char *msgPrefix) { int numChars = 0; if ((const char *)NULL != msgPrefix) { numChars = util::hz_snprintf(strerrbuf, buflen, "%s ", msgPrefix); if (numChars < 0) { return numChars; } if (numChars >= (int)buflen - 1) { return 0; } } #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errnum, 0, (LPTSTR)(strerrbuf + numChars), buflen - numChars, NULL)) { return -1; } return 0; #elif defined(__llvm__) return ::strerror_r(errnum, strerrbuf + numChars, buflen - numChars); #elif defined(__GNUC__) char *errStr = ::strerror_r(errnum, strerrbuf + numChars, buflen - numChars); int result = util::hz_snprintf(strerrbuf + numChars, buflen - numChars, "%s", errStr); if (result < 0) { return result; } return 0; #endif } int32_t getAvailableCoreCount() { #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #else return (int32_t) sysconf(_SC_NPROCESSORS_ONLN); #endif } std::string StringUtil::timeToString(int64_t timeInMillis) { boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%Y-%m-%d %H:%M:%S.%f"); std::stringstream dateStream; dateStream.imbue(std::locale(dateStream.getloc(), facet)); boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1)); dateStream << epoch + boost::posix_time::milliseconds(timeInMillis); return dateStream.str(); } std::string StringUtil::timeToStringFriendly(int64_t timeInMillis) { return timeInMillis == 0 ? "never" : timeToString(timeInMillis); } std::vector<std::string> StringUtil::tokenizeVersionString(const std::string &version) { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep("."); tokenizer tok(version, sep); std::vector<std::string> tokens; BOOST_FOREACH(const std::string &token , tok) { tokens.push_back(token); } return tokens; } int Int64Util::numberOfLeadingZeros(int64_t i) { // HD, Figure 5-6 if (i == 0) return 64; int n = 1; int64_t x = (int64_t)(i >> 32); if (x == 0) { n += 32; x = (int64_t)i; } if (x >> 16 == 0) { n += 16; x <<= 16; } if (x >> 24 == 0) { n += 8; x <<= 8; } if (x >> 28 == 0) { n += 4; x <<= 4; } if (x >> 30 == 0) { n += 2; x <<= 2; } n -= x >> 31; return n; } } } <commit_msg>Fix for strerror_r compilation problem reported at issue #435 (#436)<commit_after>/* * Copyright (c) 2008-2018, Hazelcast, Inc. 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. */ // // Created by sancar koyunlu on 5/3/13. #include "hazelcast/util/Util.h" #include "hazelcast/util/TimeUtil.h" #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <string.h> #include <algorithm> #include <stdio.h> #include <stdarg.h> #include <stdint.h> #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #define WIN32_LEAN_AND_MEAN #include <Windows.h> #else #include <sys/time.h> #include <unistd.h> #include <pthread.h> #endif namespace hazelcast { namespace util { int64_t getCurrentThreadId() { #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) return (int64_t) GetCurrentThreadId(); #else int64_t threadId = 0; pthread_t thread = pthread_self(); memcpy(&threadId, &thread, std::min(sizeof(threadId), sizeof(thread))); return threadId; #endif } void sleep(int seconds){ sleepmillis((unsigned long)(1000 * seconds)); } void sleepmillis(uint64_t milliseconds){ #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) Sleep((DWORD) milliseconds); #else ::usleep((useconds_t)(1000 * milliseconds)); #endif } char *strtok(char *str, const char *sep, char **context) { #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) return strtok_s(str, sep, context); #else return strtok_r(str, sep, context); #endif } int localtime(const time_t *clock, struct tm *result) { int returnCode = -1; #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) returnCode = localtime_s(result, clock); #else if (NULL != localtime_r(clock, result)) { returnCode = 0; } #endif return returnCode; } int hz_snprintf(char *str, size_t len, const char *format, ...) { va_list args; va_start(args, format); #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) int result = vsnprintf_s(str, len, _TRUNCATE, format, args); if (result < 0) { return len > 0 ? len - 1 : 0; } return result; #else return vsnprintf(str, len, format, args); #endif } void gitDateToHazelcastLogDate(std::string &date) { // convert the date string from "2016-04-20" to 20160420 date.erase(std::remove(date.begin(), date.end(), '"'), date.end()); if (date != "NOT_FOUND") { date.erase(std::remove(date.begin(), date.end(), '-'), date.end()); } } int64_t currentTimeMillis() { boost::posix_time::time_duration diff = TimeUtil::getDurationSinceEpoch(); return diff.total_milliseconds(); } int64_t currentTimeNanos() { boost::posix_time::time_duration diff = TimeUtil::getDurationSinceEpoch(); return diff.total_nanoseconds(); } int strerror_s(int errnum, char *strerrbuf, size_t buflen, const char *msgPrefix) { int numChars = 0; if ((const char *)NULL != msgPrefix) { numChars = util::hz_snprintf(strerrbuf, buflen, "%s ", msgPrefix); if (numChars < 0) { return numChars; } if (numChars >= (int)buflen - 1) { return 0; } } #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errnum, 0, (LPTSTR)(strerrbuf + numChars), buflen - numChars, NULL)) { return -1; } return 0; #elif defined(__llvm__) && ! _GNU_SOURCE /* XSI-compliant */ return ::strerror_r(errnum, strerrbuf + numChars, buflen - numChars); #else /* GNU-specific */ char *errStr = ::strerror_r(errnum, strerrbuf + numChars, buflen - numChars); int result = util::hz_snprintf(strerrbuf + numChars, buflen - numChars, "%s", errStr); if (result < 0) { return result; } return 0; #endif } int32_t getAvailableCoreCount() { #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #else return (int32_t) sysconf(_SC_NPROCESSORS_ONLN); #endif } std::string StringUtil::timeToString(int64_t timeInMillis) { boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%Y-%m-%d %H:%M:%S.%f"); std::stringstream dateStream; dateStream.imbue(std::locale(dateStream.getloc(), facet)); boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1)); dateStream << epoch + boost::posix_time::milliseconds(timeInMillis); return dateStream.str(); } std::string StringUtil::timeToStringFriendly(int64_t timeInMillis) { return timeInMillis == 0 ? "never" : timeToString(timeInMillis); } std::vector<std::string> StringUtil::tokenizeVersionString(const std::string &version) { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep("."); tokenizer tok(version, sep); std::vector<std::string> tokens; BOOST_FOREACH(const std::string &token , tok) { tokens.push_back(token); } return tokens; } int Int64Util::numberOfLeadingZeros(int64_t i) { // HD, Figure 5-6 if (i == 0) return 64; int n = 1; int64_t x = (int64_t)(i >> 32); if (x == 0) { n += 32; x = (int64_t)i; } if (x >> 16 == 0) { n += 16; x <<= 16; } if (x >> 24 == 0) { n += 8; x <<= 8; } if (x >> 28 == 0) { n += 4; x <<= 4; } if (x >> 30 == 0) { n += 2; x <<= 2; } n -= x >> 31; return n; } } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "qt5rendernodeinstanceserver.h" #include <QSGItem> #include "servernodeinstance.h" #include "childrenchangeeventfilter.h" #include "propertyabstractcontainer.h" #include "propertybindingcontainer.h" #include "propertyvaluecontainer.h" #include "instancecontainer.h" #include "createinstancescommand.h" #include "changefileurlcommand.h" #include "clearscenecommand.h" #include "reparentinstancescommand.h" #include "changevaluescommand.h" #include "changebindingscommand.h" #include "changeidscommand.h" #include "removeinstancescommand.h" #include "nodeinstanceclientinterface.h" #include "removepropertiescommand.h" #include "valueschangedcommand.h" #include "informationchangedcommand.h" #include "pixmapchangedcommand.h" #include "commondefines.h" #include "childrenchangeeventfilter.h" #include "changestatecommand.h" #include "childrenchangedcommand.h" #include "completecomponentcommand.h" #include "componentcompletedcommand.h" #include "createscenecommand.h" #include "dummycontextobject.h" #include "private/designersupport.h" namespace QmlDesigner { Qt5RenderNodeInstanceServer::Qt5RenderNodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) : Qt5NodeInstanceServer(nodeInstanceClient) { } void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands() { static bool inFunction = false; if (!inFunction) { inFunction = true; if (sgView()) { foreach (QSGItem *item, allItems()) { if (item && hasInstanceForObject(item)) { ServerNodeInstance instance = instanceForObject(item); if (DesignerSupport::dirty(item, DesignerSupport::ContentUpdateMask)) m_dirtyInstanceSet.insert(instance); } } clearChangedPropertyList(); if (!m_dirtyInstanceSet.isEmpty() && nodeInstanceClient()->bytesToWrite() < 10000) { nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(m_dirtyInstanceSet.toList())); m_dirtyInstanceSet.clear(); } resetAllItems(); slowDownRenderTimer(); nodeInstanceClient()->flush(); nodeInstanceClient()->synchronizeWithClientProcess(); } inFunction = false; } } void Qt5RenderNodeInstanceServer::createScene(const CreateSceneCommand &command) { NodeInstanceServer::createScene(command); QList<ServerNodeInstance> instanceList; foreach (const InstanceContainer &container, command.instances()) { ServerNodeInstance instance = instanceForId(container.instanceId()); if (instance.isValid()) { instanceList.append(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } void Qt5RenderNodeInstanceServer::clearScene(const ClearSceneCommand &command) { NodeInstanceServer::clearScene(command); m_dirtyInstanceSet.clear(); } void Qt5RenderNodeInstanceServer::completeComponent(const CompleteComponentCommand &command) { NodeInstanceServer::completeComponent(command); QList<ServerNodeInstance> instanceList; foreach (qint32 instanceId, command.instances()) { ServerNodeInstance instance = instanceForId(instanceId); if (instance.isValid()) { instanceList.append(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } } // namespace QmlDesigner <commit_msg>QmlDesigner.NodeInstances: Fix function call to parent class<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "qt5rendernodeinstanceserver.h" #include <QSGItem> #include "servernodeinstance.h" #include "childrenchangeeventfilter.h" #include "propertyabstractcontainer.h" #include "propertybindingcontainer.h" #include "propertyvaluecontainer.h" #include "instancecontainer.h" #include "createinstancescommand.h" #include "changefileurlcommand.h" #include "clearscenecommand.h" #include "reparentinstancescommand.h" #include "changevaluescommand.h" #include "changebindingscommand.h" #include "changeidscommand.h" #include "removeinstancescommand.h" #include "nodeinstanceclientinterface.h" #include "removepropertiescommand.h" #include "valueschangedcommand.h" #include "informationchangedcommand.h" #include "pixmapchangedcommand.h" #include "commondefines.h" #include "childrenchangeeventfilter.h" #include "changestatecommand.h" #include "childrenchangedcommand.h" #include "completecomponentcommand.h" #include "componentcompletedcommand.h" #include "createscenecommand.h" #include "dummycontextobject.h" #include "private/designersupport.h" namespace QmlDesigner { Qt5RenderNodeInstanceServer::Qt5RenderNodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) : Qt5NodeInstanceServer(nodeInstanceClient) { } void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands() { static bool inFunction = false; if (!inFunction) { inFunction = true; if (sgView()) { foreach (QSGItem *item, allItems()) { if (item && hasInstanceForObject(item)) { ServerNodeInstance instance = instanceForObject(item); if (DesignerSupport::dirty(item, DesignerSupport::ContentUpdateMask)) m_dirtyInstanceSet.insert(instance); } } clearChangedPropertyList(); if (!m_dirtyInstanceSet.isEmpty() && nodeInstanceClient()->bytesToWrite() < 10000) { nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(m_dirtyInstanceSet.toList())); m_dirtyInstanceSet.clear(); } resetAllItems(); slowDownRenderTimer(); nodeInstanceClient()->flush(); nodeInstanceClient()->synchronizeWithClientProcess(); } inFunction = false; } } void Qt5RenderNodeInstanceServer::createScene(const CreateSceneCommand &command) { Qt5NodeInstanceServer::createScene(command); QList<ServerNodeInstance> instanceList; foreach (const InstanceContainer &container, command.instances()) { ServerNodeInstance instance = instanceForId(container.instanceId()); if (instance.isValid()) { instanceList.append(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } void Qt5RenderNodeInstanceServer::clearScene(const ClearSceneCommand &command) { Qt5NodeInstanceServer::clearScene(command); m_dirtyInstanceSet.clear(); } void Qt5RenderNodeInstanceServer::completeComponent(const CompleteComponentCommand &command) { Qt5NodeInstanceServer::completeComponent(command); QList<ServerNodeInstance> instanceList; foreach (qint32 instanceId, command.instances()) { ServerNodeInstance instance = instanceForId(instanceId); if (instance.isValid()) { instanceList.append(instance); m_dirtyInstanceSet.insert(instance); } } nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList)); } } // namespace QmlDesigner <|endoftext|>
<commit_before>#include "parma_selector.h" #include "parma_targets.h" #include "parma_weights.h" namespace parma { class VtxSelector : public Selector { public: VtxSelector(apf::Mesh* m, apf::MeshTag* w) : Selector(m, w) {} apf::Migration* run(Targets* tgts) { apf::Migration* plan = new apf::Migration(mesh); vtag = mesh->createIntTag("selector_visited",1); const size_t maxBoundedElm = 6; double planW=0; for( size_t maxAdjElm=2; maxAdjElm<=maxBoundedElm; maxAdjElm+=2) planW += select(tgts, planW, maxAdjElm, plan); apf::removeTagFromDimension(mesh,vtag,0); mesh->destroyTag(vtag); return plan; } virtual double getWeight(apf::MeshEntity* vtx) { return getEntWeight(mesh,vtx,wtag); } private: apf::MeshTag* vtag; VtxSelector(); double add(apf::MeshEntity* vtx, const size_t maxAdjElm, const int destPid, apf::Migration* plan) { apf::DynamicArray<apf::MeshEntity*> adjElms; mesh->getAdjacent(vtx, mesh->getDimension(), adjElms); if( adjElms.getSize() > maxAdjElm ) return 0; for(size_t i=0; i<adjElms.getSize(); i++) { apf::MeshEntity* elm = adjElms[i]; if ( mesh->hasTag(elm, vtag) ) continue; mesh->setIntTag(elm, vtag, &destPid); plan->send(elm, destPid); } return getWeight(vtx); } double select(Targets* tgts, const double planW, const size_t maxAdjElm, apf::Migration* plan) { double planWeight = 0; apf::MeshEntity* vtx; apf::MeshIterator* itr = mesh->begin(0); while( (vtx = mesh->iterate(itr)) ) { if ( planW + planWeight > tgts->total() ) break; apf::Copies rmt; mesh->getRemotes(vtx, rmt); if( 1 == rmt.size() ) { int destPid = (rmt.begin())->first; if( tgts->has(destPid) ) planWeight += add(vtx, maxAdjElm, destPid, plan); } } mesh->end(itr); return planWeight; } }; Selector* makeVtxSelector(apf::Mesh* m, apf::MeshTag* w) { return new VtxSelector(m, w); } class EdgeSelector : public VtxSelector { public: EdgeSelector(apf::Mesh* m, apf::MeshTag* w) : VtxSelector(m, w) {} protected: double getWeight(apf::MeshEntity* vtx) { apf::Up edges; mesh->getUp(vtx, edges); double w = 0; for(int i=0; i<edges.n; i++) if( mesh->isShared(edges.e[i]) ) w += getEntWeight(mesh, edges.e[i], wtag); return w; } }; Selector* makeEdgeSelector(apf::Mesh* m, apf::MeshTag* w) { return new EdgeSelector(m, w); } } //end namespace parma <commit_msg>move getWeight virtual fn to protected<commit_after>#include "parma_selector.h" #include "parma_targets.h" #include "parma_weights.h" namespace parma { class VtxSelector : public Selector { public: VtxSelector(apf::Mesh* m, apf::MeshTag* w) : Selector(m, w) {} apf::Migration* run(Targets* tgts) { apf::Migration* plan = new apf::Migration(mesh); vtag = mesh->createIntTag("selector_visited",1); const size_t maxBoundedElm = 6; double planW=0; for( size_t maxAdjElm=2; maxAdjElm<=maxBoundedElm; maxAdjElm+=2) planW += select(tgts, planW, maxAdjElm, plan); apf::removeTagFromDimension(mesh,vtag,0); mesh->destroyTag(vtag); return plan; } protected: virtual double getWeight(apf::MeshEntity* vtx) { return getEntWeight(mesh,vtx,wtag); } private: apf::MeshTag* vtag; VtxSelector(); double add(apf::MeshEntity* vtx, const size_t maxAdjElm, const int destPid, apf::Migration* plan) { apf::DynamicArray<apf::MeshEntity*> adjElms; mesh->getAdjacent(vtx, mesh->getDimension(), adjElms); if( adjElms.getSize() > maxAdjElm ) return 0; for(size_t i=0; i<adjElms.getSize(); i++) { apf::MeshEntity* elm = adjElms[i]; if ( mesh->hasTag(elm, vtag) ) continue; mesh->setIntTag(elm, vtag, &destPid); plan->send(elm, destPid); } return getWeight(vtx); } double select(Targets* tgts, const double planW, const size_t maxAdjElm, apf::Migration* plan) { double planWeight = 0; apf::MeshEntity* vtx; apf::MeshIterator* itr = mesh->begin(0); while( (vtx = mesh->iterate(itr)) ) { if ( planW + planWeight > tgts->total() ) break; apf::Copies rmt; mesh->getRemotes(vtx, rmt); if( 1 == rmt.size() ) { int destPid = (rmt.begin())->first; if( tgts->has(destPid) ) planWeight += add(vtx, maxAdjElm, destPid, plan); } } mesh->end(itr); return planWeight; } }; Selector* makeVtxSelector(apf::Mesh* m, apf::MeshTag* w) { return new VtxSelector(m, w); } class EdgeSelector : public VtxSelector { public: EdgeSelector(apf::Mesh* m, apf::MeshTag* w) : VtxSelector(m, w) {} protected: double getWeight(apf::MeshEntity* vtx) { apf::Up edges; mesh->getUp(vtx, edges); double w = 0; for(int i=0; i<edges.n; i++) if( mesh->isShared(edges.e[i]) ) w += getEntWeight(mesh, edges.e[i], wtag); return w; } }; Selector* makeEdgeSelector(apf::Mesh* m, apf::MeshTag* w) { return new EdgeSelector(m, w); } } //end namespace parma <|endoftext|>
<commit_before>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief Ȩ */ #pragma once #include "win_utils_header.h" namespace zl { namespace WinUtils { class ZLPrivilege { public: static HRESULT GetPrivileges(LPCTSTR szPrivileges = SE_DEBUG_NAME) { BOOL bRet = FALSE; HANDLE hToken = NULL; LUID CurrentLUID = { 0 }; TOKEN_PRIVILEGES TokenPrivileges = { 0 }; __try { bRet = ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); if (!bRet) __leave; bRet = ::LookupPrivilegeValue(NULL, szPrivileges, &CurrentLUID); if (!bRet) __leave; TokenPrivileges.PrivilegeCount = 1; TokenPrivileges.Privileges[0].Luid = CurrentLUID; TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; bRet = ::AdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges, 0, NULL, NULL); if (!bRet) __leave; bRet = TRUE; } __finally { if (hToken) { ::CloseHandle(hToken); hToken = NULL; } } return bRet; } }; } } <commit_msg>*privilege文件注释<commit_after>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief Ȩ */ #pragma once #include "win_utils_header.h" namespace zl { namespace WinUtils { /** * @brief Ȩ޵ */ class ZLPrivilege { public: /** * @brief ǰȨ * @param[in] szPrivileges Ȩ * @return ɹط * @see OpenProcessToken LookupPrivilegeValue AdjustTokenPrivileges */ static HRESULT GetPrivileges(LPCTSTR szPrivileges = SE_DEBUG_NAME) { BOOL bRet = FALSE; HANDLE hToken = NULL; LUID CurrentLUID = { 0 }; TOKEN_PRIVILEGES TokenPrivileges = { 0 }; __try { bRet = ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); if (!bRet) __leave; bRet = ::LookupPrivilegeValue(NULL, szPrivileges, &CurrentLUID); if (!bRet) __leave; TokenPrivileges.PrivilegeCount = 1; TokenPrivileges.Privileges[0].Luid = CurrentLUID; TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; bRet = ::AdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges, 0, NULL, NULL); if (!bRet) __leave; bRet = TRUE; } __finally { if (hToken) { ::CloseHandle(hToken); hToken = NULL; } } return bRet; } }; } } <|endoftext|>
<commit_before>class Solution { public: bool isMatch(string s, string p) { const int n = s.length(); const int m = p.length(); vector<vector<bool>> dp(n + 1, vector<int>(m + 1, false)); dp[0][0] = true; for (int i = 0; i < n; ++i) { char ch = s[i]; for (int j = 0; j < m; ++j) { char pattern = p[j]; dp[i + 1][j + 1] = dp[i][j]; for (int k = 0; k < j; ++k) { dp[i + 1][j + 1] = } } } return dp[n][m]; } };<commit_msg>added solutions<commit_after>class Solution { public: bool isMatch(string s, string p) { int n = s.length(); int m = p.length(); vector<vector<bool>> dp(n + 1, vector<bool>(m + 1, false)); dp[0][0] = true; for (int i = 1; i <= m; ++i) { char pattern = p[i - 1]; if (pattern == '*') { for (int j = 0; j <= n; ++j) { if (dp[j][i - 1]) { for (int k = j; k <= n; ++k) { dp[k][i] = true; } } } } else if (pattern == '?') { for (int j = 0; j < n; ++j) { if (dp[j][i - 1]) { dp[j + 1][i] = true; } } } else { for (int j = 0; j < n; ++j) { if (dp[j][i - 1] && s[j] == pattern) { dp[j + 1][i] = true; } } } // for (int ii = 0; ii <= n; ++ii) { // for (int jj = 0; jj <= m; ++jj) { // printf("%d ", dp[ii][jj] ? 1 : 0); // } // printf("\n"); // } // printf("\n"); } return dp[n][m]; } };<|endoftext|>
<commit_before>#ifndef ALGORITHM #define ALGORITHM #include<algorithm> //find_if, remove_if #include<cstddef> //ptrdiff_t #include<functional> //equal_to #include<iterator> //iterator_traits, next #include<utility> //move namespace nAlgorithm { template<class T,class UnaryPred> bool all_of_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(!pred(begin)) return false; ++begin; } return true; } template<class T,class UnaryPred> T find_if_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(pred(begin)) return begin; ++begin; } return end; } template<class T,class UnaryPred> inline bool any_of_val(const T begin,const T end,const UnaryPred pred) { return find_if_val(begin,end,pred)!=end; } template<class T,class UnaryPred> std::ptrdiff_t count_if_val(T begin,const T end,const UnaryPred pred) { std::ptrdiff_t accu{0}; while(begin!=end) { if(pred(begin)) ++accu; ++begin; } return accu; } template<class T,class UnaryFunc> UnaryFunc for_each_val(T begin,const T end,UnaryFunc func) { while(begin!=end) { func(begin); ++begin; } return std::move(func); } template<class InIter,class UnaryPred,class UnaryFunc> void loop_until_none_of(const InIter begin,const InIter end,const UnaryPred pred,const UnaryFunc func) { for(InIter iter;(iter=std::find_if(begin,end,pred))!=end;) func(*iter); } template<class InIter,class OutIter,class BinaryOp> void multiply(InIter lbegin,const InIter lend,const InIter rbegin,const InIter rend,OutIter des,const BinaryOp op) { while(lbegin!=lend) { for(auto begin{rbegin};begin!=rend;++begin,++des) *des=op(*lbegin,*begin); ++lbegin; } } //unique_without_sort will reorder the input permutation. template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort(FwdIter begin,FwdIter end,const BinaryPred pred=BinaryPred()) { while(begin!=end) { end=std::remove_if(std::next(begin),end,[&begin=*begin,pred](auto &&val){ return pred(begin,std::forward<decltype(val)>(val)); }); ++begin; } return end; } } #endif<commit_msg>update (forwarding reference)<commit_after>#ifndef ALGORITHM #define ALGORITHM #include<algorithm> //find_if, remove_if #include<cstddef> //ptrdiff_t #include<functional> //equal_to #include<iterator> //iterator_traits, next #include<utility> //forward, move namespace nAlgorithm { template<class T,class UnaryPred> bool all_of_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(!pred(begin)) return false; ++begin; } return true; } template<class T,class UnaryPred> T find_if_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(pred(begin)) return begin; ++begin; } return end; } template<class T,class UnaryPred> inline bool any_of_val(const T begin,const T end,const UnaryPred pred) { return find_if_val(begin,end,pred)!=end; } template<class T,class UnaryPred> std::ptrdiff_t count_if_val(T begin,const T end,const UnaryPred pred) { std::ptrdiff_t accu{0}; while(begin!=end) { if(pred(begin)) ++accu; ++begin; } return accu; } template<class T,class UnaryFunc> UnaryFunc for_each_val(T begin,const T end,UnaryFunc func) { while(begin!=end) { func(begin); ++begin; } return std::move(func); } template<class InIter,class UnaryPred,class UnaryFunc> void loop_until_none_of(const InIter begin,const InIter end,const UnaryPred pred,const UnaryFunc func) { for(InIter iter;(iter=std::find_if(begin,end,pred))!=end;) func(*iter); } template<class InIter,class OutIter,class BinaryOp> void multiply(InIter lbegin,const InIter lend,const InIter rbegin,const InIter rend,OutIter des,BinaryOp &&op) { while(lbegin!=lend) { for(auto begin{rbegin};begin!=rend;++begin,++des) *des=std::forward<decltype(op)>(op)(*lbegin,*begin); ++lbegin; } } //unique_without_sort will reorder the input permutation. template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort(FwdIter begin,FwdIter end,const BinaryPred pred=BinaryPred()) { while(begin!=end) { end=std::remove_if(std::next(begin),end,[&begin=*begin,pred](auto &&val){ return pred(begin,std::forward<decltype(val)>(val)); }); ++begin; } return end; } } #endif<|endoftext|>
<commit_before><commit_msg>Small type fix<commit_after><|endoftext|>
<commit_before>#ifndef IMPORTER_POLYGONIDENTIFYER_HPP #define IMPORTER_POLYGONIDENTIFYER_HPP const char *polygons[] = { "aeroway", "amenity", "area", "building", "harbour", "historic", "landuse", "leisure", "man_made", "military", "natural", "power", "place", "shop", "sport", "tourism", "water", "waterway", "wetland" }; static const int n_polygons = (sizeof(polygons) / sizeof(*polygons)); /* Data to generate z-order column and lowzoom-table * This includes railways and administrative boundaries, too */ static struct { int offset; const char *highway; int lowzoom; } layers[] = { { 3, "minor", 0 }, { 3, "road", 0 }, { 3, "unclassified", 0 }, { 3, "residential", 0 }, { 4, "tertiary_link", 0 }, { 4, "tertiary", 0 }, { 6, "secondary_link",1 }, { 6, "secondary", 1 }, { 7, "primary_link", 1 }, { 7, "primary", 1 }, { 8, "trunk_link", 1 }, { 8, "trunk", 1 }, { 9, "motorway_link", 1 }, { 9, "motorway", 1 } }; static const int n_layers = (sizeof(layers) / sizeof(*layers)); class PolygonIdentifyer { public: bool looksLikePolygon(const Osmium::OSM::TagList& tags) { for(Osmium::OSM::TagList::const_iterator it = tags.begin(); it != tags.end(); ++it) { for(int i = 0; i < n_polygons; i++) { if(0 == strcmp(polygons[i], it->key())) { return true; } } } return false; } int calculateZOrder(const Osmium::OSM::TagList& tags) { int z_order = 0; int lowzoom; const char *layer = tags.get_tag_by_key("layer"); const char *highway = tags.get_tag_by_key("highway"); const char *bridge = tags.get_tag_by_key("bridge"); const char *tunnel = tags.get_tag_by_key("tunnel"); const char *railway = tags.get_tag_by_key("railway"); const char *boundary = tags.get_tag_by_key("boundary"); if(layer) { z_order = strtol(layer, NULL, 10) * 10; } if(highway) { for(int i = 0; i < n_layers; i++) { if(0 == strcmp(layers[i].highway, highway)) { z_order += layers[i].offset; lowzoom = layers[i].lowzoom; break; } } } if(railway) { z_order += 5; lowzoom = 1; } // Administrative boundaries are rendered at low zooms so we prefer to use the lowzoom table if(boundary && 0 == strcmp(boundary, "administrative")) { lowzoom = 1; } if(bridge && (0 == strcmp(bridge, "true") || 0 == strcmp(bridge, "yes") || 0 == strcmp(bridge, "1"))) { z_order += 10; } if(tunnel && (0 == strcmp(tunnel, "true") || 0 == strcmp(tunnel, "yes") || 0 == strcmp(tunnel, "1"))) { z_order -= 10; } return z_order; } }; #endif // IMPORTER_POLYGONIDENTIFYER_HPP <commit_msg>fix types<commit_after>#ifndef IMPORTER_POLYGONIDENTIFYER_HPP #define IMPORTER_POLYGONIDENTIFYER_HPP const char *polygons[] = { "aeroway", "amenity", "area", "building", "harbour", "historic", "landuse", "leisure", "man_made", "military", "natural", "power", "place", "shop", "sport", "tourism", "water", "waterway", "wetland" }; static const int n_polygons = (sizeof(polygons) / sizeof(*polygons)); /* Data to generate z-order column and lowzoom-table * This includes railways and administrative boundaries, too */ static struct { int offset; const char *highway; bool lowzoom; } layers[] = { { 3, "minor", 0 }, { 3, "road", 0 }, { 3, "unclassified", 0 }, { 3, "residential", 0 }, { 4, "tertiary_link", 0 }, { 4, "tertiary", 0 }, { 6, "secondary_link",1 }, { 6, "secondary", 1 }, { 7, "primary_link", 1 }, { 7, "primary", 1 }, { 8, "trunk_link", 1 }, { 8, "trunk", 1 }, { 9, "motorway_link", 1 }, { 9, "motorway", 1 } }; static const int n_layers = (sizeof(layers) / sizeof(*layers)); class PolygonIdentifyer { public: bool looksLikePolygon(const Osmium::OSM::TagList& tags) { for(Osmium::OSM::TagList::const_iterator it = tags.begin(); it != tags.end(); ++it) { for(int i = 0; i < n_polygons; i++) { if(0 == strcmp(polygons[i], it->key())) { return true; } } } return false; } long int calculateZOrder(const Osmium::OSM::TagList& tags) { long int z_order = 0; int lowzoom; const char *layer = tags.get_tag_by_key("layer"); const char *highway = tags.get_tag_by_key("highway"); const char *bridge = tags.get_tag_by_key("bridge"); const char *tunnel = tags.get_tag_by_key("tunnel"); const char *railway = tags.get_tag_by_key("railway"); const char *boundary = tags.get_tag_by_key("boundary"); if(layer) { z_order = strtol(layer, NULL, 10) * 10; } if(highway) { for(int i = 0; i < n_layers; i++) { if(0 == strcmp(layers[i].highway, highway)) { z_order += layers[i].offset; lowzoom = layers[i].lowzoom; break; } } } if(railway) { z_order += 5; lowzoom = 1; } // Administrative boundaries are rendered at low zooms so we prefer to use the lowzoom table if(boundary && 0 == strcmp(boundary, "administrative")) { lowzoom = 1; } if(bridge && (0 == strcmp(bridge, "true") || 0 == strcmp(bridge, "yes") || 0 == strcmp(bridge, "1"))) { z_order += 10; } if(tunnel && (0 == strcmp(tunnel, "true") || 0 == strcmp(tunnel, "yes") || 0 == strcmp(tunnel, "1"))) { z_order -= 10; } return z_order; } }; #endif // IMPORTER_POLYGONIDENTIFYER_HPP <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_MULTIPLICATION_HPP #define ETL_MULTIPLICATION_HPP #include <algorithm> namespace etl { namespace detail { template<typename A, typename B, typename C, cpp::disable_if_all_u<etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast> = cpp::detail::dummy> void check_mmul_sizes(const A& a, const B& b, C& c){ cpp_assert( dim(a,1) == dim(b,0) //interior dimensions && dim(a,0) == dim(c,0) //exterior dimension 1 && dim(b,1) == dim(c,1), //exterior dimension 2 "Invalid sizes for multiplication"); cpp_unused(a); cpp_unused(b); cpp_unused(c); } template<typename A, typename B, typename C, cpp::enable_if_all_u<etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast> = cpp::detail::dummy> void check_mmul_sizes(const A&, const B&, C&){ static_assert( etl_traits<A>::template dim<1>() == etl_traits<B>::template dim<0>() //interior dimensions && etl_traits<A>::template dim<0>() == etl_traits<C>::template dim<0>() //exterior dimension 1 && etl_traits<B>::template dim<1>() == etl_traits<C>::template dim<1>(), //exterior dimension 2 "Invalid sizes for multiplication"); } } //end of namespace detail template<typename A, typename B, typename C> static C& mmul(const A& a, const B& b, C& c){ static_assert(is_etl_expr<A>::value && is_etl_expr<B>::value && is_etl_expr<C>::value, "Matrix multiplication only supported for ETL expressions"); static_assert(etl_traits<A>::dimensions() == 2 && etl_traits<B>::dimensions() == 2 && etl_traits<C>::dimensions() == 2, "Matrix multiplication only works in 2D"); detail::check_mmul_sizes(a,b,c); c = 0; for(std::size_t i = 0; i < rows(a); i++){ for(std::size_t j = 0; j < columns(b); j++){ for(std::size_t k = 0; k < columns(a); k++){ c(i,j) += a(i,k) * b(k,j); } } } return c; } template<typename A, typename B, typename C, cpp::enable_if_all_u< etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast, etl_traits<A>::dimensions() == 1, etl_traits<B>::dimensions() == 2 > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(reshape<1, etl_traits<B>::template dim<0>()>(a), b, c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast, etl_traits<A>::dimensions() == 2, etl_traits<B>::dimensions() == 1 > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(a, reshape<etl_traits<A>::template dim<1>(),1>(b), c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 1, etl_traits<B>::dimensions() == 2, cpp::not_u<etl_traits<A>::is_fast>::value > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(reshape(a, 1, dim<0>(b)), b, c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 2, etl_traits<B>::dimensions() == 1, cpp::not_u<etl_traits<B>::is_fast>::value > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(a, reshape(b, dim<1>(a), 1), c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 1, etl_traits<B>::dimensions() == 2, etl_traits<A>::is_fast > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(reshape<1, etl_traits<B>::template dim<0>()>(a), b, c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 2, etl_traits<B>::dimensions() == 1, etl_traits<B>::is_fast > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(a, reshape<etl_traits<A>::template dim<1>(),1>(b), c); } } //end of namespace etl #endif <commit_msg>Improve assertions<commit_after>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_MULTIPLICATION_HPP #define ETL_MULTIPLICATION_HPP #include <algorithm> namespace etl { namespace detail { template<typename A, typename B, typename C, cpp::disable_if_all_u<etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast> = cpp::detail::dummy> void check_mmul_sizes(const A& a, const B& b, C& c){ cpp_assert( dim<1>(a) == dim<0>(b) //interior dimensions && dim<0>(a) == dim<0>(c) //exterior dimension 1 && dim<1>(b) == dim<1>(c), //exterior dimension 2 "Invalid sizes for multiplication"); cpp_unused(a); cpp_unused(b); cpp_unused(c); } template<typename A, typename B, typename C, cpp::enable_if_all_u<etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast> = cpp::detail::dummy> void check_mmul_sizes(const A&, const B&, C&){ static_assert( etl_traits<A>::template dim<1>() == etl_traits<B>::template dim<0>() //interior dimensions && etl_traits<A>::template dim<0>() == etl_traits<C>::template dim<0>() //exterior dimension 1 && etl_traits<B>::template dim<1>() == etl_traits<C>::template dim<1>(), //exterior dimension 2 "Invalid sizes for multiplication"); } } //end of namespace detail template<typename A, typename B, typename C> static C& mmul(const A& a, const B& b, C& c){ static_assert(is_etl_expr<A>::value && is_etl_expr<B>::value && is_etl_expr<C>::value, "Matrix multiplication only supported for ETL expressions"); static_assert(etl_traits<A>::dimensions() == 2 && etl_traits<B>::dimensions() == 2 && etl_traits<C>::dimensions() == 2, "Matrix multiplication only works in 2D"); detail::check_mmul_sizes(a,b,c); c = 0; for(std::size_t i = 0; i < rows(a); i++){ for(std::size_t j = 0; j < columns(b); j++){ for(std::size_t k = 0; k < columns(a); k++){ c(i,j) += a(i,k) * b(k,j); } } } return c; } template<typename A, typename B, typename C, cpp::enable_if_all_u< etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast, etl_traits<A>::dimensions() == 1, etl_traits<B>::dimensions() == 2 > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(reshape<1, etl_traits<B>::template dim<0>()>(a), b, c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< etl_traits<A>::is_fast, etl_traits<B>::is_fast, etl_traits<C>::is_fast, etl_traits<A>::dimensions() == 2, etl_traits<B>::dimensions() == 1 > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(a, reshape<etl_traits<A>::template dim<1>(),1>(b), c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 1, etl_traits<B>::dimensions() == 2, cpp::not_u<etl_traits<A>::is_fast>::value > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(reshape(a, 1, dim<0>(b)), b, c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 2, etl_traits<B>::dimensions() == 1, cpp::not_u<etl_traits<B>::is_fast>::value > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(a, reshape(b, dim<1>(a), 1), c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 1, etl_traits<B>::dimensions() == 2, etl_traits<A>::is_fast > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(reshape<1, etl_traits<B>::template dim<0>()>(a), b, c); } template<typename A, typename B, typename C, cpp::enable_if_all_u< cpp::or_u<!etl_traits<A>::is_fast, !etl_traits<B>::is_fast, !etl_traits<C>::is_fast>::value, etl_traits<A>::dimensions() == 2, etl_traits<B>::dimensions() == 1, etl_traits<B>::is_fast > = cpp::detail::dummy> static C& auto_vmmul(const A& a, const B& b, C& c){ return mmul(a, reshape<etl_traits<A>::template dim<1>(),1>(b), c); } } //end of namespace etl #endif <|endoftext|>
<commit_before>#if defined(LUG_SYSTEM_WINDOWS) inline const char* getLastErrorWindows() { static const DWORD size = 200 + 1; static WCHAR bufferWide[size]; static char buffer[size]; auto lastError = GetLastError(); FormatMessage( FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, lastError, 0, reinterpret_cast<LPSTR>(bufferWide), size, nullptr ); #pragma warning (push) #pragma warning (disable : 4996) std::wcstombs(buffer, bufferWide, size); #pragma warning (pop) return buffer; } #endif inline Handle open(const char* name) { Handle handle = nullptr; #if defined(LUG_SYSTEM_WINDOWS) handle = LoadLibraryA(name); #else handle = dlopen(name, RTLD_LAZY | RTLD_LOCAL); #endif if (!handle) { #if defined(LUG_SYSTEM_WINDOWS) LUG_LOG.warn("Library: Can't load the library: {}", getLastErrorWindows()); #else LUG_LOG.warn("Library: Can't load the library: {}", dlerror()); #endif } return handle; } inline void close(Handle handle) { if (!handle) { return; } #if defined(LUG_SYSTEM_WINDOWS) FreeLibrary(handle); #else dlclose(handle); #endif } template<typename Function> inline Function sym(Handle handle, const char *name) { void* sym = nullptr; #if defined(LUG_SYSTEM_WINDOWS) sym = GetProcAddress(handle, name); #else sym = dlsym(handle, name); #endif if (!sym) { #if defined(LUG_SYSTEM_WINDOWS) LUG_LOG.warn("Library: Can't load the symbol {}: {}", name, getLastErrorWindows()); #else LUG_LOG.warn("Library: Can't load the symbol {}: {}", name, dlerror()); #endif } return reinterpret_cast<Function>(sym); } <commit_msg>Fix getLastErrorWindows()<commit_after>#if defined(LUG_SYSTEM_WINDOWS) inline const char* getLastErrorWindows() { static const DWORD size = 200 + 1; static char buffer[size]; auto lastError = GetLastError(); auto messageSize = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, lastError, 0, buffer, size, nullptr ); if (messageSize > 0) { buffer[messageSize - 1] = 0; } return buffer; } #endif inline Handle open(const char* name) { Handle handle = nullptr; #if defined(LUG_SYSTEM_WINDOWS) handle = LoadLibraryA(name); #else handle = dlopen(name, RTLD_LAZY | RTLD_LOCAL); #endif if (!handle) { #if defined(LUG_SYSTEM_WINDOWS) LUG_LOG.warn("Library: Can't load the library: {}: {}", name, getLastErrorWindows()); #else LUG_LOG.warn("Library: Can't load the library: {}", dlerror()); #endif } return handle; } inline void close(Handle handle) { if (!handle) { return; } #if defined(LUG_SYSTEM_WINDOWS) FreeLibrary(handle); #else dlclose(handle); #endif } template<typename Function> inline Function sym(Handle handle, const char *name) { void* sym = nullptr; #if defined(LUG_SYSTEM_WINDOWS) sym = GetProcAddress(handle, name); #else sym = dlsym(handle, name); #endif if (!sym) { #if defined(LUG_SYSTEM_WINDOWS) LUG_LOG.warn("Library: Can't load the symbol {}: {}", name, getLastErrorWindows()); #else LUG_LOG.warn("Library: Can't load the symbol {}: {}", name, dlerror()); #endif } return reinterpret_cast<Function>(sym); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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_ENUMERATION_INCLUDED #define MAPNIK_ENUMERATION_INCLUDED #include <mapnik/config.hpp> #include <vector> #include <bitset> #include <iostream> #include <cstdlib> namespace mapnik { class illegal_enum_value : public std::exception { public: illegal_enum_value() {} illegal_enum_value( const std::string & what ) : what_( what ) { } virtual ~illegal_enum_value() throw() {}; virtual const char * what() const throw() { return what_.c_str(); } protected: std::string what_; }; /** Slim wrapper for enumerations. It creates a new type from a native enum and * a char pointer array. It almost exactly behaves like a native enumeration * type. It supports string conversion through stream operators. This is usefull * for debugging, serialization/deserialization and also helps with implementing * language bindings. The two convinient macros DEFINE_ENUM() and IMPLEMENT_ENUM() * are provided to help with instanciation. * * @par Limitations: * - The enum must start at zero. * - The enum must be consecutive. * - The enum must be terminated with a special token consisting of the enum's * name plus "_MAX". * - The corresponding char pointer array must be terminated with an empty string. * - The names must only consist of characters and digits (<i>a-z, A-Z, 0-9</i>), * underscores (<i>_</i>) and dashes (<i>-</i>). * * * @warning At the moment the verify() method is called during static initialization. * It quits the application with exit code 1 if any error is detected. The other solution * i thought of is to do the checks at compile time (using boost::mpl). * * @par Example: * The following code goes into the header file: * @code * enum fruit_enum { * APPLE, * CHERRY, * BANANA, * PASSION_FRUIT, * fruit_enum_MAX * }; * * static const char * fruit_strings[] = { * "apple", * "cherry", * "banana", * "passion_fruit", * "" * }; * * DEFINE_ENUM( fruit, fruit_enum); * @endcode * In the corresponding cpp file do: * @code * IMPLEMENT_ENUM( fruit, fruit_strings ); * @endcode * And here is how to use the resulting type Fruit * @code * * int * main(int argc, char * argv[]) { * fruit f(APPLE); * switch ( f ) { * case BANANA: * case APPLE: * cerr << "No thanks. I hate " << f << "s" << endl; * break; * default: * cerr << "Hmmm ... yummy " << f << endl; * break; * } * * f = CHERRY; * * fruit_enum native_enum = f; * * f.from_string("passion_fruit"); * * for (unsigned i = 0; i < fruit::MAX; ++i) { * cerr << i << " = " << fruit::get_string(i) << endl; * } * * f.from_string("elephant"); // throws illegal_enum_value * * return 0; * } * @endcode */ template <class ENUM, int THE_MAX> class MAPNIK_DECL enumeration { public: typedef ENUM native_type; enumeration() {}; enumeration( ENUM v ) : value_(v) {} enumeration( const enumeration & other ) : value_(other.value_) {} /** Assignment operator for native enum values. */ void operator=(ENUM v) { value_ = v; } /** Assignment operator. */ void operator=(const enumeration & other) { value_ = other.value_; } /** Conversion operator for native enum values. */ operator ENUM() const { return value_; } enum Max { MAX = THE_MAX }; ENUM max() const { return THE_MAX; } /** Converts @p str to an enum. * @throw illegal_enum_value @p str is not a legal identifier. * */ void from_string(const std::string & str) { for (unsigned i = 0; i < THE_MAX; ++i) { if (str == our_strings_[i]) { value_ = static_cast<ENUM>(i); return; } } throw illegal_enum_value(std::string("Illegal enumeration value '") + str + "' for enum " + our_name_); } /** Parses the input stream @p is for a word consisting of characters and * digits (<i>a-z, A-Z, 0-9</i>) and underscores (<i>_</i>). * The failbit of the stream is set if the word is not a valid identifier. */ std::istream & parse(std::istream & is) { std::string word; char c; while ( is.peek() != std::char_traits< char >::eof()) { is >> c; if ( isspace(c) && word.empty() ) { continue; } if ( isalnum(c) || (c == '_') || c == '-' ) { word += c; } else { is.unget(); break; } } try { from_string( word ); } catch (const illegal_enum_value &) { is.setstate(std::ios::failbit); } return is; } /** Returns the current value as a string identifier. */ std::string as_string() const { return our_strings_[value_]; } /** Prints the string identifier to the output stream @p os. */ std::ostream & print(std::ostream & os = std::cerr) const { return os << our_strings_[value_]; } /** Static helper function to iterate over valid identifiers. */ static const char * get_string(unsigned i) { return our_strings_[i]; } /** Performs some simple checks and quits the application if * any error is detected. Tries to print helpful error messages. */ static bool verify(const char * filename, unsigned line_no) { for (unsigned i = 0; i < THE_MAX; ++i) { if (our_strings_[i] == 0 ) { std::cerr << "### FATAL: Not enough strings for enum " << our_name_ << " defined in file '" << filename << "' at line " << line_no << std::endl; std::exit(1); } } if ( std::string("") != our_strings_[THE_MAX]) { std::cerr << "### FATAL: The string array for enum " << our_name_ << " defined in file '" << filename << "' at line " << line_no << " has too many items or is not terminated with an " << "empty string." << std::endl; std::exit(1); } return true; } static const std::string & get_full_qualified_name() { return our_name_; } static std::string get_name() { std::string::size_type idx = our_name_.find_last_of(":"); if ( idx == std::string::npos ) { return our_name_; } else { return our_name_.substr( idx + 1 ); } } private: ENUM value_; static const char ** our_strings_ ; static std::string our_name_ ; static bool our_verified_flag_; }; /** ostream operator for enumeration * @relates mapnik::enumeration */ template <class ENUM, int THE_MAX> std::ostream & operator<<(std::ostream & os, const mapnik::enumeration<ENUM, THE_MAX> & e) { e.print( os ); return os; } /** istream operator for enumeration * @relates mapnik::enumeration */ template <class ENUM, int THE_MAX> std::istream & operator>>(std::istream & is, mapnik::enumeration<ENUM, THE_MAX> & e) { e.parse( is ); return is; } } // end of namespace /** Helper macro. Creates a typedef. * @relates mapnik::enumeration */ #define DEFINE_ENUM( name, e) \ typedef mapnik::enumeration<e, e ## _MAX> name /** Helper macro. Runs the verify() method during static initialization. * @relates mapnik::enumeration */ #define IMPLEMENT_ENUM( name, strings ) \ template <> const char ** name ::our_strings_ = strings; \ template <> std::string name ::our_name_ = #name; \ template <> bool name ::our_verified_flag_( name ::verify(__FILE__, __LINE__)); #endif // MAPNIK_ENUMERATION_INCLUDED <commit_msg>+ comment out exit() calls (todo: implement better compile time tests)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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_ENUMERATION_INCLUDED #define MAPNIK_ENUMERATION_INCLUDED #include <mapnik/config.hpp> #include <vector> #include <bitset> #include <iostream> #include <cstdlib> namespace mapnik { class illegal_enum_value : public std::exception { public: illegal_enum_value() {} illegal_enum_value( const std::string & what ) : what_( what ) { } virtual ~illegal_enum_value() throw() {}; virtual const char * what() const throw() { return what_.c_str(); } protected: std::string what_; }; /** Slim wrapper for enumerations. It creates a new type from a native enum and * a char pointer array. It almost exactly behaves like a native enumeration * type. It supports string conversion through stream operators. This is usefull * for debugging, serialization/deserialization and also helps with implementing * language bindings. The two convinient macros DEFINE_ENUM() and IMPLEMENT_ENUM() * are provided to help with instanciation. * * @par Limitations: * - The enum must start at zero. * - The enum must be consecutive. * - The enum must be terminated with a special token consisting of the enum's * name plus "_MAX". * - The corresponding char pointer array must be terminated with an empty string. * - The names must only consist of characters and digits (<i>a-z, A-Z, 0-9</i>), * underscores (<i>_</i>) and dashes (<i>-</i>). * * * @warning At the moment the verify() method is called during static initialization. * It quits the application with exit code 1 if any error is detected. The other solution * i thought of is to do the checks at compile time (using boost::mpl). * * @par Example: * The following code goes into the header file: * @code * enum fruit_enum { * APPLE, * CHERRY, * BANANA, * PASSION_FRUIT, * fruit_enum_MAX * }; * * static const char * fruit_strings[] = { * "apple", * "cherry", * "banana", * "passion_fruit", * "" * }; * * DEFINE_ENUM( fruit, fruit_enum); * @endcode * In the corresponding cpp file do: * @code * IMPLEMENT_ENUM( fruit, fruit_strings ); * @endcode * And here is how to use the resulting type Fruit * @code * * int * main(int argc, char * argv[]) { * fruit f(APPLE); * switch ( f ) { * case BANANA: * case APPLE: * cerr << "No thanks. I hate " << f << "s" << endl; * break; * default: * cerr << "Hmmm ... yummy " << f << endl; * break; * } * * f = CHERRY; * * fruit_enum native_enum = f; * * f.from_string("passion_fruit"); * * for (unsigned i = 0; i < fruit::MAX; ++i) { * cerr << i << " = " << fruit::get_string(i) << endl; * } * * f.from_string("elephant"); // throws illegal_enum_value * * return 0; * } * @endcode */ template <class ENUM, int THE_MAX> class MAPNIK_DECL enumeration { public: typedef ENUM native_type; enumeration() {}; enumeration( ENUM v ) : value_(v) {} enumeration( const enumeration & other ) : value_(other.value_) {} /** Assignment operator for native enum values. */ void operator=(ENUM v) { value_ = v; } /** Assignment operator. */ void operator=(const enumeration & other) { value_ = other.value_; } /** Conversion operator for native enum values. */ operator ENUM() const { return value_; } enum Max { MAX = THE_MAX }; ENUM max() const { return THE_MAX; } /** Converts @p str to an enum. * @throw illegal_enum_value @p str is not a legal identifier. * */ void from_string(const std::string & str) { for (unsigned i = 0; i < THE_MAX; ++i) { if (str == our_strings_[i]) { value_ = static_cast<ENUM>(i); return; } } throw illegal_enum_value(std::string("Illegal enumeration value '") + str + "' for enum " + our_name_); } /** Parses the input stream @p is for a word consisting of characters and * digits (<i>a-z, A-Z, 0-9</i>) and underscores (<i>_</i>). * The failbit of the stream is set if the word is not a valid identifier. */ std::istream & parse(std::istream & is) { std::string word; char c; while ( is.peek() != std::char_traits< char >::eof()) { is >> c; if ( isspace(c) && word.empty() ) { continue; } if ( isalnum(c) || (c == '_') || c == '-' ) { word += c; } else { is.unget(); break; } } try { from_string( word ); } catch (const illegal_enum_value &) { is.setstate(std::ios::failbit); } return is; } /** Returns the current value as a string identifier. */ std::string as_string() const { return our_strings_[value_]; } /** Prints the string identifier to the output stream @p os. */ std::ostream & print(std::ostream & os = std::cerr) const { return os << our_strings_[value_]; } /** Static helper function to iterate over valid identifiers. */ static const char * get_string(unsigned i) { return our_strings_[i]; } /** Performs some simple checks and quits the application if * any error is detected. Tries to print helpful error messages. */ static bool verify(const char * filename, unsigned line_no) { for (unsigned i = 0; i < THE_MAX; ++i) { if (our_strings_[i] == 0 ) { std::cerr << "### FATAL: Not enough strings for enum " << our_name_ << " defined in file '" << filename << "' at line " << line_no << std::endl; //std::exit(1); } } if ( std::string("") != our_strings_[THE_MAX]) { std::cerr << "### FATAL: The string array for enum " << our_name_ << " defined in file '" << filename << "' at line " << line_no << " has too many items or is not terminated with an " << "empty string." << std::endl; //std::exit(1); } return true; } static const std::string & get_full_qualified_name() { return our_name_; } static std::string get_name() { std::string::size_type idx = our_name_.find_last_of(":"); if ( idx == std::string::npos ) { return our_name_; } else { return our_name_.substr( idx + 1 ); } } private: ENUM value_; static const char ** our_strings_ ; static std::string our_name_ ; static bool our_verified_flag_; }; /** ostream operator for enumeration * @relates mapnik::enumeration */ template <class ENUM, int THE_MAX> std::ostream & operator<<(std::ostream & os, const mapnik::enumeration<ENUM, THE_MAX> & e) { e.print( os ); return os; } /** istream operator for enumeration * @relates mapnik::enumeration */ template <class ENUM, int THE_MAX> std::istream & operator>>(std::istream & is, mapnik::enumeration<ENUM, THE_MAX> & e) { e.parse( is ); return is; } } // end of namespace /** Helper macro. Creates a typedef. * @relates mapnik::enumeration */ #define DEFINE_ENUM( name, e) \ typedef mapnik::enumeration<e, e ## _MAX> name /** Helper macro. Runs the verify() method during static initialization. * @relates mapnik::enumeration */ #define IMPLEMENT_ENUM( name, strings ) \ template <> const char ** name ::our_strings_ = strings; \ template <> std::string name ::our_name_ = #name; \ template <> bool name ::our_verified_flag_( name ::verify(__FILE__, __LINE__)); #endif // MAPNIK_ENUMERATION_INCLUDED <|endoftext|>
<commit_before>#ifndef DYNAMICGRAPH_HPP #define DYNAMICGRAPH_HPP #include "util/deallocating_vector.hpp" #include "util/exception.hpp" #include "util/exception_utils.hpp" #include "util/integer_range.hpp" #include "util/permutation.hpp" #include "util/typedefs.hpp" #include <boost/assert.hpp> #include <cstdint> #include <algorithm> #include <atomic> #include <limits> #include <tuple> #include <vector> namespace osrm { namespace util { namespace detail { // These types need to live outside of DynamicGraph // to be not dependable. We need this for transforming graphs // with different data. template <typename EdgeIterator> struct DynamicNode { // index of the first edge EdgeIterator first_edge; // amount of edges unsigned edges; }; template <typename NodeIterator, typename EdgeDataT> struct DynamicEdge { NodeIterator target; EdgeDataT data; }; } template <typename EdgeDataT> class DynamicGraph { public: using EdgeData = EdgeDataT; using NodeIterator = std::uint32_t; using EdgeIterator = std::uint32_t; using EdgeRange = range<EdgeIterator>; using Node = detail::DynamicNode<EdgeIterator>; using Edge = detail::DynamicEdge<NodeIterator, EdgeDataT>; template <typename E> friend class DynamicGraph; class InputEdge { public: NodeIterator source; NodeIterator target; EdgeDataT data; InputEdge() : source(std::numeric_limits<NodeIterator>::max()), target(std::numeric_limits<NodeIterator>::max()) { } template <typename... Ts> InputEdge(NodeIterator source, NodeIterator target, Ts &&... data) : source(source), target(target), data(std::forward<Ts>(data)...) { } bool operator<(const InputEdge &rhs) const { return std::tie(source, target) < std::tie(rhs.source, rhs.target); } }; DynamicGraph() : DynamicGraph(0) {} // Constructs an empty graph with a given number of nodes. explicit DynamicGraph(NodeIterator nodes) : number_of_nodes(nodes), number_of_edges(0) { node_array.reserve(number_of_nodes); node_array.resize(number_of_nodes); edge_list.reserve(number_of_nodes * 1.1); edge_list.resize(number_of_nodes); } /** * Constructs a DynamicGraph from a list of edges sorted by source node id. */ template <class ContainerT> DynamicGraph(const NodeIterator nodes, const ContainerT &graph) { // we need to cast here because DeallocatingVector does not have a valid const iterator BOOST_ASSERT(std::is_sorted(const_cast<ContainerT &>(graph).begin(), const_cast<ContainerT &>(graph).end())); number_of_nodes = nodes; number_of_edges = static_cast<EdgeIterator>(graph.size()); node_array.resize(number_of_nodes); EdgeIterator edge = 0; EdgeIterator position = 0; for (const auto node : irange(0u, number_of_nodes)) { EdgeIterator last_edge = edge; while (edge < number_of_edges && graph[edge].source == node) { ++edge; } node_array[node].first_edge = position; node_array[node].edges = edge - last_edge; position += node_array[node].edges; } edge_list.reserve(static_cast<std::size_t>(edge_list.size() * 1.1)); edge_list.resize(position); edge = 0; for (const auto node : irange(0u, number_of_nodes)) { for (const auto i : irange(node_array[node].first_edge, node_array[node].first_edge + node_array[node].edges)) { edge_list[i].target = graph[edge].target; BOOST_ASSERT(edge_list[i].target < number_of_nodes); edge_list[i].data = graph[edge].data; ++edge; } } BOOST_ASSERT(node_array.size() == number_of_nodes); } // Copy&move for the same data // DynamicGraph(const DynamicGraph &other) { number_of_nodes = other.number_of_nodes; // atomics can't be moved this is why we need an own constructor number_of_edges = static_cast<std::uint32_t>(other.number_of_edges); node_array = other.node_array; edge_list = other.edge_list; } DynamicGraph &operator=(const DynamicGraph &other) { auto copy_other = other; *this = std::move(other); return *this; } DynamicGraph(DynamicGraph &&other) { number_of_nodes = other.number_of_nodes; // atomics can't be moved this is why we need an own constructor number_of_edges = static_cast<std::uint32_t>(other.number_of_edges); node_array = std::move(other.node_array); edge_list = std::move(other.edge_list); } DynamicGraph &operator=(DynamicGraph &&other) { number_of_nodes = other.number_of_nodes; // atomics can't be moved this is why we need an own constructor number_of_edges = static_cast<std::uint32_t>(other.number_of_edges); node_array = std::move(other.node_array); edge_list = std::move(other.edge_list); return *this; } // Removes all edges to and from nodes for which filter(node_id) returns false template <typename Pred> auto Filter(Pred filter) const & { BOOST_ASSERT(node_array.size() == number_of_nodes); DynamicGraph other; other.number_of_nodes = number_of_nodes; other.number_of_edges = static_cast<std::uint32_t>(number_of_edges); other.edge_list.reserve(edge_list.size()); other.node_array.resize(node_array.size()); NodeID node_id = 0; std::transform( node_array.begin(), node_array.end(), other.node_array.begin(), [&](const Node &node) { const EdgeIterator first_edge = other.edge_list.size(); BOOST_ASSERT(node_id < number_of_nodes); if (filter(node_id++)) { std::copy_if(edge_list.begin() + node.first_edge, edge_list.begin() + node.first_edge + node.edges, std::back_inserter(other.edge_list), [&](const auto &edge) { return filter(edge.target); }); const unsigned num_edges = other.edge_list.size() - first_edge; return Node{first_edge, num_edges}; } else { return Node{first_edge, 0}; } }); return other; } unsigned GetNumberOfNodes() const { return number_of_nodes; } unsigned GetNumberOfEdges() const { return number_of_edges; } auto GetEdgeCapacity() const { return edge_list.size(); } unsigned GetOutDegree(const NodeIterator n) const { return node_array[n].edges; } unsigned GetDirectedOutDegree(const NodeIterator n) const { unsigned degree = 0; for (const auto edge : irange(BeginEdges(n), EndEdges(n))) { if (!GetEdgeData(edge).reversed) { ++degree; } } return degree; } NodeIterator GetTarget(const EdgeIterator e) const { return NodeIterator(edge_list[e].target); } void SetTarget(const EdgeIterator e, const NodeIterator n) { edge_list[e].target = n; } EdgeDataT &GetEdgeData(const EdgeIterator e) { return edge_list[e].data; } const EdgeDataT &GetEdgeData(const EdgeIterator e) const { return edge_list[e].data; } EdgeIterator BeginEdges(const NodeIterator n) const { return EdgeIterator(node_array[n].first_edge); } EdgeIterator EndEdges(const NodeIterator n) const { return EdgeIterator(node_array[n].first_edge + node_array[n].edges); } EdgeRange GetAdjacentEdgeRange(const NodeIterator node) const { return irange(BeginEdges(node), EndEdges(node)); } NodeIterator InsertNode() { node_array.emplace_back(node_array.back()); number_of_nodes += 1; return number_of_nodes; } // adds an edge. Invalidates edge iterators for the source node EdgeIterator InsertEdge(const NodeIterator from, const NodeIterator to, const EdgeDataT &data) { Node &node = node_array[from]; EdgeIterator one_beyond_last_of_node = node.edges + node.first_edge; // if we can't write at the end of this nodes edges // that is: the end is the end of the edge_list, // or the beginning of the next nodes edges if (one_beyond_last_of_node == edge_list.size() || !isDummy(one_beyond_last_of_node)) { // can we write before this nodes edges? if (node.first_edge != 0 && isDummy(node.first_edge - 1)) { node.first_edge--; edge_list[node.first_edge] = edge_list[node.first_edge + node.edges]; } else { // we have to move this nodes edges to the end of the edge_list EdgeIterator newFirstEdge = (EdgeIterator)edge_list.size(); unsigned newSize = node.edges * 1.1 + 2; EdgeIterator requiredCapacity = newSize + edge_list.size(); EdgeIterator oldCapacity = edge_list.capacity(); // make sure there is enough space at the end if (requiredCapacity >= oldCapacity) { edge_list.reserve(requiredCapacity * 1.1); } edge_list.resize(edge_list.size() + newSize); // move the edges over and invalidate the old ones for (const auto i : irange(0u, node.edges)) { edge_list[newFirstEdge + i] = edge_list[node.first_edge + i]; makeDummy(node.first_edge + i); } // invalidate until the end of edge_list for (const auto i : irange(node.edges + 1, newSize)) { makeDummy(newFirstEdge + i); } node.first_edge = newFirstEdge; } } // get the position for the edge that is to be inserted // and write it Edge &edge = edge_list[node.first_edge + node.edges]; edge.target = to; edge.data = data; ++number_of_edges; ++node.edges; return EdgeIterator(node.first_edge + node.edges); } // removes an edge. Invalidates edge iterators for the source node void DeleteEdge(const NodeIterator source, const EdgeIterator e) { Node &node = node_array[source]; --number_of_edges; --node.edges; BOOST_ASSERT(std::numeric_limits<unsigned>::max() != node.edges); const unsigned last = node.first_edge + node.edges; BOOST_ASSERT(std::numeric_limits<unsigned>::max() != last); // swap with last edge edge_list[e] = edge_list[last]; makeDummy(last); } // removes all edges (source,target) int32_t DeleteEdgesTo(const NodeIterator source, const NodeIterator target) { int32_t deleted = 0; for (EdgeIterator i = BeginEdges(source), iend = EndEdges(source); i < iend - deleted; ++i) { if (edge_list[i].target == target) { do { deleted++; edge_list[i] = edge_list[iend - deleted]; makeDummy(iend - deleted); } while (i < iend - deleted && edge_list[i].target == target); } } number_of_edges -= deleted; node_array[source].edges -= deleted; return deleted; } // searches for a specific edge EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const { for (const auto i : irange(BeginEdges(from), EndEdges(from))) { if (to == edge_list[i].target) { return i; } } return SPECIAL_EDGEID; } // searches for a specific edge EdgeIterator FindSmallestEdge(const NodeIterator from, const NodeIterator to) const { EdgeIterator smallest_edge = SPECIAL_EDGEID; EdgeWeight smallest_weight = INVALID_EDGE_WEIGHT; for (auto edge : GetAdjacentEdgeRange(from)) { const NodeID target = GetTarget(edge); const EdgeWeight weight = GetEdgeData(edge).distance; if (target == to && weight < smallest_weight) { smallest_edge = edge; smallest_weight = weight; } } return smallest_edge; } EdgeIterator FindEdgeInEitherDirection(const NodeIterator from, const NodeIterator to) const { EdgeIterator tmp = FindEdge(from, to); return (SPECIAL_NODEID != tmp ? tmp : FindEdge(to, from)); } EdgeIterator FindEdgeIndicateIfReverse(const NodeIterator from, const NodeIterator to, bool &result) const { EdgeIterator current_iterator = FindEdge(from, to); if (SPECIAL_NODEID == current_iterator) { current_iterator = FindEdge(to, from); if (SPECIAL_NODEID != current_iterator) { result = true; } } return current_iterator; } void Renumber(const std::vector<NodeID> &old_to_new_node) { // permutate everything but the sentinel util::inplacePermutation(node_array.begin(), node_array.end(), old_to_new_node); // Build up edge permutation EdgeID new_edge_index = 0; std::vector<EdgeID> old_to_new_edge(edge_list.size(), SPECIAL_EDGEID); for (auto node : util::irange<NodeID>(0, number_of_nodes)) { auto new_first_edge = new_edge_index; // move all filled edges for (auto edge : GetAdjacentEdgeRange(node)) { if (new_edge_index == std::numeric_limits<EdgeID>::max()) { throw util::exception("There are too many edges, OSRM only supports 2^32" + SOURCE_REF); } edge_list[edge].target = old_to_new_node[edge_list[edge].target]; BOOST_ASSERT(edge_list[edge].target != SPECIAL_NODEID); old_to_new_edge[edge] = new_edge_index++; } node_array[node].first_edge = new_first_edge; } auto number_of_valid_edges = new_edge_index; // move all dummy edges to the end of the renumbered range for (auto edge : util::irange<NodeID>(0, edge_list.size())) { if (old_to_new_edge[edge] == SPECIAL_EDGEID) { BOOST_ASSERT(isDummy(edge)); old_to_new_edge[edge] = new_edge_index++; } } BOOST_ASSERT(std::find(old_to_new_edge.begin(), old_to_new_edge.end(), SPECIAL_EDGEID) == old_to_new_edge.end()); util::inplacePermutation(edge_list.begin(), edge_list.end(), old_to_new_edge); // Remove useless dummy nodes at the end edge_list.resize(number_of_valid_edges); number_of_edges = number_of_valid_edges; } protected: bool isDummy(const EdgeIterator edge) const { return edge_list[edge].target == (std::numeric_limits<NodeIterator>::max)(); } void makeDummy(const EdgeIterator edge) { edge_list[edge].target = (std::numeric_limits<NodeIterator>::max)(); } NodeIterator number_of_nodes; std::atomic_uint number_of_edges; std::vector<Node> node_array; DeallocatingVector<Edge> edge_list; }; } } #endif // DYNAMICGRAPH_HPP <commit_msg>Remove dummy edges before inplace permutation<commit_after>#ifndef DYNAMICGRAPH_HPP #define DYNAMICGRAPH_HPP #include "util/deallocating_vector.hpp" #include "util/exception.hpp" #include "util/exception_utils.hpp" #include "util/integer_range.hpp" #include "util/permutation.hpp" #include "util/typedefs.hpp" #include <boost/assert.hpp> #include <cstdint> #include <algorithm> #include <atomic> #include <limits> #include <tuple> #include <vector> namespace osrm { namespace util { namespace detail { // These types need to live outside of DynamicGraph // to be not dependable. We need this for transforming graphs // with different data. template <typename EdgeIterator> struct DynamicNode { // index of the first edge EdgeIterator first_edge; // amount of edges unsigned edges; }; template <typename NodeIterator, typename EdgeDataT> struct DynamicEdge { NodeIterator target; EdgeDataT data; }; } template <typename EdgeDataT> class DynamicGraph { public: using EdgeData = EdgeDataT; using NodeIterator = std::uint32_t; using EdgeIterator = std::uint32_t; using EdgeRange = range<EdgeIterator>; using Node = detail::DynamicNode<EdgeIterator>; using Edge = detail::DynamicEdge<NodeIterator, EdgeDataT>; template <typename E> friend class DynamicGraph; class InputEdge { public: NodeIterator source; NodeIterator target; EdgeDataT data; InputEdge() : source(std::numeric_limits<NodeIterator>::max()), target(std::numeric_limits<NodeIterator>::max()) { } template <typename... Ts> InputEdge(NodeIterator source, NodeIterator target, Ts &&... data) : source(source), target(target), data(std::forward<Ts>(data)...) { } bool operator<(const InputEdge &rhs) const { return std::tie(source, target) < std::tie(rhs.source, rhs.target); } }; DynamicGraph() : DynamicGraph(0) {} // Constructs an empty graph with a given number of nodes. explicit DynamicGraph(NodeIterator nodes) : number_of_nodes(nodes), number_of_edges(0) { node_array.reserve(number_of_nodes); node_array.resize(number_of_nodes); edge_list.reserve(number_of_nodes * 1.1); edge_list.resize(number_of_nodes); } /** * Constructs a DynamicGraph from a list of edges sorted by source node id. */ template <class ContainerT> DynamicGraph(const NodeIterator nodes, const ContainerT &graph) { // we need to cast here because DeallocatingVector does not have a valid const iterator BOOST_ASSERT(std::is_sorted(const_cast<ContainerT &>(graph).begin(), const_cast<ContainerT &>(graph).end())); number_of_nodes = nodes; number_of_edges = static_cast<EdgeIterator>(graph.size()); node_array.resize(number_of_nodes); EdgeIterator edge = 0; EdgeIterator position = 0; for (const auto node : irange(0u, number_of_nodes)) { EdgeIterator last_edge = edge; while (edge < number_of_edges && graph[edge].source == node) { ++edge; } node_array[node].first_edge = position; node_array[node].edges = edge - last_edge; position += node_array[node].edges; } edge_list.reserve(static_cast<std::size_t>(edge_list.size() * 1.1)); edge_list.resize(position); edge = 0; for (const auto node : irange(0u, number_of_nodes)) { for (const auto i : irange(node_array[node].first_edge, node_array[node].first_edge + node_array[node].edges)) { edge_list[i].target = graph[edge].target; BOOST_ASSERT(edge_list[i].target < number_of_nodes); edge_list[i].data = graph[edge].data; ++edge; } } BOOST_ASSERT(node_array.size() == number_of_nodes); } // Copy&move for the same data // DynamicGraph(const DynamicGraph &other) { number_of_nodes = other.number_of_nodes; // atomics can't be moved this is why we need an own constructor number_of_edges = static_cast<std::uint32_t>(other.number_of_edges); node_array = other.node_array; edge_list = other.edge_list; } DynamicGraph &operator=(const DynamicGraph &other) { auto copy_other = other; *this = std::move(other); return *this; } DynamicGraph(DynamicGraph &&other) { number_of_nodes = other.number_of_nodes; // atomics can't be moved this is why we need an own constructor number_of_edges = static_cast<std::uint32_t>(other.number_of_edges); node_array = std::move(other.node_array); edge_list = std::move(other.edge_list); } DynamicGraph &operator=(DynamicGraph &&other) { number_of_nodes = other.number_of_nodes; // atomics can't be moved this is why we need an own constructor number_of_edges = static_cast<std::uint32_t>(other.number_of_edges); node_array = std::move(other.node_array); edge_list = std::move(other.edge_list); return *this; } // Removes all edges to and from nodes for which filter(node_id) returns false template <typename Pred> auto Filter(Pred filter) const & { BOOST_ASSERT(node_array.size() == number_of_nodes); DynamicGraph other; other.number_of_nodes = number_of_nodes; other.number_of_edges = static_cast<std::uint32_t>(number_of_edges); other.edge_list.reserve(edge_list.size()); other.node_array.resize(node_array.size()); NodeID node_id = 0; std::transform( node_array.begin(), node_array.end(), other.node_array.begin(), [&](const Node &node) { const EdgeIterator first_edge = other.edge_list.size(); BOOST_ASSERT(node_id < number_of_nodes); if (filter(node_id++)) { std::copy_if(edge_list.begin() + node.first_edge, edge_list.begin() + node.first_edge + node.edges, std::back_inserter(other.edge_list), [&](const auto &edge) { return filter(edge.target); }); const unsigned num_edges = other.edge_list.size() - first_edge; return Node{first_edge, num_edges}; } else { return Node{first_edge, 0}; } }); return other; } unsigned GetNumberOfNodes() const { return number_of_nodes; } unsigned GetNumberOfEdges() const { return number_of_edges; } auto GetEdgeCapacity() const { return edge_list.size(); } unsigned GetOutDegree(const NodeIterator n) const { return node_array[n].edges; } unsigned GetDirectedOutDegree(const NodeIterator n) const { unsigned degree = 0; for (const auto edge : irange(BeginEdges(n), EndEdges(n))) { if (!GetEdgeData(edge).reversed) { ++degree; } } return degree; } NodeIterator GetTarget(const EdgeIterator e) const { return NodeIterator(edge_list[e].target); } void SetTarget(const EdgeIterator e, const NodeIterator n) { edge_list[e].target = n; } EdgeDataT &GetEdgeData(const EdgeIterator e) { return edge_list[e].data; } const EdgeDataT &GetEdgeData(const EdgeIterator e) const { return edge_list[e].data; } EdgeIterator BeginEdges(const NodeIterator n) const { return EdgeIterator(node_array[n].first_edge); } EdgeIterator EndEdges(const NodeIterator n) const { return EdgeIterator(node_array[n].first_edge + node_array[n].edges); } EdgeRange GetAdjacentEdgeRange(const NodeIterator node) const { return irange(BeginEdges(node), EndEdges(node)); } NodeIterator InsertNode() { node_array.emplace_back(node_array.back()); number_of_nodes += 1; return number_of_nodes; } // adds an edge. Invalidates edge iterators for the source node EdgeIterator InsertEdge(const NodeIterator from, const NodeIterator to, const EdgeDataT &data) { Node &node = node_array[from]; EdgeIterator one_beyond_last_of_node = node.edges + node.first_edge; // if we can't write at the end of this nodes edges // that is: the end is the end of the edge_list, // or the beginning of the next nodes edges if (one_beyond_last_of_node == edge_list.size() || !isDummy(one_beyond_last_of_node)) { // can we write before this nodes edges? if (node.first_edge != 0 && isDummy(node.first_edge - 1)) { node.first_edge--; edge_list[node.first_edge] = edge_list[node.first_edge + node.edges]; } else { // we have to move this nodes edges to the end of the edge_list EdgeIterator newFirstEdge = (EdgeIterator)edge_list.size(); unsigned newSize = node.edges * 1.1 + 2; EdgeIterator requiredCapacity = newSize + edge_list.size(); EdgeIterator oldCapacity = edge_list.capacity(); // make sure there is enough space at the end if (requiredCapacity >= oldCapacity) { edge_list.reserve(requiredCapacity * 1.1); } edge_list.resize(edge_list.size() + newSize); // move the edges over and invalidate the old ones for (const auto i : irange(0u, node.edges)) { edge_list[newFirstEdge + i] = edge_list[node.first_edge + i]; makeDummy(node.first_edge + i); } // invalidate until the end of edge_list for (const auto i : irange(node.edges + 1, newSize)) { makeDummy(newFirstEdge + i); } node.first_edge = newFirstEdge; } } // get the position for the edge that is to be inserted // and write it Edge &edge = edge_list[node.first_edge + node.edges]; edge.target = to; edge.data = data; ++number_of_edges; ++node.edges; return EdgeIterator(node.first_edge + node.edges); } // removes an edge. Invalidates edge iterators for the source node void DeleteEdge(const NodeIterator source, const EdgeIterator e) { Node &node = node_array[source]; --number_of_edges; --node.edges; BOOST_ASSERT(std::numeric_limits<unsigned>::max() != node.edges); const unsigned last = node.first_edge + node.edges; BOOST_ASSERT(std::numeric_limits<unsigned>::max() != last); // swap with last edge edge_list[e] = edge_list[last]; makeDummy(last); } // removes all edges (source,target) int32_t DeleteEdgesTo(const NodeIterator source, const NodeIterator target) { int32_t deleted = 0; for (EdgeIterator i = BeginEdges(source), iend = EndEdges(source); i < iend - deleted; ++i) { if (edge_list[i].target == target) { do { deleted++; edge_list[i] = edge_list[iend - deleted]; makeDummy(iend - deleted); } while (i < iend - deleted && edge_list[i].target == target); } } number_of_edges -= deleted; node_array[source].edges -= deleted; return deleted; } // searches for a specific edge EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const { for (const auto i : irange(BeginEdges(from), EndEdges(from))) { if (to == edge_list[i].target) { return i; } } return SPECIAL_EDGEID; } // searches for a specific edge EdgeIterator FindSmallestEdge(const NodeIterator from, const NodeIterator to) const { EdgeIterator smallest_edge = SPECIAL_EDGEID; EdgeWeight smallest_weight = INVALID_EDGE_WEIGHT; for (auto edge : GetAdjacentEdgeRange(from)) { const NodeID target = GetTarget(edge); const EdgeWeight weight = GetEdgeData(edge).distance; if (target == to && weight < smallest_weight) { smallest_edge = edge; smallest_weight = weight; } } return smallest_edge; } EdgeIterator FindEdgeInEitherDirection(const NodeIterator from, const NodeIterator to) const { EdgeIterator tmp = FindEdge(from, to); return (SPECIAL_NODEID != tmp ? tmp : FindEdge(to, from)); } EdgeIterator FindEdgeIndicateIfReverse(const NodeIterator from, const NodeIterator to, bool &result) const { EdgeIterator current_iterator = FindEdge(from, to); if (SPECIAL_NODEID == current_iterator) { current_iterator = FindEdge(to, from); if (SPECIAL_NODEID != current_iterator) { result = true; } } return current_iterator; } void Renumber(const std::vector<NodeID> &old_to_new_node) { // permutate everything but the sentinel util::inplacePermutation(node_array.begin(), node_array.end(), old_to_new_node); // Build up edge permutation if (edge_list.size() >= std::numeric_limits<EdgeID>::max()) { throw util::exception("There are too many edges, OSRM only supports 2^32" + SOURCE_REF); } EdgeID new_edge_index = 0; std::vector<EdgeID> old_to_new_edge(edge_list.size(), SPECIAL_EDGEID); for (auto node : util::irange<NodeID>(0, number_of_nodes)) { auto new_first_edge = new_edge_index; // move all filled edges for (auto edge : GetAdjacentEdgeRange(node)) { edge_list[edge].target = old_to_new_node[edge_list[edge].target]; BOOST_ASSERT(edge_list[edge].target != SPECIAL_NODEID); old_to_new_edge[edge] = new_edge_index++; } node_array[node].first_edge = new_first_edge; } auto number_of_valid_edges = new_edge_index; // move all dummy edges to the end of the renumbered range for (auto edge : util::irange<NodeID>(0, edge_list.size())) { if (old_to_new_edge[edge] == SPECIAL_EDGEID) { BOOST_ASSERT(isDummy(edge)); old_to_new_edge[edge] = new_edge_index++; } } BOOST_ASSERT(std::find(old_to_new_edge.begin(), old_to_new_edge.end(), SPECIAL_EDGEID) == old_to_new_edge.end()); util::inplacePermutation(edge_list.begin(), edge_list.end(), old_to_new_edge); // Remove useless dummy nodes at the end edge_list.resize(number_of_valid_edges); number_of_edges = number_of_valid_edges; } protected: bool isDummy(const EdgeIterator edge) const { return edge_list[edge].target == (std::numeric_limits<NodeIterator>::max)(); } void makeDummy(const EdgeIterator edge) { edge_list[edge].target = (std::numeric_limits<NodeIterator>::max)(); } NodeIterator number_of_nodes; std::atomic_uint number_of_edges; std::vector<Node> node_array; DeallocatingVector<Edge> edge_list; }; } } #endif // DYNAMICGRAPH_HPP <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <sstream> #include <fstream> std::ofstream outputfile("output.txt"); void print_reverse(const std::string &sentence, int iteration) { std::vector<std::string> words; std::stringstream stream(sentence); outputfile << "Case #" << iteration << ": "; for(std::string word; stream >> word;) words.push_back(word); for(std::vector<std::string>::reverse_iterator it = words.rbegin(); it != words.rend(); ++it) outputfile << *it << " "; } int main() { std::string sentence; std::string fileName; std::string word; int cases = 0; int cnt = 1; std::cout << "Enter Input File Name: "; getline(std::cin,fileName); std::ifstream streamIn; streamIn.open(fileName); if(!streamIn) { std::cout << "Error Opening File.\n"; return -1; } streamIn >> cases; streamIn.ignore(); while(!streamIn.fail() && cnt != cases+1) { getline(streamIn,sentence); print_reverse(sentence,cnt); outputfile << "\n"; ++cnt; } return 0; } <commit_msg>Update reverse_words.cpp<commit_after>#include <iostream> #include <string> #include <vector> #include <sstream> #include <fstream> std::ofstream outputfile("output.txt"); void print_reverse(const std::string &sentence, int iteration) { std::vector<std::string> words; std::stringstream stream(sentence); outputfile << "Case #" << iteration << ": "; for(std::string word; stream >> word;) words.push_back(word); for(std::vector<std::string>::reverse_iterator it = words.rbegin(); it != words.rend(); ++it) outputfile << *it << " "; } int main() { std::string sentence; std::string fileName; std::string word; int cases = 0; int cnt = 1; std::cout << "Enter Input File Name: "; getline(std::cin,fileName); std::ifstream streamIn; streamIn.open(fileName); if(!streamIn) { std::cout << "Error Opening File.\n"; return -1; } streamIn >> cases; streamIn.ignore(); while(!streamIn.fail() && cnt != cases+1) { getline(streamIn,sentence); print_reverse(sentence,cnt); outputfile << "\n"; ++cnt; } return 0; } <|endoftext|>
<commit_before>#include <time.h> class diddy { public: // only accurate to 1 second static int systemMillisecs() { time_t seconds; seconds = time (NULL); return seconds * 1000; } static void flushKeys() { for( int i=0;i<512;++i ){ app->input->keyStates[i]&=0x100; } } static int getUpdateRate() { return app->updateRate; } static void showMouse() { } static void hideMouse() { } static void setMouse(int x, int y) { } static void showKeyboard() { } static void launchBrowser(String address) { } static void launchEmail(String email, String subject, String text) { } }; <commit_msg>Added launchBrowser functionality to iOS.<commit_after>#include <time.h> class diddy { public: // only accurate to 1 second static int systemMillisecs() { time_t seconds; seconds = time (NULL); return seconds * 1000; } static void flushKeys() { for( int i=0;i<512;++i ){ app->input->keyStates[i]&=0x100; } } static int getUpdateRate() { return app->updateRate; } static void showMouse() { } static void hideMouse() { } static void setMouse(int x, int y) { } static void showKeyboard() { } static void launchBrowser(String address) { NSString *stringUrl = tonsstr(address); NSURL *nsUrl = [NSURL URLWithString:stringUrl]; [[UIApplication sharedApplication] openURL:nsUrl]; } static void launchEmail(String email, String subject, String text) { } }; <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2008 Thomas Krennwallner * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file EvaluateExtatom.cpp * @author Thomas Krennwallner * @date Sat Jan 19 20:18:36 CEST 2008 * * @brief Evaluate external atoms. * * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex/EvaluateExtatom.h" #include <iostream> #include <sstream> #include <algorithm> DLVHEX_NAMESPACE_BEGIN EvaluateExtatom::EvaluateExtatom(const ExternalAtom* ea, PluginContainer& c) : externalAtom(ea), container(c) { } void EvaluateExtatom::groundInputList(const AtomSet& i, std::vector<Tuple>& inputArguments) const { // // first, we assume that we only take the original input list // inputArguments.push_back(externalAtom->getInputTerms()); // // did we create an auxiliary predicate before? // if (!externalAtom->getAuxPredicate().empty()) { // // now that we know there are variable input arguments // (otherwise there wouldn't be such a dependency), we can start // over with the input list again and construct it from the // result of the auxiliary rules // inputArguments.clear(); AtomSet arglist; // // get all the facts from i that match the auxiliary head atom // the arguments of those facts will be our input lists! // i.matchPredicate(externalAtom->getAuxPredicate(), arglist); for (AtomSet::const_iterator argi = arglist.begin(); argi != arglist.end(); ++argi) { inputArguments.push_back(argi->getArguments()); } } } /** * @brief Check the answers returned from the external atom, and * remove ill-formed tuples. * * Check whether the answers in the output list are * (1) ground * (2) conform to the output pattern, i.e., * &rdf[uri](S,rdf:subClassOf,O) shall only return tuples of form * <s, rdf:subClassOf, o>, and not for instance <s, * rdf:subPropertyOf, o>, we have to filter them out (do we?) */ struct CheckOutput : public std::binary_function<const Term, const Term, bool> { bool operator() (const Term& t1, const Term& t2) const { // answers must be ground, otw. programming error in the plugin assert(t1.isInt() || t1.isString() || t1.isSymbol()); // pattern tuple values must coincide if (t2.isInt() || t2.isString() || t2.isSymbol()) { return t1 == t2; } else // t2.isVariable() -> t1 is a variable binding for t2 { return true; } } }; void EvaluateExtatom::evaluate(const AtomSet& i, AtomSet& result) const throw (PluginError) { boost::shared_ptr<PluginAtom> pluginAtom = container.getAtom(externalAtom->getFunctionName()); if (!pluginAtom) { throw PluginError("Could not find plugin for external atom " + externalAtom->getFunctionName()); } std::vector<Tuple> inputArguments; groundInputList(i, inputArguments); std::string fnc = externalAtom->getFunctionName(); // // evaluate external atom for externalAtomch input tuple we have now // for (std::vector<Tuple>::const_iterator inputi = inputArguments.begin(); inputi != inputArguments.end(); ++inputi) { AtomSet inputSet; // // extract input set from i according to the input parameters // for (unsigned s = 0; s < inputi->size(); s++) { const Term* inputTerm = &(*inputi)[s]; // // at this point, the entire input list must be ground! // assert(!inputTerm->isVariable()); switch(pluginAtom->getInputType(s)) { case PluginAtom::CONSTANT: // // nothing to do, the constant will be passed directly to the plugin // break; case PluginAtom::PREDICATE: // // collect all facts from interpretation that we need for the input // of the external atom // /// @todo: since matchpredicate doesn't neet the output list, do we /// need that factlist here? i.matchPredicate(inputTerm->getString(), inputSet); break; default: // // not a specified type - worst case, now we have to pass the // entire interpretation. we simply overwrite a previously // created inputSet, because there can't be specified input // types after this one anyway - TUPLE must always be after // CONSTANT and PREDICATE, see PluginAtom! // //inputSet = i; break; } } // // build a query object: // - interpretation // - input list // - actual arguments of the external atom (maybe it is partly ground, // then the plugin can be more efficient) // PluginAtom::Query query(inputSet, *inputi, externalAtom->getArguments()); PluginAtom::Answer answer; try { pluginAtom->retrieve(query, answer); } catch (PluginError& e) { std::ostringstream atomstr; atomstr << externalAtom->getFunctionName() << "[" << externalAtom->getInputTerms() << "](" << externalAtom->getArguments() << ")" << " in line " << externalAtom->getLine(); e.setContext(atomstr.str()); throw e; } // // build result with the replacement name for each answer tuple // boost::shared_ptr<std::vector<Tuple> > answers = answer.getTuples(); for (std::vector<Tuple>::const_iterator s = answers->begin(); s != answers->end(); ++s) { if (s->size() != externalAtom->getArguments().size()) { throw PluginError("External atom " + externalAtom->getFunctionName() + " returned tuple of incompatible size."); } // check if this answer from pluginatom conforms to the external atom's arguments std::pair<Tuple::const_iterator,Tuple::const_iterator> mismatched = std::mismatch(s->begin(), s->end(), externalAtom->getArguments().begin(), CheckOutput() ); if (mismatched.first == s->end()) // no mismatch found -> add this tuple to the result { // the replacement atom contains both the input and the output list! // (*inputi must be ground here, since it comes from // groundInputList(i, inputArguments)) Tuple resultTuple(*inputi); // add output list resultTuple.insert(resultTuple.end(), s->begin(), s->end()); // setup new atom with appropriate replacement name AtomPtr ap(new Atom(externalAtom->getReplacementName(), resultTuple)); result.insert(ap); } else { // found a mismatch, ignore this answer tuple } } } } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <commit_msg>Code cleanups and documentation.<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2008 Thomas Krennwallner * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file EvaluateExtatom.cpp * @author Thomas Krennwallner * @date Sat Jan 19 20:18:36 CEST 2008 * * @brief Evaluate external atoms. * * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex/EvaluateExtatom.h" #include <iostream> #include <sstream> #include <algorithm> DLVHEX_NAMESPACE_BEGIN EvaluateExtatom::EvaluateExtatom(const ExternalAtom* ea, PluginContainer& c) : externalAtom(ea), container(c) { } void EvaluateExtatom::groundInputList(const AtomSet& i, std::vector<Tuple>& inputArguments) const { if (externalAtom->pureGroundInput()) { // take the original input list inputArguments.push_back(externalAtom->getInputTerms()); } else // nonground input list { // // now that we know there are variable input arguments // (otherwise there wouldn't be such a dependency), we can start // constructing the input list from the result of the auxiliary // rules // AtomSet arglist; // // get all the facts from i that match the auxiliary head atom // the arguments of those facts will be our input lists! // i.matchPredicate(externalAtom->getAuxPredicate(), arglist); // // for each auxiliary fact we create a new input list for the // external atom, i.e., we evaluate our external atom n = // |arglist| times. // for (AtomSet::const_iterator argi = arglist.begin(); argi != arglist.end(); ++argi) { inputArguments.push_back(argi->getArguments()); } } } /** * @brief Check the answers returned from the external atom, and * remove ill-formed tuples. * * Check whether the answers in the output list are * (1) ground * (2) conform to the output pattern, i.e., * &rdf[uri](S,rdf:subClassOf,O) shall only return tuples of form * <s, rdf:subClassOf, o>, and not for instance <s, * rdf:subPropertyOf, o>, we have to filter them out (do we?) */ struct CheckOutput : public std::binary_function<const Term, const Term, bool> { bool operator() (const Term& t1, const Term& t2) const { // answers must be ground, otw. programming error in the plugin assert(t1.isInt() || t1.isString() || t1.isSymbol()); // pattern tuple values must coincide if (t2.isInt() || t2.isString() || t2.isSymbol()) { return t1 == t2; } else // t2.isVariable() -> t1 is a variable binding for t2 { return true; } } }; void EvaluateExtatom::evaluate(const AtomSet& i, AtomSet& result) const throw (PluginError) { const std::string& fnc = externalAtom->getFunctionName(); boost::shared_ptr<PluginAtom> pluginAtom = container.getAtom(fnc); if (!pluginAtom) { throw PluginError("Could not find plugin for external atom " + fnc); } std::vector<Tuple> inputArguments; groundInputList(i, inputArguments); // // evaluate external atom for each input tuple we have extracted in // groundInputList() // for (std::vector<Tuple>::const_iterator inputi = inputArguments.begin(); inputi != inputArguments.end(); ++inputi) { AtomSet inputSet; const std::vector<PluginAtom::InputType>& inputtypes = pluginAtom->getInputTypes(); Tuple::const_iterator termit = inputi->begin(); // // extract input set from i according to the input parameters // for (std::vector<PluginAtom::InputType>::const_iterator typeit = inputtypes.begin(); termit != inputi->end() && typeit != inputtypes.end(); ++termit, ++typeit) { // // at this point, the entire input list must be ground! // assert(!termit->isVariable()); switch(*typeit) { case PluginAtom::CONSTANT: // // nothing to do, the constant will be passed directly to the plugin // break; case PluginAtom::PREDICATE: // // collect all facts from interpretation that we need for the input // of the external atom // /// @todo: since matchpredicate doesn't neet the output list, do we /// need that factlist here? i.matchPredicate(termit->getString(), inputSet); break; default: // // not a specified type - worst case, now we have to pass the // entire interpretation. we simply overwrite a previously // created inputSet, because there can't be specified input // types after this one anyway - TUPLE must always be after // CONSTANT and PREDICATE, see PluginAtom! // //inputSet = i; break; } } // // build a query object: // - interpretation // - input list // - actual arguments of the external atom (maybe it is partly ground, // then the plugin can be more efficient) // PluginAtom::Query query(inputSet, *inputi, externalAtom->getArguments()); PluginAtom::Answer answer; try { pluginAtom->retrieve(query, answer); } catch (PluginError& e) { std::ostringstream atomstr; atomstr << externalAtom->getFunctionName() << "[" << externalAtom->getInputTerms() << "](" << externalAtom->getArguments() << ")" << " in line " << externalAtom->getLine(); e.setContext(atomstr.str()); throw e; } // // build result with the replacement name for each answer tuple // boost::shared_ptr<std::vector<Tuple> > answers = answer.getTuples(); for (std::vector<Tuple>::const_iterator s = answers->begin(); s != answers->end(); ++s) { if (s->size() != externalAtom->getArguments().size()) { throw PluginError("External atom " + externalAtom->getFunctionName() + " returned tuple of incompatible size."); } // check if this answer from pluginatom conforms to the external atom's arguments std::pair<Tuple::const_iterator,Tuple::const_iterator> mismatched = std::mismatch(s->begin(), s->end(), externalAtom->getArguments().begin(), CheckOutput() ); if (mismatched.first == s->end()) // no mismatch found -> add this tuple to the result { // the replacement atom contains both the input and the output list! // (*inputi must be ground here, since it comes from // groundInputList(i, inputArguments)) Tuple resultTuple(*inputi); // add output list resultTuple.insert(resultTuple.end(), s->begin(), s->end()); // setup new atom with appropriate replacement name AtomPtr ap(new Atom(externalAtom->getReplacementName(), resultTuple)); result.insert(ap); } else { // found a mismatch, ignore this answer tuple } } } } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <|endoftext|>
<commit_before><commit_msg>fix<commit_after><|endoftext|>
<commit_before>/* dtkMath.tpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Wed Mar 9 11:05:40 2011 (+0100) * Version: $Id$ * Last-Updated: Thu Sep 13 16:25:21 2012 (+0200) * By: tkloczko * Update #: 94 */ /* Commentary: * */ /* Change log: * */ #ifndef DTKMATH_TPP #define DTKMATH_TPP #include "dtkMatrixSquared.h" #include "dtkQuaternion.h" #include "dtkVector3D.h" #include <math.h> template<class T> T dtkDeg2Rad(const T& value) { return M_PI * value / 180.; } template<class T> T dtkRad2Deg(const T& value) { return 180. * value / M_PI; } template <class T> dtkVector3D<T> dtkRotate(const dtkQuaternion<T>& quaternion, const dtkVector3D<T>& vector) { dtkQuaternion<T> q(quaternion*dtkQuaternion<T>(vector[0], vector[1], vector[2], 0)*dtkInverse<T>(quaternion)); return dtkVector3D<T>(q[0], q[1], q[2]); } //! dtkMixedProduct(const dtkVector3D &v0, const dtkVector3D &v1, const dtkVector3D &v2) /*! * This function calculates the mixed product (also called triple scalar product) * formed by three dtkVector3D. */ template <class T> T dtkMixedProduct(const dtkVector3D<T> &v0, const dtkVector3D<T> &v1, const dtkVector3D<T> &v2) { dtkVector3D<T> v; v.storeOuterProduct(v1, v2); return (v0*v); } //! dtkQuaternionFromEulerAxisAndAngle(const dtkVector3D<T> &dtkVecEulerAxis, const T &rotateEulerAngle) /*! * This function returns a quaternion representing a rigid body's * attitude from its Euler axis and angle. * NOTE: Argument vector dtkVecEulerAxis MUST be a unit vector. */ template <class T> dtkQuaternion<T> dtkQuaternionFromAxisAngle(const dtkVector3D<T> &axis, const T &angle) { dtkVector3D<T> v = axis.unit(); return dtkQuaternion<T>(1.0, dtkVector3D<T>(axis[0], axis[1], axis[2]), dtkDeg2Rad(angle/(T)2)); } template <class T> dtkQuaternion<T> dtkQuaternionFromHPR(T h, T p, T r) { T cosH, sinH, cosP, sinP, cosR, sinR; T half_r, half_p, half_h; /* put angles into radians and divide by two, since all angles in formula * are (angle/2) */ half_h = dtkDeg2Rad(h / 2.0); half_p = dtkDeg2Rad(p / 2.0); half_r = dtkDeg2Rad(r / 2.0); cosH = cos(half_h); sinH = sin(half_h); cosP = cos(half_p); sinP = sin(half_p); cosR = cos(half_r); sinR = sin(half_r); return dtkQuaternion<T>( sinR * cosP * cosH - cosR * sinP * sinH, cosR * sinP * cosH + sinR * cosP * sinH, cosR * cosP * sinH - sinR * sinP * cosH, cosR * cosP * cosH + sinR * sinP * sinH); } //! dtkEulerAxisFromQuaternion(const dtkQuaternion<T> &qtn) /*! * This function returns Euler axis from a quaternion representing a rigid body's * attitude. */ template <class T> dtkVector3D<T> dtkAxisFromQuaternion(const dtkQuaternion<T> &qtn) { dtkVector3D<T> axis(qtn[0], qtn[1], qtn[2]); return axis.unit(); } //! dtkQuaternionFromMatSquared(const dtkMatrixSquared<T> &mat) /*! * This function returns the quaternion corresponding to a * transformation matrix. */ template <class T> dtkQuaternion<T> dtkQuaternionFromMatSquared(const dtkMatrixSquared<T> &mat) { T sclrTmp = dtkMatrixSquaredTrace(mat); dtkQuaternion<T> qtn; if(sclrTmp > 0) { sclrTmp = 0.5*sqrt(1 + sclrTmp); qtn[0] = 0.25*(mat[1][2] - mat[2][1])/sclrTmp; qtn[1] = 0.25*(mat[2][0] - mat[0][2])/sclrTmp; qtn[2] = 0.25*(mat[0][1] - mat[1][0])/sclrTmp; qtn[3] = sclrTmp; } else { // We could be in trouble, so we have to take // precautions. NOTE: Parts of this piece of code were taken // from the example in the article "Rotating Objects Using // Quaternions" in Game Developer Magazine written by Nick // Bobick, july 3, 1998, vol. 2, issue 26. int i = 0; if (mat[1][1] > mat[0][0]) i = 1; if (mat[2][2] > mat[i][i]) i = 2; switch (i) { case 0: sclrTmp = 0.5*sqrt(1 + mat[0][0] - mat[1][1] - mat[2][2]); qtn[0] = sclrTmp; qtn[1] = 0.25*(mat[0][1] + mat[1][0])/sclrTmp; qtn[2] = 0.25*(mat[0][2] + mat[2][0])/sclrTmp; qtn[3] = 0.25*(mat[1][2] - mat[2][1])/sclrTmp; break; case 1: sclrTmp = 0.5*sqrt(1 - mat[0][0] + mat[1][1] - mat[2][2]); qtn[0] = 0.25*(mat[1][0] + mat[0][1])/sclrTmp; qtn[1] = sclrTmp; qtn[2] = 0.25*(mat[1][2] + mat[2][1])/sclrTmp; qtn[3] = 0.25*(mat[2][0] - mat[0][2])/sclrTmp; break; case 2: sclrTmp = 0.5*sqrt(1 - mat[0][0] - mat[1][1] + mat[2][2]); qtn[0] = 0.25*(mat[2][0] + mat[0][2])/sclrTmp; qtn[1] = 0.25*(mat[2][1] + mat[1][2])/sclrTmp; qtn[2] = sclrTmp; qtn[3] = 0.25*(mat[0][1] - mat[1][0])/sclrTmp; break; } } return qtn; } //! dtkEulerAngleFromQuaternion(const dtkQuaternion<T> &qtn) /*! * This function returns Euler angle from a quaternion representing a rigid body's * attitude. */ template <class T> T dtkAngleFromQuaternion(const dtkQuaternion<T> &qtn) { return 2*dtkRad2Deg(acos(qtn[3])); } //! dtkChangeOfBasis(dtkVector3D< dtkVector3D<T> >&from, dtkVector3D< dtkVector3D<T> >&to) /*! * This is a "change of basis" from the "from" frame to the "to" * frame. the "to" frame is typically the "Standard basis" frame. * The "from" is a frame that represents the current orientation * of the object in the shape of an orthonormal tripod. */ template <class T> dtkMatrixSquared<T> dtkChangeOfBasis(dtkVector3D< dtkVector3D<T> >&from, dtkVector3D< dtkVector3D<T> >&to) { dtkMatrixSquared<T> A( 3 ); enum { x , y , z }; // _X,_Y,_Z is typically the standard basis frame. // | x^_X , y^_X , z^_X | // | x^_Y , y^_Y , z^_Y | // | x^_Z , y^_Z , z^_Z | A[0][0] = from[x]*to[x]; A[0][1] = from[y]*to[x]; A[0][2] = from[z]*to[x]; A[1][0] = from[x]*to[y]; A[1][1] = from[y]*to[y]; A[1][2] = from[z]*to[y]; A[2][0] = from[x]*to[z]; A[2][1] = from[y]*to[z]; A[2][2] = from[z]*to[z]; // This is simply the transpose done manually which would save // and inverse call. // | x ^ _X , x ^ _Y , x ^ _Z | // | y ^ _X , y ^ _Y , y ^ _Z | // | z ^ _X , z ^ _Y , z ^ _Z | // And finally we return the matrix that takes the "from" frame // to the "to"/"Standard basis" frame. return A; } #endif // ///////////////////////////////////////////////////////////////// // Credits // ///////////////////////////////////////////////////////////////// // $Id: coordsys.h 165 2008-01-19 19:53:19Z hkuiper $ // CwMtx matrix and vector math library // Copyright (C) 1999-2001 Harry Kuiper // Copyright (C) 2000 Will DeVore (template conversion) // 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 <commit_msg>backport 8dfbec3c604101a18039cadd66b432ba3b5f325d (Add mixed product taking 3 double array as arguments)<commit_after>/* dtkMath.tpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Wed Mar 9 11:05:40 2011 (+0100) * Version: $Id$ * Last-Updated: mer. févr. 19 10:02:15 2014 (+0100) * By: Thibaud Kloczko * Update #: 108 */ /* Commentary: * */ /* Change log: * */ #ifndef DTKMATH_TPP #define DTKMATH_TPP #include "dtkMatrixSquared.h" #include "dtkQuaternion.h" #include "dtkVector3D.h" #include <math.h> template<class T> T dtkDeg2Rad(const T& value) { return M_PI * value / 180.; } template<class T> T dtkRad2Deg(const T& value) { return 180. * value / M_PI; } template <class T> dtkVector3D<T> dtkRotate(const dtkQuaternion<T>& quaternion, const dtkVector3D<T>& vector) { dtkQuaternion<T> q(quaternion*dtkQuaternion<T>(vector[0], vector[1], vector[2], 0)*dtkInverse<T>(quaternion)); return dtkVector3D<T>(q[0], q[1], q[2]); } //! dtkMixedProduct(const dtkVector3D &v0, const dtkVector3D &v1, const dtkVector3D &v2) /*! * This function calculates the mixed product (also called triple scalar product) * formed by three dtkVector3D. */ template <class T> T dtkMixedProduct(const dtkVector3D<T> &v0, const dtkVector3D<T> &v1, const dtkVector3D<T> &v2) { dtkVector3D<T> v; v.storeOuterProduct(v1, v2); return (v0*v); } //! dtkMixedProduct(const T v0[3], const T v1[3], const T v2[3]) /*! * This function calculates the mixed product (also called triple scalar product) * formed by three vectors v0, v1, v2. */ template <class T> inline T dtkMixedProduct(const T v0[3], const T v1[3], const T v2[3]) { return v0[0] * v1[1] * v2[2] + v1[0] * v2[1] * v0[2] + v2[0] * v0[1] * v1[2] - v0[0] * v2[1] * v1[2] - v1[0] * v0[1] * v2[2] - v2[0] * v1[1] * v0[2]; } //! dtkQuaternionFromEulerAxisAndAngle(const dtkVector3D<T> &dtkVecEulerAxis, const T &rotateEulerAngle) /*! * This function returns a quaternion representing a rigid body's * attitude from its Euler axis and angle. * NOTE: Argument vector dtkVecEulerAxis MUST be a unit vector. */ template <class T> dtkQuaternion<T> dtkQuaternionFromAxisAngle(const dtkVector3D<T> &axis, const T &angle) { dtkVector3D<T> v = axis.unit(); return dtkQuaternion<T>(1.0, dtkVector3D<T>(axis[0], axis[1], axis[2]), dtkDeg2Rad(angle/(T)2)); } template <class T> dtkQuaternion<T> dtkQuaternionFromHPR(T h, T p, T r) { T cosH, sinH, cosP, sinP, cosR, sinR; T half_r, half_p, half_h; /* put angles into radians and divide by two, since all angles in formula * are (angle/2) */ half_h = dtkDeg2Rad(h / 2.0); half_p = dtkDeg2Rad(p / 2.0); half_r = dtkDeg2Rad(r / 2.0); cosH = cos(half_h); sinH = sin(half_h); cosP = cos(half_p); sinP = sin(half_p); cosR = cos(half_r); sinR = sin(half_r); return dtkQuaternion<T>( sinR * cosP * cosH - cosR * sinP * sinH, cosR * sinP * cosH + sinR * cosP * sinH, cosR * cosP * sinH - sinR * sinP * cosH, cosR * cosP * cosH + sinR * sinP * sinH); } //! dtkEulerAxisFromQuaternion(const dtkQuaternion<T> &qtn) /*! * This function returns Euler axis from a quaternion representing a rigid body's * attitude. */ template <class T> dtkVector3D<T> dtkAxisFromQuaternion(const dtkQuaternion<T> &qtn) { dtkVector3D<T> axis(qtn[0], qtn[1], qtn[2]); return axis.unit(); } //! dtkQuaternionFromMatSquared(const dtkMatrixSquared<T> &mat) /*! * This function returns the quaternion corresponding to a * transformation matrix. */ template <class T> dtkQuaternion<T> dtkQuaternionFromMatSquared(const dtkMatrixSquared<T> &mat) { T sclrTmp = dtkMatrixSquaredTrace(mat); dtkQuaternion<T> qtn; if(sclrTmp > 0) { sclrTmp = 0.5*sqrt(1 + sclrTmp); qtn[0] = 0.25*(mat[1][2] - mat[2][1])/sclrTmp; qtn[1] = 0.25*(mat[2][0] - mat[0][2])/sclrTmp; qtn[2] = 0.25*(mat[0][1] - mat[1][0])/sclrTmp; qtn[3] = sclrTmp; } else { // We could be in trouble, so we have to take // precautions. NOTE: Parts of this piece of code were taken // from the example in the article "Rotating Objects Using // Quaternions" in Game Developer Magazine written by Nick // Bobick, july 3, 1998, vol. 2, issue 26. int i = 0; if (mat[1][1] > mat[0][0]) i = 1; if (mat[2][2] > mat[i][i]) i = 2; switch (i) { case 0: sclrTmp = 0.5*sqrt(1 + mat[0][0] - mat[1][1] - mat[2][2]); qtn[0] = sclrTmp; qtn[1] = 0.25*(mat[0][1] + mat[1][0])/sclrTmp; qtn[2] = 0.25*(mat[0][2] + mat[2][0])/sclrTmp; qtn[3] = 0.25*(mat[1][2] - mat[2][1])/sclrTmp; break; case 1: sclrTmp = 0.5*sqrt(1 - mat[0][0] + mat[1][1] - mat[2][2]); qtn[0] = 0.25*(mat[1][0] + mat[0][1])/sclrTmp; qtn[1] = sclrTmp; qtn[2] = 0.25*(mat[1][2] + mat[2][1])/sclrTmp; qtn[3] = 0.25*(mat[2][0] - mat[0][2])/sclrTmp; break; case 2: sclrTmp = 0.5*sqrt(1 - mat[0][0] - mat[1][1] + mat[2][2]); qtn[0] = 0.25*(mat[2][0] + mat[0][2])/sclrTmp; qtn[1] = 0.25*(mat[2][1] + mat[1][2])/sclrTmp; qtn[2] = sclrTmp; qtn[3] = 0.25*(mat[0][1] - mat[1][0])/sclrTmp; break; } } return qtn; } //! dtkEulerAngleFromQuaternion(const dtkQuaternion<T> &qtn) /*! * This function returns Euler angle from a quaternion representing a rigid body's * attitude. */ template <class T> T dtkAngleFromQuaternion(const dtkQuaternion<T> &qtn) { return 2*dtkRad2Deg(acos(qtn[3])); } //! dtkChangeOfBasis(dtkVector3D< dtkVector3D<T> >&from, dtkVector3D< dtkVector3D<T> >&to) /*! * This is a "change of basis" from the "from" frame to the "to" * frame. the "to" frame is typically the "Standard basis" frame. * The "from" is a frame that represents the current orientation * of the object in the shape of an orthonormal tripod. */ template <class T> dtkMatrixSquared<T> dtkChangeOfBasis(dtkVector3D< dtkVector3D<T> >&from, dtkVector3D< dtkVector3D<T> >&to) { dtkMatrixSquared<T> A( 3 ); enum { x , y , z }; // _X,_Y,_Z is typically the standard basis frame. // | x^_X , y^_X , z^_X | // | x^_Y , y^_Y , z^_Y | // | x^_Z , y^_Z , z^_Z | A[0][0] = from[x]*to[x]; A[0][1] = from[y]*to[x]; A[0][2] = from[z]*to[x]; A[1][0] = from[x]*to[y]; A[1][1] = from[y]*to[y]; A[1][2] = from[z]*to[y]; A[2][0] = from[x]*to[z]; A[2][1] = from[y]*to[z]; A[2][2] = from[z]*to[z]; // This is simply the transpose done manually which would save // and inverse call. // | x ^ _X , x ^ _Y , x ^ _Z | // | y ^ _X , y ^ _Y , y ^ _Z | // | z ^ _X , z ^ _Y , z ^ _Z | // And finally we return the matrix that takes the "from" frame // to the "to"/"Standard basis" frame. return A; } #endif // ///////////////////////////////////////////////////////////////// // Credits // ///////////////////////////////////////////////////////////////// // $Id: coordsys.h 165 2008-01-19 19:53:19Z hkuiper $ // CwMtx matrix and vector math library // Copyright (C) 1999-2001 Harry Kuiper // Copyright (C) 2000 Will DeVore (template conversion) // 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 <|endoftext|>
<commit_before>/* Copyright (C) 2004-2005 ian reinhart geiser <[email protected]> */ #include <kconfig.h> #include <kmacroexpander.h> #include <kconfiggroup.h> #include <kaboutdata.h> #include <QCommandLineOption> #include <QCommandLineParser> #include <QCoreApplication> #include <QFile> #include <QFileInfo> #include <QHash> #include <QString> #include <QStringList> #include <QTextStream> static const char classHeader[] = "/**\n" "* This file was autogenerated by kgendesignerplugin. Any changes will be lost!\n" "* The generated code in this file is licensed under the same license that the\n" "* input file.\n" "*/\n" "#include <QIcon>\n" "#include <QtDesigner/QDesignerContainerExtension>\n" "#if QT_VERSION >= 0x050500\n" "# include <QtUiPlugin/QDesignerCustomWidgetInterface>\n" "#else\n" "# include <QDesignerCustomWidgetInterface>\n" "#endif\n" "#include <qplugin.h>\n" "#include <qdebug.h>\n"; static const char collClassDef[] = "class %CollName : public QObject, public QDesignerCustomWidgetCollectionInterface\n" "{\n" " Q_OBJECT\n" " Q_INTERFACES(QDesignerCustomWidgetCollectionInterface)\n" " Q_PLUGIN_METADATA(IID \"org.qt-project.Qt.QDesignerCustomWidgetInterface\")\n" "public:\n" " %CollName(QObject *parent = nullptr);\n" " virtual ~%CollName() {}\n" " QList<QDesignerCustomWidgetInterface*> customWidgets() const Q_DECL_OVERRIDE { return m_plugins; } \n" " \n" "private:\n" " QList<QDesignerCustomWidgetInterface*> m_plugins;\n" "};\n\n" ; static const char collClassImpl[] = "%CollName::%CollName(QObject *parent)\n" " : QObject(parent)" "{\n" "%CollectionAdd\n" "}\n\n"; static const char classDef[] = "class %PluginName : public QObject, public QDesignerCustomWidgetInterface\n" "{\n" " Q_OBJECT\n" " Q_INTERFACES(QDesignerCustomWidgetInterface)\n" "public:\n" " %PluginName(QObject *parent = nullptr) :\n QObject(parent), mInitialized(false) {}\n" " virtual ~%PluginName() {}\n" " \n" " bool isContainer() const Q_DECL_OVERRIDE { return %IsContainer; }\n" " bool isInitialized() const Q_DECL_OVERRIDE { return mInitialized; }\n" " QIcon icon() const Q_DECL_OVERRIDE { return QIcon(QStringLiteral(\"%IconName\")); }\n" " QString codeTemplate() const Q_DECL_OVERRIDE { return QStringLiteral(\"%CodeTemplate\"); }\n" " QString domXml() const Q_DECL_OVERRIDE { return %DomXml; }\n" " QString group() const Q_DECL_OVERRIDE { return QStringLiteral(\"%Group\"); }\n" " QString includeFile() const Q_DECL_OVERRIDE { return QStringLiteral(\"%IncludeFile\"); }\n" " QString name() const Q_DECL_OVERRIDE { return QStringLiteral(\"%Class\"); }\n" " QString toolTip() const Q_DECL_OVERRIDE { return QStringLiteral(\"%ToolTip\"); }\n" " QString whatsThis() const Q_DECL_OVERRIDE { return QStringLiteral(\"%WhatsThis\"); }\n\n" " QWidget* createWidget( QWidget* parent ) Q_DECL_OVERRIDE \n {%CreateWidget\n }\n" " void initialize(QDesignerFormEditorInterface *core) Q_DECL_OVERRIDE \n {%Initialize\n }\n" "\n" "private:\n" " bool mInitialized;\n" "};\n\n"; static QString denamespace(const QString &str); static QString buildCollClass(KConfig &input, const QStringList &classes, const QString &group); static QString buildWidgetClass(const QString &name, KConfig &input, const QString &group); static QString buildWidgetInclude(const QString &name, KConfig &input); static void buildFile(QTextStream &stream, const QString &group, const QString &fileName, const QString &pluginName); int main(int argc, char **argv) { QCoreApplication app(argc, argv); QString description = QCoreApplication::translate("main", "Builds Qt widget plugins from an ini style description file."); const QString version = QStringLiteral("0.5"); app.setApplicationVersion(version); QCommandLineParser parser; parser.addVersionOption(); parser.addHelpOption(); parser.addPositionalArgument(QStringLiteral("file"), QCoreApplication::translate("main", "Input file.")); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("o"), QCoreApplication::translate("main", "Output file."), QStringLiteral("file"))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("n"), QCoreApplication::translate("main", "Name of the plugin class to generate (deprecated, use PluginName in the input file)."), QStringLiteral("name"), QStringLiteral("WidgetsPlugin"))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("g"), QCoreApplication::translate("main", "Default widget group name to display in designer (deprecated, use DefaultGroup in the input file)."), QStringLiteral("group"), QStringLiteral("Custom"))); KAboutData about(QStringLiteral("kgendesignerplugin"), QCoreApplication::translate("kgendesignerplugin about data", "kgendesignerplugin"), version, description, KAboutLicense::GPL, QCoreApplication::translate("kgendesignerplugin about data", "(C) 2004-2005 Ian Reinhart Geiser"), QString(), QString(), QStringLiteral("[email protected]")); about.addAuthor(QCoreApplication::translate("kgendesignerplugin about data", "Ian Reinhart Geiser"), QString(), QStringLiteral("[email protected]")); about.addAuthor(QCoreApplication::translate("kgendesignerplugin about data", "Daniel Molkentin"), QString(), QStringLiteral("[email protected]")); about.setupCommandLine(&parser); parser.process(app); about.processCommandLine(&parser); if (parser.positionalArguments().count() < 1) { parser.showHelp(); return 1; } QFileInfo fi(parser.positionalArguments().at(0)); QString outputFile = parser.value(QStringLiteral("o")); QString pluginName = parser.value(QStringLiteral("n")); QString group = parser.value(QStringLiteral("g")); QString fileName = fi.absoluteFilePath(); if (parser.isSet(QStringLiteral("o"))) { QFile output(outputFile); if (output.open(QIODevice::WriteOnly)) { QTextStream ts(&output); buildFile(ts, group, fileName, pluginName); QString mocFile = output.fileName(); mocFile.replace(QStringLiteral(".cpp"), QStringLiteral(".moc")); ts << QStringLiteral("#include <%1>\n").arg(mocFile) << '\n'; } output.close(); } else { QTextStream ts(stdout, QIODevice::WriteOnly); buildFile(ts, group, fileName, pluginName); } } void buildFile(QTextStream &ts, const QString &group, const QString &fileName, const QString &pluginName) { KConfig input(fileName, KConfig::NoGlobals); KConfigGroup cg(&input, "Global"); ts << classHeader << '\n'; QString defaultGroup = cg.readEntry("DefaultGroup", group); QStringList includes = cg.readEntry("Includes", QStringList()); QStringList classes = input.groupList(); classes.removeAll(QStringLiteral("Global")); for (const QString &myInclude : qAsConst(classes)) { includes += buildWidgetInclude(myInclude, input); } for (const QString &myInclude : qAsConst(includes)) { ts << "#include <" << myInclude << ">\n"; } ts << QLatin1String("\n\n"); // Autogenerate widget defs here for (const QString &myClass : qAsConst(classes)) { ts << buildWidgetClass(myClass, input, defaultGroup) << "\n"; } ts << buildCollClass(input, classes, pluginName); ts.flush(); } QString denamespace(const QString &str) { QString denamespaced = str; denamespaced.remove(QStringLiteral("::")); return denamespaced; } QString buildCollClass(KConfig &_input, const QStringList &classes, const QString &pluginName) { KConfigGroup input(&_input, "Global"); QHash<QString, QString> defMap; const QString collName = input.readEntry("PluginName", pluginName); Q_ASSERT(!collName.isEmpty()); defMap.insert(QStringLiteral("CollName"), collName); QString genCode; for (const QString &myClass : classes) { genCode += QStringLiteral(" m_plugins.append( new %1(this) );\n").arg(denamespace(myClass) + QStringLiteral("Plugin")); } defMap.insert(QStringLiteral("CollectionAdd"), genCode); QString str = KMacroExpander::expandMacros(QLatin1String(collClassDef), defMap); str += KMacroExpander::expandMacros(QLatin1String(collClassImpl), defMap); return str; } QString buildWidgetClass(const QString &name, KConfig &_input, const QString &group) { KConfigGroup input(&_input, name); QHash<QString, QString> defMap; defMap.insert(QStringLiteral("Group"), input.readEntry("Group", group).replace(QLatin1Char('\"'), QStringLiteral("\\\""))); defMap.insert(QStringLiteral("IncludeFile"), input.readEntry("IncludeFile", QString(name.toLower() + QStringLiteral(".h"))).remove(QLatin1Char(':'))); defMap.insert(QStringLiteral("ToolTip"), input.readEntry("ToolTip", QString(name + QStringLiteral(" Widget"))).replace(QLatin1Char('\"'), QStringLiteral("\\\""))); defMap.insert(QStringLiteral("WhatsThis"), input.readEntry("WhatsThis", QString(name + QStringLiteral(" Widget"))).replace(QLatin1Char('\"'), QStringLiteral("\\\""))); defMap.insert(QStringLiteral("IsContainer"), input.readEntry("IsContainer", QStringLiteral("false"))); defMap.insert(QStringLiteral("IconName"), input.readEntry("IconName", QString::fromLatin1(":/pics/%1.png").arg(denamespace(name).toLower()))); defMap.insert(QStringLiteral("Class"), name); defMap.insert(QStringLiteral("PluginName"), denamespace(name) + QLatin1String("Plugin")); // FIXME: ### make this more useful, i.e. outsource to separate file QString domXml = input.readEntry("DomXML", QString()); // If domXml is empty then we should call base class function if (domXml.isEmpty()) { domXml = QStringLiteral("QDesignerCustomWidgetInterface::domXml()"); } else { domXml = QStringLiteral("QStringLiteral(\"%1\")").arg(domXml.replace(QLatin1Char('\"'), QStringLiteral("\\\""))); } defMap.insert(QStringLiteral("DomXml"), domXml); defMap.insert(QStringLiteral("CodeTemplate"), input.readEntry("CodeTemplate")); defMap.insert(QStringLiteral("CreateWidget"), input.readEntry("CreateWidget", QStringLiteral("\n return new %1%2;") .arg(input.readEntry("ImplClass", name)) .arg(input.readEntry("ConstructorArgs", "( parent )")))); defMap.insert(QStringLiteral("Initialize"), input.readEntry("Initialize", "\n Q_UNUSED(core);\n if (mInitialized) return;\n mInitialized=true;")); QString code = KMacroExpander::expandMacros(QLatin1String(classDef), defMap); return code.replace(QLatin1String("QStringLiteral(\"\")"), QLatin1String("QString()")); } QString buildWidgetInclude(const QString &name, KConfig &_input) { KConfigGroup input(&_input, name); return input.readEntry("IncludeFile", QString(name.toLower() + QStringLiteral(".h"))); } <commit_msg>GIT_SILENT: we can use std::as_const directly<commit_after>/* Copyright (C) 2004-2005 ian reinhart geiser <[email protected]> */ #include <kconfig.h> #include <kmacroexpander.h> #include <kconfiggroup.h> #include <kaboutdata.h> #include <QCommandLineOption> #include <QCommandLineParser> #include <QCoreApplication> #include <QFile> #include <QFileInfo> #include <QHash> #include <QString> #include <QStringList> #include <QTextStream> static const char classHeader[] = "/**\n" "* This file was autogenerated by kgendesignerplugin. Any changes will be lost!\n" "* The generated code in this file is licensed under the same license that the\n" "* input file.\n" "*/\n" "#include <QIcon>\n" "#include <QtDesigner/QDesignerContainerExtension>\n" "#if QT_VERSION >= 0x050500\n" "# include <QtUiPlugin/QDesignerCustomWidgetInterface>\n" "#else\n" "# include <QDesignerCustomWidgetInterface>\n" "#endif\n" "#include <qplugin.h>\n" "#include <qdebug.h>\n"; static const char collClassDef[] = "class %CollName : public QObject, public QDesignerCustomWidgetCollectionInterface\n" "{\n" " Q_OBJECT\n" " Q_INTERFACES(QDesignerCustomWidgetCollectionInterface)\n" " Q_PLUGIN_METADATA(IID \"org.qt-project.Qt.QDesignerCustomWidgetInterface\")\n" "public:\n" " %CollName(QObject *parent = nullptr);\n" " virtual ~%CollName() {}\n" " QList<QDesignerCustomWidgetInterface*> customWidgets() const Q_DECL_OVERRIDE { return m_plugins; } \n" " \n" "private:\n" " QList<QDesignerCustomWidgetInterface*> m_plugins;\n" "};\n\n" ; static const char collClassImpl[] = "%CollName::%CollName(QObject *parent)\n" " : QObject(parent)" "{\n" "%CollectionAdd\n" "}\n\n"; static const char classDef[] = "class %PluginName : public QObject, public QDesignerCustomWidgetInterface\n" "{\n" " Q_OBJECT\n" " Q_INTERFACES(QDesignerCustomWidgetInterface)\n" "public:\n" " %PluginName(QObject *parent = nullptr) :\n QObject(parent), mInitialized(false) {}\n" " virtual ~%PluginName() {}\n" " \n" " bool isContainer() const Q_DECL_OVERRIDE { return %IsContainer; }\n" " bool isInitialized() const Q_DECL_OVERRIDE { return mInitialized; }\n" " QIcon icon() const Q_DECL_OVERRIDE { return QIcon(QStringLiteral(\"%IconName\")); }\n" " QString codeTemplate() const Q_DECL_OVERRIDE { return QStringLiteral(\"%CodeTemplate\"); }\n" " QString domXml() const Q_DECL_OVERRIDE { return %DomXml; }\n" " QString group() const Q_DECL_OVERRIDE { return QStringLiteral(\"%Group\"); }\n" " QString includeFile() const Q_DECL_OVERRIDE { return QStringLiteral(\"%IncludeFile\"); }\n" " QString name() const Q_DECL_OVERRIDE { return QStringLiteral(\"%Class\"); }\n" " QString toolTip() const Q_DECL_OVERRIDE { return QStringLiteral(\"%ToolTip\"); }\n" " QString whatsThis() const Q_DECL_OVERRIDE { return QStringLiteral(\"%WhatsThis\"); }\n\n" " QWidget* createWidget( QWidget* parent ) Q_DECL_OVERRIDE \n {%CreateWidget\n }\n" " void initialize(QDesignerFormEditorInterface *core) Q_DECL_OVERRIDE \n {%Initialize\n }\n" "\n" "private:\n" " bool mInitialized;\n" "};\n\n"; static QString denamespace(const QString &str); static QString buildCollClass(KConfig &input, const QStringList &classes, const QString &group); static QString buildWidgetClass(const QString &name, KConfig &input, const QString &group); static QString buildWidgetInclude(const QString &name, KConfig &input); static void buildFile(QTextStream &stream, const QString &group, const QString &fileName, const QString &pluginName); int main(int argc, char **argv) { QCoreApplication app(argc, argv); QString description = QCoreApplication::translate("main", "Builds Qt widget plugins from an ini style description file."); const QString version = QStringLiteral("0.5"); app.setApplicationVersion(version); QCommandLineParser parser; parser.addVersionOption(); parser.addHelpOption(); parser.addPositionalArgument(QStringLiteral("file"), QCoreApplication::translate("main", "Input file.")); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("o"), QCoreApplication::translate("main", "Output file."), QStringLiteral("file"))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("n"), QCoreApplication::translate("main", "Name of the plugin class to generate (deprecated, use PluginName in the input file)."), QStringLiteral("name"), QStringLiteral("WidgetsPlugin"))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("g"), QCoreApplication::translate("main", "Default widget group name to display in designer (deprecated, use DefaultGroup in the input file)."), QStringLiteral("group"), QStringLiteral("Custom"))); KAboutData about(QStringLiteral("kgendesignerplugin"), QCoreApplication::translate("kgendesignerplugin about data", "kgendesignerplugin"), version, description, KAboutLicense::GPL, QCoreApplication::translate("kgendesignerplugin about data", "(C) 2004-2005 Ian Reinhart Geiser"), QString(), QString(), QStringLiteral("[email protected]")); about.addAuthor(QCoreApplication::translate("kgendesignerplugin about data", "Ian Reinhart Geiser"), QString(), QStringLiteral("[email protected]")); about.addAuthor(QCoreApplication::translate("kgendesignerplugin about data", "Daniel Molkentin"), QString(), QStringLiteral("[email protected]")); about.setupCommandLine(&parser); parser.process(app); about.processCommandLine(&parser); if (parser.positionalArguments().count() < 1) { parser.showHelp(); return 1; } QFileInfo fi(parser.positionalArguments().at(0)); QString outputFile = parser.value(QStringLiteral("o")); QString pluginName = parser.value(QStringLiteral("n")); QString group = parser.value(QStringLiteral("g")); QString fileName = fi.absoluteFilePath(); if (parser.isSet(QStringLiteral("o"))) { QFile output(outputFile); if (output.open(QIODevice::WriteOnly)) { QTextStream ts(&output); buildFile(ts, group, fileName, pluginName); QString mocFile = output.fileName(); mocFile.replace(QStringLiteral(".cpp"), QStringLiteral(".moc")); ts << QStringLiteral("#include <%1>\n").arg(mocFile) << '\n'; } output.close(); } else { QTextStream ts(stdout, QIODevice::WriteOnly); buildFile(ts, group, fileName, pluginName); } } void buildFile(QTextStream &ts, const QString &group, const QString &fileName, const QString &pluginName) { KConfig input(fileName, KConfig::NoGlobals); KConfigGroup cg(&input, "Global"); ts << classHeader << '\n'; QString defaultGroup = cg.readEntry("DefaultGroup", group); QStringList includes = cg.readEntry("Includes", QStringList()); QStringList classes = input.groupList(); classes.removeAll(QStringLiteral("Global")); for (const QString &myInclude : std::as_const(classes)) { includes += buildWidgetInclude(myInclude, input); } for (const QString &myInclude : std::as_const(includes)) { ts << "#include <" << myInclude << ">\n"; } ts << QLatin1String("\n\n"); // Autogenerate widget defs here for (const QString &myClass : std::as_const(classes)) { ts << buildWidgetClass(myClass, input, defaultGroup) << "\n"; } ts << buildCollClass(input, classes, pluginName); ts.flush(); } QString denamespace(const QString &str) { QString denamespaced = str; denamespaced.remove(QStringLiteral("::")); return denamespaced; } QString buildCollClass(KConfig &_input, const QStringList &classes, const QString &pluginName) { KConfigGroup input(&_input, "Global"); QHash<QString, QString> defMap; const QString collName = input.readEntry("PluginName", pluginName); Q_ASSERT(!collName.isEmpty()); defMap.insert(QStringLiteral("CollName"), collName); QString genCode; for (const QString &myClass : classes) { genCode += QStringLiteral(" m_plugins.append( new %1(this) );\n").arg(denamespace(myClass) + QStringLiteral("Plugin")); } defMap.insert(QStringLiteral("CollectionAdd"), genCode); QString str = KMacroExpander::expandMacros(QLatin1String(collClassDef), defMap); str += KMacroExpander::expandMacros(QLatin1String(collClassImpl), defMap); return str; } QString buildWidgetClass(const QString &name, KConfig &_input, const QString &group) { KConfigGroup input(&_input, name); QHash<QString, QString> defMap; defMap.insert(QStringLiteral("Group"), input.readEntry("Group", group).replace(QLatin1Char('\"'), QStringLiteral("\\\""))); defMap.insert(QStringLiteral("IncludeFile"), input.readEntry("IncludeFile", QString(name.toLower() + QStringLiteral(".h"))).remove(QLatin1Char(':'))); defMap.insert(QStringLiteral("ToolTip"), input.readEntry("ToolTip", QString(name + QStringLiteral(" Widget"))).replace(QLatin1Char('\"'), QStringLiteral("\\\""))); defMap.insert(QStringLiteral("WhatsThis"), input.readEntry("WhatsThis", QString(name + QStringLiteral(" Widget"))).replace(QLatin1Char('\"'), QStringLiteral("\\\""))); defMap.insert(QStringLiteral("IsContainer"), input.readEntry("IsContainer", QStringLiteral("false"))); defMap.insert(QStringLiteral("IconName"), input.readEntry("IconName", QString::fromLatin1(":/pics/%1.png").arg(denamespace(name).toLower()))); defMap.insert(QStringLiteral("Class"), name); defMap.insert(QStringLiteral("PluginName"), denamespace(name) + QLatin1String("Plugin")); // FIXME: ### make this more useful, i.e. outsource to separate file QString domXml = input.readEntry("DomXML", QString()); // If domXml is empty then we should call base class function if (domXml.isEmpty()) { domXml = QStringLiteral("QDesignerCustomWidgetInterface::domXml()"); } else { domXml = QStringLiteral("QStringLiteral(\"%1\")").arg(domXml.replace(QLatin1Char('\"'), QStringLiteral("\\\""))); } defMap.insert(QStringLiteral("DomXml"), domXml); defMap.insert(QStringLiteral("CodeTemplate"), input.readEntry("CodeTemplate")); defMap.insert(QStringLiteral("CreateWidget"), input.readEntry("CreateWidget", QStringLiteral("\n return new %1%2;") .arg(input.readEntry("ImplClass", name)) .arg(input.readEntry("ConstructorArgs", "( parent )")))); defMap.insert(QStringLiteral("Initialize"), input.readEntry("Initialize", "\n Q_UNUSED(core);\n if (mInitialized) return;\n mInitialized=true;")); QString code = KMacroExpander::expandMacros(QLatin1String(classDef), defMap); return code.replace(QLatin1String("QStringLiteral(\"\")"), QLatin1String("QString()")); } QString buildWidgetInclude(const QString &name, KConfig &_input) { KConfigGroup input(&_input, name); return input.readEntry("IncludeFile", QString(name.toLower() + QStringLiteral(".h"))); } <|endoftext|>
<commit_before>#include <iostream> #include <map> #include "object/health_stimulation.h" #include "object/stimulation.h" #include "level/blockobject.h" #include "object/enemy.h" #include "object/heart.h" #include "object/item.h" #include "util/load_exception.h" #include "object/object.h" #include "object_factory.h" using namespace std; #ifndef debug #define debug cout<<"File: "<<__FILE__<<" Line: "<<__LINE__<<endl; // #define debug #endif ObjectFactory * ObjectFactory::factory = NULL; Object * ObjectFactory::createObject( BlockObject * block ){ if ( factory == NULL ){ factory = new ObjectFactory(); } return factory->makeObject( block ); } void ObjectFactory::destroy(){ if ( factory ){ delete factory; factory = NULL; } } ObjectFactory::ObjectFactory(){ } static Stimulation * makeStimulation( const string & str, int value ){ if ( str == "health" ){ return new HealthStimulation( value ); } return new Stimulation(); } Object * ObjectFactory::makeItem( Item * item, BlockObject * block ){ int x, z; block->getCoords( x, z ); item->setX( x ); item->setZ( z ); return item; } Object * ObjectFactory::makeEnemy( Enemy * ret, BlockObject * block ){ // Enemy * ret; /* string name = block->getName(); for ( int q = 0; q < name.size(); q++ ){ if ( name[q] >= 'A' && name[q] <= 'Z' ){ name[q] = name[q] - 'A' + 'a'; } } string filename( "data/chars/" ); filename += name; filename += "/"; filename += name; filename += ".txt"; */ /* string filename = block->getPath(); try{ ret = new Enemy( filename ); } catch( const LoadException & le ){ cout<<__FILE__<<" : "<<le.getReason()<<endl; // delete ret; return NULL; } */ int x, z; block->getCoords( x, z ); ret->setX( x ); ret->setZ( z ); if ( block->getAggression() > 0 ){ ret->setAggression( block->getAggression() ); } ret->setName( block->getAlias() ); ret->setMap( block->getMap() ); ret->setHealth( block->getHealth() ); ret->setMaxHealth( block->getHealth() ); hearts.push_back( ret->getHeart() ); return ret; } Object * ObjectFactory::makeObject( BlockObject * block ){ // Object * ret = NULL; switch( block->getType() ){ case OBJECT_ITEM : { try{ if ( cached[ block->getPath() ] == NULL ){ cached[ block->getPath() ] = new Item( block->getPath(), makeStimulation( block->getStimulationType(), block->getStimulationValue() ) ); cout << "Cached " << block->getPath() << endl; } return makeItem( (Item *) cached[ block->getPath() ]->copy(), block ); } catch ( const LoadException & le ){ cout << "Could not load " << block->getPath() << " because " << le.getReason() << endl; } break; } case OBJECT_ENEMY : { try{ if ( cached[ block->getPath() ] == NULL ){ cached[ block->getPath() ] = new Enemy( block->getPath() ); cout << "Cached " << block->getPath() << endl; } /* ret = cached[ block->getName() ]->copy(); Enemy * enemy = (Enemy *) ret; int x, z; block->getCoords( x, z ); ret->setX( x ); ret->setZ( z ); if ( block->getAggression() > 0 ){ enemy->setAggression( block->getAggression() ); } enemy->setName( block->getAlias() ); enemy->setMap( block->getMap() ); ret->setHealth( block->getHealth() ); ret->setMaxHealth( block->getHealth() ); return ret; } */ return makeEnemy( (Enemy *) cached[ block->getPath() ]->copy(), block ); } catch ( const LoadException & le ){ cout << "Could not load " << block->getPath() << " because " << le.getReason() << endl; } break; } default : { cout<<__FILE__<<": No type given for: "<<block->getPath()<<endl; return NULL; break; } } /* we keep the original becuase only the original stores the animations * and other special memory things */ // cout<<"Adding cached object to factory"<<endl; // cached[ block->getName() ] = ret; // cout<<"Object factory has "<<cached.size()<<" elements"<<endl; // return ret->copy(); return NULL; } ObjectFactory::~ObjectFactory(){ // cout<<"Object Factory erasing: "<<cached.size()<<" elements"<<endl; for ( map< string, Object * >::iterator it = cached.begin(); it != cached.end(); it++ ){ // cout<<"Object factory deleting object: "<< (*it).second << endl; delete (*it).second; } /* for ( vector< Heart * >::iterator it = hearts.begin(); it != hearts.end(); it++ ){ delete *it; } */ } <commit_msg>set max health before regular health<commit_after>#include <iostream> #include <map> #include "object/health_stimulation.h" #include "object/stimulation.h" #include "level/blockobject.h" #include "object/enemy.h" #include "object/heart.h" #include "object/item.h" #include "util/load_exception.h" #include "object/object.h" #include "object_factory.h" using namespace std; #ifndef debug #define debug cout<<"File: "<<__FILE__<<" Line: "<<__LINE__<<endl; // #define debug #endif ObjectFactory * ObjectFactory::factory = NULL; Object * ObjectFactory::createObject( BlockObject * block ){ if ( factory == NULL ){ factory = new ObjectFactory(); } return factory->makeObject( block ); } void ObjectFactory::destroy(){ if ( factory ){ delete factory; factory = NULL; } } ObjectFactory::ObjectFactory(){ } static Stimulation * makeStimulation( const string & str, int value ){ if ( str == "health" ){ return new HealthStimulation( value ); } return new Stimulation(); } Object * ObjectFactory::makeItem( Item * item, BlockObject * block ){ int x, z; block->getCoords( x, z ); item->setX( x ); item->setZ( z ); return item; } Object * ObjectFactory::makeEnemy( Enemy * ret, BlockObject * block ){ int x, z; block->getCoords( x, z ); ret->setX( x ); ret->setZ( z ); if ( block->getAggression() > 0 ){ ret->setAggression( block->getAggression() ); } ret->setName( block->getAlias() ); ret->setMap( block->getMap() ); ret->setMaxHealth( block->getHealth() ); ret->setHealth( block->getHealth() ); hearts.push_back( ret->getHeart() ); return ret; } Object * ObjectFactory::makeObject( BlockObject * block ){ // Object * ret = NULL; switch( block->getType() ){ case OBJECT_ITEM : { try{ if ( cached[ block->getPath() ] == NULL ){ cached[ block->getPath() ] = new Item( block->getPath(), makeStimulation( block->getStimulationType(), block->getStimulationValue() ) ); cout << "Cached " << block->getPath() << endl; } return makeItem( (Item *) cached[ block->getPath() ]->copy(), block ); } catch ( const LoadException & le ){ cout << "Could not load " << block->getPath() << " because " << le.getReason() << endl; } break; } case OBJECT_ENEMY : { try{ if ( cached[ block->getPath() ] == NULL ){ cached[ block->getPath() ] = new Enemy( block->getPath() ); cout << "Cached " << block->getPath() << endl; } return makeEnemy( (Enemy *) cached[ block->getPath() ]->copy(), block ); } catch ( const LoadException & le ){ cout << "Could not load " << block->getPath() << " because " << le.getReason() << endl; } break; } default : { cout<<__FILE__<<": No type given for: "<<block->getPath()<<endl; return NULL; break; } } /* we keep the original becuase only the original stores the animations * and other special memory things */ // cout<<"Adding cached object to factory"<<endl; // cached[ block->getName() ] = ret; // cout<<"Object factory has "<<cached.size()<<" elements"<<endl; // return ret->copy(); return NULL; } ObjectFactory::~ObjectFactory(){ // cout<<"Object Factory erasing: "<<cached.size()<<" elements"<<endl; for ( map< string, Object * >::iterator it = cached.begin(); it != cached.end(); it++ ){ // cout<<"Object factory deleting object: "<< (*it).second << endl; delete (*it).second; } /* for ( vector< Heart * >::iterator it = hearts.begin(); it != hearts.end(); it++ ){ delete *it; } */ } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "kudu/rpc/rpcz_store.h" #include <algorithm> // IWYU pragma: keep #include <array> #include <cstdint> #include <mutex> // for unique_lock #include <ostream> #include <string> #include <utility> #include <vector> #include <gflags/gflags.h> #include <glog/logging.h> #include <google/protobuf/message.h> #include "kudu/gutil/port.h" #include "kudu/gutil/ref_counted.h" #include "kudu/gutil/strings/stringpiece.h" #include "kudu/gutil/walltime.h" #include "kudu/rpc/inbound_call.h" #include "kudu/rpc/rpc_header.pb.h" #include "kudu/rpc/rpc_introspection.pb.h" #include "kudu/rpc/service_if.h" #include "kudu/util/atomic.h" #include "kudu/util/flag_tags.h" #include "kudu/util/monotime.h" #include "kudu/util/trace.h" #include "kudu/util/trace_metrics.h" DEFINE_bool(rpc_dump_all_traces, false, "If true, dump all RPC traces at INFO level"); TAG_FLAG(rpc_dump_all_traces, advanced); TAG_FLAG(rpc_dump_all_traces, runtime); DEFINE_int32(rpc_duration_too_long_ms, 1000, "Threshold (in milliseconds) above which a RPC is considered too long and its " "duration and method name are logged at INFO level. The time measured is between " "when a RPC is accepted and when its call handler completes."); TAG_FLAG(rpc_duration_too_long_ms, advanced); TAG_FLAG(rpc_duration_too_long_ms, runtime); using std::pair; using std::string; using std::vector; using std::unique_ptr; namespace kudu { namespace rpc { // Sample an RPC call once every N milliseconds within each // bucket. If the current sample in a latency bucket is older // than this threshold, a new sample will be taken. static const int kSampleIntervalMs = 1000; static const int kBucketThresholdsMs[] = {10, 100, 1000}; static constexpr int kNumBuckets = arraysize(kBucketThresholdsMs) + 1; // An instance of this class is created For each RPC method implemented // on the server. It keeps several recent samples for each RPC, currently // based on fixed time buckets. class MethodSampler { public: MethodSampler() {} ~MethodSampler() {} // Potentially sample a single call. void SampleCall(InboundCall* call); // Dump the current samples. void GetSamplePBs(RpczMethodPB* pb); private: // Convert the trace metrics from 't' into protobuf entries in 'sample_pb'. // This function recurses through the parent-child relationship graph, // keeping the current tree path in 'child_path' (empty at the root). static void GetTraceMetrics(const Trace& t, const string& child_path, RpczSamplePB* sample_pb); // An individual recorded sample. struct Sample { RequestHeader header; scoped_refptr<Trace> trace; int duration_ms; }; // A sample, including the particular time at which it was // sampled, and a lock protecting it. struct SampleBucket { SampleBucket() : last_sample_time(0) {} AtomicInt<int64_t> last_sample_time; simple_spinlock sample_lock; Sample sample; }; std::array<SampleBucket, kNumBuckets> buckets_; DISALLOW_COPY_AND_ASSIGN(MethodSampler); }; MethodSampler* RpczStore::SamplerForCall(InboundCall* call) { if (PREDICT_FALSE(!call->method_info())) { return nullptr; } // Most likely, we already have a sampler created for the call. { shared_lock<rw_spinlock> l(samplers_lock_.get_lock()); auto it = method_samplers_.find(call->method_info()); if (PREDICT_TRUE(it != method_samplers_.end())) { return it->second.get(); } } // If missing, create a new sampler for this method and try to insert it. unique_ptr<MethodSampler> ms(new MethodSampler()); std::lock_guard<percpu_rwlock> lock(samplers_lock_); auto it = method_samplers_.find(call->method_info()); if (it != method_samplers_.end()) { return it->second.get(); } auto* ret = ms.get(); method_samplers_[call->method_info()] = std::move(ms); return ret; } void MethodSampler::SampleCall(InboundCall* call) { // First determine which sample bucket to put this in. int duration_ms = call->timing().TotalDuration().ToMilliseconds(); SampleBucket* bucket = &buckets_[kNumBuckets - 1]; for (int i = 0 ; i < kNumBuckets - 1; i++) { if (duration_ms < kBucketThresholdsMs[i]) { bucket = &buckets_[i]; break; } } MicrosecondsInt64 now = GetMonoTimeMicros(); int64_t us_since_trace = now - bucket->last_sample_time.Load(); if (us_since_trace > kSampleIntervalMs * 1000) { Sample new_sample = {call->header(), call->trace(), duration_ms}; { std::unique_lock<simple_spinlock> lock(bucket->sample_lock, std::try_to_lock); // If another thread is already taking a sample, it's not worth waiting. if (!lock.owns_lock()) { return; } std::swap(bucket->sample, new_sample); bucket->last_sample_time.Store(now); } VLOG(2) << "Sampled call " << call->ToString(); } } void MethodSampler::GetTraceMetrics(const Trace& t, const string& child_path, RpczSamplePB* sample_pb) { auto m = t.metrics().Get(); for (const auto& e : m) { auto* pb = sample_pb->add_metrics(); pb->set_key(e.first); pb->set_value(e.second); if (!child_path.empty()) { pb->set_child_path(child_path); } } for (const auto& child_pair : t.ChildTraces()) { string path = child_path; if (!path.empty()) { path += "."; } path += child_pair.first.ToString(); GetTraceMetrics(*child_pair.second.get(), path, sample_pb); } } void MethodSampler::GetSamplePBs(RpczMethodPB* method_pb) { for (auto& bucket : buckets_) { if (bucket.last_sample_time.Load() == 0) continue; std::unique_lock<simple_spinlock> lock(bucket.sample_lock); auto* sample_pb = method_pb->add_samples(); sample_pb->mutable_header()->CopyFrom(bucket.sample.header); sample_pb->set_trace(bucket.sample.trace->DumpToString(Trace::INCLUDE_TIME_DELTAS)); GetTraceMetrics(*bucket.sample.trace.get(), "", sample_pb); sample_pb->set_duration_ms(bucket.sample.duration_ms); } } RpczStore::RpczStore() {} RpczStore::~RpczStore() {} void RpczStore::AddCall(InboundCall* call) { LogTrace(call); auto* sampler = SamplerForCall(call); if (PREDICT_FALSE(!sampler)) return; sampler->SampleCall(call); } void RpczStore::DumpPB(const DumpRpczStoreRequestPB& req, DumpRpczStoreResponsePB* resp) { vector<pair<RpcMethodInfo*, MethodSampler*>> samplers; { shared_lock<rw_spinlock> l(samplers_lock_.get_lock()); for (const auto& p : method_samplers_) { samplers.emplace_back(p.first, p.second.get()); } } for (const auto& p : samplers) { auto* sampler = p.second; RpczMethodPB* method_pb = resp->add_methods(); // TODO: use the actual RPC name instead of the request type name. // Currently this isn't conveniently plumbed here, but the type name // is close enough. method_pb->set_method_name(p.first->req_prototype->GetTypeName()); sampler->GetSamplePBs(method_pb); } } void RpczStore::LogTrace(InboundCall* call) { int duration_ms = call->timing().TotalDuration().ToMilliseconds(); if (call->header_.has_timeout_millis() && call->header_.timeout_millis() > 0) { double log_threshold = call->header_.timeout_millis() * 0.75f; if (duration_ms > log_threshold) { // TODO: consider pushing this onto another thread since it may be slow. // The traces may also be too large to fit in a log message. LOG(WARNING) << call->ToString() << " took " << duration_ms << "ms (client timeout " << call->header_.timeout_millis() << ")."; string s = call->trace()->DumpToString(); if (!s.empty()) { LOG(WARNING) << "Trace:\n" << s; } return; } } if (PREDICT_FALSE(FLAGS_rpc_dump_all_traces)) { LOG(INFO) << call->ToString() << " took " << duration_ms << "ms. Trace:"; call->trace()->Dump(&LOG(INFO), true); } else if (duration_ms > FLAGS_rpc_duration_too_long_ms) { LOG(INFO) << call->ToString() << " took " << duration_ms << "ms. " << "Request Metrics: " << call->trace()->MetricsAsJSON(); } } } // namespace rpc } // namespace kudu <commit_msg>rpcz: print timeout units (ms) when logging<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "kudu/rpc/rpcz_store.h" #include <algorithm> // IWYU pragma: keep #include <array> #include <cstdint> #include <mutex> // for unique_lock #include <ostream> #include <string> #include <utility> #include <vector> #include <gflags/gflags.h> #include <glog/logging.h> #include <google/protobuf/message.h> #include "kudu/gutil/port.h" #include "kudu/gutil/ref_counted.h" #include "kudu/gutil/strings/human_readable.h" #include "kudu/gutil/strings/stringpiece.h" #include "kudu/gutil/walltime.h" #include "kudu/rpc/inbound_call.h" #include "kudu/rpc/rpc_header.pb.h" #include "kudu/rpc/rpc_introspection.pb.h" #include "kudu/rpc/service_if.h" #include "kudu/util/atomic.h" #include "kudu/util/flag_tags.h" #include "kudu/util/monotime.h" #include "kudu/util/trace.h" #include "kudu/util/trace_metrics.h" DEFINE_bool(rpc_dump_all_traces, false, "If true, dump all RPC traces at INFO level"); TAG_FLAG(rpc_dump_all_traces, advanced); TAG_FLAG(rpc_dump_all_traces, runtime); DEFINE_int32(rpc_duration_too_long_ms, 1000, "Threshold (in milliseconds) above which a RPC is considered too long and its " "duration and method name are logged at INFO level. The time measured is between " "when a RPC is accepted and when its call handler completes."); TAG_FLAG(rpc_duration_too_long_ms, advanced); TAG_FLAG(rpc_duration_too_long_ms, runtime); using std::pair; using std::string; using std::vector; using std::unique_ptr; namespace kudu { namespace rpc { // Sample an RPC call once every N milliseconds within each // bucket. If the current sample in a latency bucket is older // than this threshold, a new sample will be taken. static const int kSampleIntervalMs = 1000; static const int kBucketThresholdsMs[] = {10, 100, 1000}; static constexpr int kNumBuckets = arraysize(kBucketThresholdsMs) + 1; // An instance of this class is created For each RPC method implemented // on the server. It keeps several recent samples for each RPC, currently // based on fixed time buckets. class MethodSampler { public: MethodSampler() {} ~MethodSampler() {} // Potentially sample a single call. void SampleCall(InboundCall* call); // Dump the current samples. void GetSamplePBs(RpczMethodPB* pb); private: // Convert the trace metrics from 't' into protobuf entries in 'sample_pb'. // This function recurses through the parent-child relationship graph, // keeping the current tree path in 'child_path' (empty at the root). static void GetTraceMetrics(const Trace& t, const string& child_path, RpczSamplePB* sample_pb); // An individual recorded sample. struct Sample { RequestHeader header; scoped_refptr<Trace> trace; int duration_ms; }; // A sample, including the particular time at which it was // sampled, and a lock protecting it. struct SampleBucket { SampleBucket() : last_sample_time(0) {} AtomicInt<int64_t> last_sample_time; simple_spinlock sample_lock; Sample sample; }; std::array<SampleBucket, kNumBuckets> buckets_; DISALLOW_COPY_AND_ASSIGN(MethodSampler); }; MethodSampler* RpczStore::SamplerForCall(InboundCall* call) { if (PREDICT_FALSE(!call->method_info())) { return nullptr; } // Most likely, we already have a sampler created for the call. { shared_lock<rw_spinlock> l(samplers_lock_.get_lock()); auto it = method_samplers_.find(call->method_info()); if (PREDICT_TRUE(it != method_samplers_.end())) { return it->second.get(); } } // If missing, create a new sampler for this method and try to insert it. unique_ptr<MethodSampler> ms(new MethodSampler()); std::lock_guard<percpu_rwlock> lock(samplers_lock_); auto it = method_samplers_.find(call->method_info()); if (it != method_samplers_.end()) { return it->second.get(); } auto* ret = ms.get(); method_samplers_[call->method_info()] = std::move(ms); return ret; } void MethodSampler::SampleCall(InboundCall* call) { // First determine which sample bucket to put this in. int duration_ms = call->timing().TotalDuration().ToMilliseconds(); SampleBucket* bucket = &buckets_[kNumBuckets - 1]; for (int i = 0 ; i < kNumBuckets - 1; i++) { if (duration_ms < kBucketThresholdsMs[i]) { bucket = &buckets_[i]; break; } } MicrosecondsInt64 now = GetMonoTimeMicros(); int64_t us_since_trace = now - bucket->last_sample_time.Load(); if (us_since_trace > kSampleIntervalMs * 1000) { Sample new_sample = {call->header(), call->trace(), duration_ms}; { std::unique_lock<simple_spinlock> lock(bucket->sample_lock, std::try_to_lock); // If another thread is already taking a sample, it's not worth waiting. if (!lock.owns_lock()) { return; } std::swap(bucket->sample, new_sample); bucket->last_sample_time.Store(now); } VLOG(2) << "Sampled call " << call->ToString(); } } void MethodSampler::GetTraceMetrics(const Trace& t, const string& child_path, RpczSamplePB* sample_pb) { auto m = t.metrics().Get(); for (const auto& e : m) { auto* pb = sample_pb->add_metrics(); pb->set_key(e.first); pb->set_value(e.second); if (!child_path.empty()) { pb->set_child_path(child_path); } } for (const auto& child_pair : t.ChildTraces()) { string path = child_path; if (!path.empty()) { path += "."; } path += child_pair.first.ToString(); GetTraceMetrics(*child_pair.second.get(), path, sample_pb); } } void MethodSampler::GetSamplePBs(RpczMethodPB* method_pb) { for (auto& bucket : buckets_) { if (bucket.last_sample_time.Load() == 0) continue; std::unique_lock<simple_spinlock> lock(bucket.sample_lock); auto* sample_pb = method_pb->add_samples(); sample_pb->mutable_header()->CopyFrom(bucket.sample.header); sample_pb->set_trace(bucket.sample.trace->DumpToString(Trace::INCLUDE_TIME_DELTAS)); GetTraceMetrics(*bucket.sample.trace.get(), "", sample_pb); sample_pb->set_duration_ms(bucket.sample.duration_ms); } } RpczStore::RpczStore() {} RpczStore::~RpczStore() {} void RpczStore::AddCall(InboundCall* call) { LogTrace(call); auto* sampler = SamplerForCall(call); if (PREDICT_FALSE(!sampler)) return; sampler->SampleCall(call); } void RpczStore::DumpPB(const DumpRpczStoreRequestPB& req, DumpRpczStoreResponsePB* resp) { vector<pair<RpcMethodInfo*, MethodSampler*>> samplers; { shared_lock<rw_spinlock> l(samplers_lock_.get_lock()); for (const auto& p : method_samplers_) { samplers.emplace_back(p.first, p.second.get()); } } for (const auto& p : samplers) { auto* sampler = p.second; RpczMethodPB* method_pb = resp->add_methods(); // TODO: use the actual RPC name instead of the request type name. // Currently this isn't conveniently plumbed here, but the type name // is close enough. method_pb->set_method_name(p.first->req_prototype->GetTypeName()); sampler->GetSamplePBs(method_pb); } } void RpczStore::LogTrace(InboundCall* call) { int duration_ms = call->timing().TotalDuration().ToMilliseconds(); if (call->header_.has_timeout_millis() && call->header_.timeout_millis() > 0) { double log_threshold = call->header_.timeout_millis() * 0.75f; if (duration_ms > log_threshold) { // TODO: consider pushing this onto another thread since it may be slow. // The traces may also be too large to fit in a log message. int64_t timeout_ms = call->header_.timeout_millis(); LOG(WARNING) << call->ToString() << " took " << duration_ms << " ms " << "(" << HumanReadableElapsedTime::ToShortString(duration_ms * .001) << "). " << "Client timeout " << timeout_ms << " ms " << "(" << HumanReadableElapsedTime::ToShortString(timeout_ms * .001) << ")"; string s = call->trace()->DumpToString(); if (!s.empty()) { LOG(WARNING) << "Trace:\n" << s; } return; } } if (PREDICT_FALSE(FLAGS_rpc_dump_all_traces)) { LOG(INFO) << call->ToString() << " took " << duration_ms << "ms. Trace:"; call->trace()->Dump(&LOG(INFO), true); } else if (duration_ms > FLAGS_rpc_duration_too_long_ms) { LOG(INFO) << call->ToString() << " took " << duration_ms << "ms. " << "Request Metrics: " << call->trace()->MetricsAsJSON(); } } } // namespace rpc } // namespace kudu <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* libvisio * Version: MPL 1.1 / GPLv2+ / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2011 Fridrich Strba <[email protected]> * Copyright (C) 2011 Eilidh McAdam <[email protected]> * * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPLv2+"), or * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable * instead of those above. */ #include <string> #include "VSDInternalStream.h" #include "libvisio_utils.h" #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/remove_whitespace.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/range/iterator_range.hpp> uint8_t libvisio::readU8(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead); if (p && numBytesRead == sizeof(uint8_t)) return *(uint8_t const *)(p); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } uint16_t libvisio::readU16(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead); if (p && numBytesRead == sizeof(uint16_t)) return (uint16_t)p[0]|((uint16_t)p[1]<<8); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } int16_t libvisio::readS16(WPXInputStream *input) { return (int16_t)readU16(input); } uint32_t libvisio::readU32(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead); if (p && numBytesRead == sizeof(uint32_t)) return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } int32_t libvisio::readS32(WPXInputStream *input) { return (int32_t)readU32(input); } uint64_t libvisio::readU64(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead); if (p && numBytesRead == sizeof(uint64_t)) return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } double libvisio::readDouble(WPXInputStream *input) { union { uint64_t u; double d; } tmpUnion; tmpUnion.u = readU64(input); return tmpUnion.d; } void libvisio::appendFromBase64(WPXBinaryData &data, const unsigned char *base64Data, size_t base64DataLength) { boost::iterator_range<const char *> base64String((const char *)base64Data, (const char *)base64Data + base64DataLength); typedef boost::archive::iterators::transform_width< boost::archive::iterators::binary_from_base64< boost::archive::iterators::remove_whitespace< std::string::const_iterator > >, 8, 6 > base64_decoder; std::vector<unsigned char> buffer; std::copy(base64_decoder(base64String.begin()), base64_decoder(base64String.end()), std::back_inserter(buffer)); if (!buffer.empty()) data.append(&buffer[0], buffer.size()); } const ::WPXString libvisio::getColourString(const Colour &c) { ::WPXString sColour; sColour.sprintf("#%.2x%.2x%.2x", c.r, c.g, c.b); return sColour; } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>Some versions of boost bomb on '=' padding characters<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* libvisio * Version: MPL 1.1 / GPLv2+ / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2011 Fridrich Strba <[email protected]> * Copyright (C) 2011 Eilidh McAdam <[email protected]> * * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPLv2+"), or * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable * instead of those above. */ #include <vector> #include <string> #include <algorithm> // std::count #include "VSDInternalStream.h" #include "libvisio_utils.h" #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/remove_whitespace.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/range/iterator_range.hpp> uint8_t libvisio::readU8(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead); if (p && numBytesRead == sizeof(uint8_t)) return *(uint8_t const *)(p); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } uint16_t libvisio::readU16(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead); if (p && numBytesRead == sizeof(uint16_t)) return (uint16_t)p[0]|((uint16_t)p[1]<<8); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } int16_t libvisio::readS16(WPXInputStream *input) { return (int16_t)readU16(input); } uint32_t libvisio::readU32(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead); if (p && numBytesRead == sizeof(uint32_t)) return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } int32_t libvisio::readS32(WPXInputStream *input) { return (int32_t)readU32(input); } uint64_t libvisio::readU64(WPXInputStream *input) { if (!input || input->atEOS()) { VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } unsigned long numBytesRead; uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead); if (p && numBytesRead == sizeof(uint64_t)) return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56); VSD_DEBUG_MSG(("Throwing EndOfStreamException\n")); throw EndOfStreamException(); } double libvisio::readDouble(WPXInputStream *input) { union { uint64_t u; double d; } tmpUnion; tmpUnion.u = readU64(input); return tmpUnion.d; } void libvisio::appendFromBase64(WPXBinaryData &data, const unsigned char *base64Data, size_t base64DataLength) { std::string base64String((const char *)base64Data, base64DataLength); unsigned numPadding = std::count(base64String.begin(), base64String.end(), '='); std::replace(base64String.begin(),base64String.end(),'=','A'); // replace '=' by base64 encoding of '\0' typedef boost::archive::iterators::transform_width< boost::archive::iterators::binary_from_base64< boost::archive::iterators::remove_whitespace< std::string::const_iterator > >, 8, 6 > base64_decoder; std::vector<unsigned char> buffer; std::copy(base64_decoder(base64String.begin()), base64_decoder(base64String.end()), std::back_inserter(buffer)); if (!buffer.empty()) { buffer.erase(buffer.end()-numPadding,buffer.end()); // erase padding '\0' characters if (!buffer.empty()) data.append(&buffer[0], buffer.size()); } } const ::WPXString libvisio::getColourString(const Colour &c) { ::WPXString sColour; sColour.sprintf("#%.2x%.2x%.2x", c.r, c.g, c.b); return sColour; } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>/// /// @file LoadBalancerAC.cpp /// @brief This load balancer assigns work to the threads in the /// computation of the A & C formulas (AC.cpp) in /// Xavier Gourdon's algorithm. /// /// Copyright (C) 2021 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <LoadBalancerAC.hpp> #include <SegmentedPiTable.hpp> #include <primecount-internal.hpp> #include <imath.hpp> #include <stdint.h> #include <algorithm> #include <iostream> namespace { // CPU cache sizes per core const int64_t l1_cache_size = 32 << 10; const int64_t l2_cache_size = 256 << 10; const int64_t numbers_per_byte = primecount::SegmentedPiTable::numbers_per_byte(); // Minimum segment size = 1 KiB const int64_t min_segment_size = (1 << 10) * numbers_per_byte; } // namespace namespace primecount { LoadBalancerAC::LoadBalancerAC(int64_t sqrtx, int64_t y, bool is_print, int threads) : sqrtx_(sqrtx), x14_(isqrt(sqrtx)), y_(y), is_print_(is_print), threads_(threads) { if (threads_ == 1) segment_size_ = std::max(x14_, l2_cache_size * numbers_per_byte); else { // The default segment size is x^(1/4). // This is tiny, will fit into the CPU's cache. segment_size_ = x14_; // Most special leaves are below y (~ x^(1/3) * log(x)). // We make sure this interval is evenly distributed // amongst all threads by using a small segment size. // Above y we use a larger segment size but still ensure // that it fits into the CPU's cache. if (y_ < sqrtx_) { if (segment_size_ <= l1_cache_size * numbers_per_byte && y_ + (l1_cache_size * numbers_per_byte * threads_) * 4 <= sqrtx_) large_segment_size_ = l1_cache_size * numbers_per_byte; else if (segment_size_ * 4 <= l1_cache_size * numbers_per_byte && y_ + (segment_size_ * 4 * threads_) * 4 <= sqrtx_) large_segment_size_ = segment_size_ * 4; else if (segment_size_ <= l2_cache_size * numbers_per_byte && y_ + (l2_cache_size * numbers_per_byte * threads_) * 8 <= sqrtx_) large_segment_size_ = l2_cache_size * numbers_per_byte; } } validate_segment_sizes(); compute_total_segments(); print_status(); } bool LoadBalancerAC::get_work(int64_t& low, int64_t& high) { LockGuard lockGuard(lock_); if (low_ >= sqrtx_) return false; // Most special leaves are below y (~ x^(1/3) * log(x)). // We make sure this interval is evenly distributed // amongst all threads by using a small segment size. // Above y we use a larger segment size but still ensure // that it fits into the CPU's cache. if (low_ > y_) segment_size_ = large_segment_size_; low = low_; high = low + segment_size_; high = std::min(high, sqrtx_); low_ = high; segment_nr_++; print_status(); return low < sqrtx_; } void LoadBalancerAC::validate_segment_sizes() { segment_size_ = std::max(min_segment_size, segment_size_); large_segment_size_ = std::max(segment_size_, large_segment_size_); if (segment_size_ % 240) segment_size_ += 240 - segment_size_ % 240; if (large_segment_size_ % 240) large_segment_size_ += 240 - large_segment_size_ % 240; } void LoadBalancerAC::compute_total_segments() { int64_t small_segments = ceil_div(y_, segment_size_); int64_t threshold = std::min(small_segments * segment_size_, sqrtx_); int64_t large_segments = ceil_div(sqrtx_ - threshold, large_segment_size_); total_segments_ = small_segments + large_segments; } void LoadBalancerAC::print_status() { if (is_print_) { double time = get_time(); double old = time_; double threshold = 0.1; if (old == 0 || (time - old) >= threshold) { time_ = time; std::cout << "\rStatus: " << segment_nr_ << "/" << total_segments_ << std::flush; } } } } // namespace <commit_msg>Tune load balancing<commit_after>/// /// @file LoadBalancerAC.cpp /// @brief This load balancer assigns work to the threads in the /// computation of the A & C formulas (AC.cpp) in /// Xavier Gourdon's algorithm. /// /// Copyright (C) 2021 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <LoadBalancerAC.hpp> #include <SegmentedPiTable.hpp> #include <primecount-internal.hpp> #include <imath.hpp> #include <min.hpp> #include <stdint.h> #include <algorithm> #include <iostream> namespace { // CPU L2 cache sizes per core const int64_t l2_cache_size = 512 << 10; const int64_t numbers_per_byte = primecount::SegmentedPiTable::numbers_per_byte(); const int64_t l2_segment_size = l2_cache_size * numbers_per_byte; // Minimum segment size = 1 KiB const int64_t min_segment_size = (1 << 10) * numbers_per_byte; } // namespace namespace primecount { LoadBalancerAC::LoadBalancerAC(int64_t sqrtx, int64_t y, bool is_print, int threads) : sqrtx_(sqrtx), x14_(isqrt(sqrtx)), y_(y), is_print_(is_print), threads_(threads) { if (threads_ == 1) segment_size_ = std::max(x14_, l2_segment_size); else { // The default segment size is x^(1/4). // This is tiny, will fit into the CPU's cache. segment_size_ = x14_; // Most special leaves are below y (~ x^(1/3) * log(x)). // We make sure this interval is evenly distributed // amongst all threads by using a small segment size. // Above y we use a larger segment size but still ensure // that it fits into the CPU's cache. if (y_ < sqrtx_) { int64_t max_segment_size = (sqrtx_ - y_) / (threads_ * 8); large_segment_size_ = segment_size_ * 16; large_segment_size_ = min3(large_segment_size_, l2_segment_size, max_segment_size); large_segment_size_ = std::max(segment_size_, large_segment_size_); } } validate_segment_sizes(); compute_total_segments(); print_status(); } bool LoadBalancerAC::get_work(int64_t& low, int64_t& high) { LockGuard lockGuard(lock_); if (low_ >= sqrtx_) return false; // Most special leaves are below y (~ x^(1/3) * log(x)). // We make sure this interval is evenly distributed // amongst all threads by using a small segment size. // Above y we use a larger segment size but still ensure // that it fits into the CPU's cache. if (low_ > y_) segment_size_ = large_segment_size_; low = low_; high = low + segment_size_; high = std::min(high, sqrtx_); low_ = high; segment_nr_++; print_status(); return low < sqrtx_; } void LoadBalancerAC::validate_segment_sizes() { segment_size_ = std::max(min_segment_size, segment_size_); large_segment_size_ = std::max(segment_size_, large_segment_size_); if (segment_size_ % 240) segment_size_ += 240 - segment_size_ % 240; if (large_segment_size_ % 240) large_segment_size_ += 240 - large_segment_size_ % 240; } void LoadBalancerAC::compute_total_segments() { int64_t small_segments = ceil_div(y_, segment_size_); int64_t threshold = std::min(small_segments * segment_size_, sqrtx_); int64_t large_segments = ceil_div(sqrtx_ - threshold, large_segment_size_); total_segments_ = small_segments + large_segments; } void LoadBalancerAC::print_status() { if (is_print_) { double time = get_time(); double old = time_; double threshold = 0.1; if (old == 0 || (time - old) >= threshold) { time_ = time; std::cout << "\rStatus: " << segment_nr_ << "/" << total_segments_ << std::flush; } } } } // namespace <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2020 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QLabel> #include <QNetworkInterface> #include "de_web_plugin.h" #include "de_web_widget.h" #include "ui_de_web_widget.h" /*! Constructor. */ DeRestWidget::DeRestWidget(QWidget *parent) : QDialog(parent), ui(new Ui::DeWebWidget) { ui->setupUi(this); setWindowTitle(tr("DE REST API")); deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance(); quint16 httpPort = apsCtrl ? deCONZ::ApsController::instance()->getParameter(deCONZ::ParamHttpPort) : 0; ui->ipAddressesLabel->setTextFormat(Qt::RichText); ui->ipAddressesLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->ipAddressesLabel->setOpenExternalLinks(true); ui->gitCommitLabel->setText(QLatin1String(GIT_COMMMIT)); QString str; QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces(); QList<QNetworkInterface>::Iterator ifi = ifaces.begin(); QList<QNetworkInterface>::Iterator ifend = ifaces.end(); for (; ifi != ifend; ++ifi) { QString name = ifi->humanReadableName(); // filter if (name.contains("vm", Qt::CaseInsensitive) || name.contains("virtual", Qt::CaseInsensitive) || name.contains("loop", Qt::CaseInsensitive)) { continue; } QList<QNetworkAddressEntry> addr = ifi->addressEntries(); QList<QNetworkAddressEntry>::Iterator i = addr.begin(); QList<QNetworkAddressEntry>::Iterator end = addr.end(); for (; i != end; ++i) { QHostAddress a = i->ip(); if (a.protocol() == QAbstractSocket::IPv4Protocol) { QString url = QString("http://%1:%2").arg(a.toString()).arg(httpPort); str.append("<b>"); str.append(ifi->humanReadableName()); str.append("</b>&nbsp;&nbsp;&nbsp;&nbsp;"); str.append(QString("<a href=\"%1\">%2</a><br/>").arg(url).arg(url)); } } } if (httpPort == 0) { str = tr("No HTTP server is running"); } ui->ipAddressesLabel->setText(str); } /*! Deconstructor. */ DeRestWidget::~DeRestWidget() { Q_ASSERT(ui); delete ui; ui = nullptr; } /*! Returns true if the plugin is active. */ bool DeRestWidget::pluginActive() const { if (ui) { return ui->pluginActiveCheckBox->isChecked(); } return false; } void DeRestWidget::showEvent(QShowEvent *) { deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance(); if (!apsCtrl) { return; } QByteArray sec0 = apsCtrl->getParameter(deCONZ::ParamSecurityMaterial0); if (!sec0.isEmpty()) { QByteArray installCode; for (int i = 0; i < 4; i++) { installCode += sec0.mid(i * 4, 4); if (i < 3) { installCode += ' '; } } ui->labelInstallCode->setText(installCode); } else { ui->labelInstallCode->setText(tr("not available")); } } <commit_msg>Plugin dialog: filter more irrelevant network interfaces<commit_after>/* * Copyright (c) 2013-2020 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QLabel> #include <QNetworkInterface> #include "de_web_plugin.h" #include "de_web_widget.h" #include "ui_de_web_widget.h" /*! Constructor. */ DeRestWidget::DeRestWidget(QWidget *parent) : QDialog(parent), ui(new Ui::DeWebWidget) { ui->setupUi(this); setWindowTitle(tr("DE REST API")); deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance(); quint16 httpPort = apsCtrl ? deCONZ::ApsController::instance()->getParameter(deCONZ::ParamHttpPort) : 0; ui->ipAddressesLabel->setTextFormat(Qt::RichText); ui->ipAddressesLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->ipAddressesLabel->setOpenExternalLinks(true); ui->gitCommitLabel->setText(QLatin1String(GIT_COMMMIT)); QString str; QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces(); QList<QNetworkInterface>::Iterator ifi = ifaces.begin(); QList<QNetworkInterface>::Iterator ifend = ifaces.end(); for (; ifi != ifend; ++ifi) { QString name = ifi->humanReadableName(); // filter if (name.contains("br-", Qt::CaseInsensitive) || name.contains("docker", Qt::CaseInsensitive) || name.contains("vm", Qt::CaseInsensitive) || name.contains("virtual", Qt::CaseInsensitive) || name.contains("loop", Qt::CaseInsensitive)) { continue; } QList<QNetworkAddressEntry> addr = ifi->addressEntries(); QList<QNetworkAddressEntry>::Iterator i = addr.begin(); QList<QNetworkAddressEntry>::Iterator end = addr.end(); for (; i != end; ++i) { QHostAddress a = i->ip(); if (a.protocol() == QAbstractSocket::IPv4Protocol) { QString url = QString("http://%1:%2").arg(a.toString()).arg(httpPort); str.append("<b>"); str.append(ifi->humanReadableName()); str.append("</b>&nbsp;&nbsp;&nbsp;&nbsp;"); str.append(QString("<a href=\"%1\">%2</a><br/>").arg(url).arg(url)); } } } if (httpPort == 0) { str = tr("No HTTP server is running"); } ui->ipAddressesLabel->setText(str); } /*! Deconstructor. */ DeRestWidget::~DeRestWidget() { Q_ASSERT(ui); delete ui; ui = nullptr; } /*! Returns true if the plugin is active. */ bool DeRestWidget::pluginActive() const { if (ui) { return ui->pluginActiveCheckBox->isChecked(); } return false; } void DeRestWidget::showEvent(QShowEvent *) { deCONZ::ApsController *apsCtrl = deCONZ::ApsController::instance(); if (!apsCtrl) { return; } QByteArray sec0 = apsCtrl->getParameter(deCONZ::ParamSecurityMaterial0); if (!sec0.isEmpty()) { QByteArray installCode; for (int i = 0; i < 4; i++) { installCode += sec0.mid(i * 4, 4); if (i < 3) { installCode += ' '; } } ui->labelInstallCode->setText(installCode); } else { ui->labelInstallCode->setText(tr("not available")); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qdebug.h> #include "qnativeimage_p.h" #include "qcolormap.h" #include "private/qpaintengine_raster_p.h" #if defined(Q_WS_X11) && !defined(QT_NO_MITSHM) #include <qx11info_x11.h> #include <sys/ipc.h> #include <sys/shm.h> #include <qwidget.h> #endif #ifdef Q_WS_MAC #include <private/qpaintengine_mac_p.h> #endif QT_BEGIN_NAMESPACE #ifdef Q_WS_WIN typedef struct { BITMAPINFOHEADER bmiHeader; DWORD redMask; DWORD greenMask; DWORD blueMask; } BITMAPINFO_MASK; QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool isTextBuffer, QWidget *) { #ifndef Q_WS_WINCE Q_UNUSED(isTextBuffer); #endif BITMAPINFO_MASK bmi; memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biSizeImage = 0; if (format == QImage::Format_RGB16) { bmi.bmiHeader.biBitCount = 16; #ifdef Q_WS_WINCE if (isTextBuffer) { bmi.bmiHeader.biCompression = BI_RGB; bmi.redMask = 0; bmi.greenMask = 0; bmi.blueMask = 0; } else #endif { bmi.bmiHeader.biCompression = BI_BITFIELDS; bmi.redMask = 0xF800; bmi.greenMask = 0x07E0; bmi.blueMask = 0x001F; } } else { bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.redMask = 0; bmi.greenMask = 0; bmi.blueMask = 0; } HDC display_dc = GetDC(0); hdc = CreateCompatibleDC(display_dc); ReleaseDC(0, display_dc); Q_ASSERT(hdc); uchar *bits = 0; bitmap = CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO *>(&bmi), DIB_RGB_COLORS, (void**) &bits, 0, 0); Q_ASSERT(bitmap); Q_ASSERT(bits); null_bitmap = (HBITMAP)SelectObject(hdc, bitmap); image = QImage(bits, width, height, format); Q_ASSERT(image.paintEngine()->type() == QPaintEngine::Raster); static_cast<QRasterPaintEngine *>(image.paintEngine())->setDC(hdc); #ifndef Q_WS_WINCE GdiFlush(); #endif } QNativeImage::~QNativeImage() { if (bitmap || hdc) { Q_ASSERT(hdc); Q_ASSERT(bitmap); if (null_bitmap) SelectObject(hdc, null_bitmap); DeleteDC(hdc); DeleteObject(bitmap); } } QImage::Format QNativeImage::systemFormat() { if (QColormap::instance().depth() == 16) return QImage::Format_RGB16; return QImage::Format_RGB32; } #elif defined(Q_WS_X11) && !defined(QT_NO_MITSHM) QNativeImage::QNativeImage(int width, int height, QImage::Format format,bool /* isTextBuffer */, QWidget *widget) : xshmimg(0), xshmpm(0) { if (!X11->use_mitshm) { image = QImage(width, height, format); // follow good coding practice and set xshminfo attributes, though values not used in this case xshminfo.readOnly = true; xshminfo.shmaddr = 0; xshminfo.shmid = 0; xshminfo.shmseg = 0; return; } QX11Info info = widget->x11Info(); int dd = info.depth(); Visual *vis = (Visual*) info.visual(); xshmimg = XShmCreateImage(X11->display, vis, dd, ZPixmap, 0, &xshminfo, width, height); if (!xshmimg) { qWarning("QNativeImage: Unable to create shared XImage."); return; } bool ok; xshminfo.shmid = shmget(IPC_PRIVATE, xshmimg->bytes_per_line * xshmimg->height, IPC_CREAT | 0777); ok = xshminfo.shmid != -1; if (ok) { xshmimg->data = (char*)shmat(xshminfo.shmid, 0, 0); xshminfo.shmaddr = xshmimg->data; if (shmctl(xshminfo.shmid, IPC_RMID, 0) == -1) qWarning() << "Error while marking the shared memory segment to be destroyed"; ok = (xshminfo.shmaddr != (char*)-1); if (ok) image = QImage((uchar *)xshmimg->data, width, height, systemFormat()); } xshminfo.readOnly = false; if (ok) ok = XShmAttach(X11->display, &xshminfo); if (!ok) { qWarning() << "QNativeImage: Unable to attach to shared memory segment."; if (xshmimg->data) { free(xshmimg->data); xshmimg->data = 0; } XDestroyImage(xshmimg); xshmimg = 0; if (xshminfo.shmaddr) shmdt(xshminfo.shmaddr); if (xshminfo.shmid != -1) shmctl(xshminfo.shmid, IPC_RMID, 0); return; } if (X11->use_mitshm_pixmaps) { xshmpm = XShmCreatePixmap(X11->display, DefaultRootWindow(X11->display), xshmimg->data, &xshminfo, width, height, dd); if (!xshmpm) { qWarning() << "QNativeImage: Unable to create shared Pixmap."; } } } QNativeImage::~QNativeImage() { if (!xshmimg) return; if (xshmpm) { XFreePixmap(X11->display, xshmpm); xshmpm = 0; } XShmDetach(X11->display, &xshminfo); xshmimg->data = 0; XDestroyImage(xshmimg); xshmimg = 0; shmdt(xshminfo.shmaddr); shmctl(xshminfo.shmid, IPC_RMID, 0); } QImage::Format QNativeImage::systemFormat() { if (QX11Info::appDepth() == 16) return QImage::Format_RGB16; return QImage::Format_RGB32; } #elif defined(Q_WS_MAC) QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool /* isTextBuffer */, QWidget *widget) : image(width, height, format) { uint cgflags = kCGImageAlphaNoneSkipFirst; #ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version cgflags |= kCGBitmapByteOrder32Host; #endif cg = CGBitmapContextCreate(image.bits(), width, height, 8, image.bytesPerLine(), QCoreGraphicsPaintEngine::macDisplayColorSpace(widget), cgflags); CGContextTranslateCTM(cg, 0, height); CGContextScaleCTM(cg, 1, -1); Q_ASSERT(image.paintEngine()->type() == QPaintEngine::Raster); static_cast<QRasterPaintEngine *>(image.paintEngine())->setCGContext(cg); } QNativeImage::~QNativeImage() { CGContextRelease(cg); } QImage::Format QNativeImage::systemFormat() { return QImage::Format_RGB32; } #else // other platforms... QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool /* isTextBuffer */, QWidget *) : image(width, height, format) { } QNativeImage::~QNativeImage() { } QImage::Format QNativeImage::systemFormat() { return QImage::Format_RGB32; } #endif // platforms QT_END_NAMESPACE <commit_msg>Fixed translucent window rendering on 16 bit X11.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qdebug.h> #include "qnativeimage_p.h" #include "qcolormap.h" #include "private/qpaintengine_raster_p.h" #if defined(Q_WS_X11) && !defined(QT_NO_MITSHM) #include <qx11info_x11.h> #include <sys/ipc.h> #include <sys/shm.h> #include <qwidget.h> #endif #ifdef Q_WS_MAC #include <private/qpaintengine_mac_p.h> #endif QT_BEGIN_NAMESPACE #ifdef Q_WS_WIN typedef struct { BITMAPINFOHEADER bmiHeader; DWORD redMask; DWORD greenMask; DWORD blueMask; } BITMAPINFO_MASK; QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool isTextBuffer, QWidget *) { #ifndef Q_WS_WINCE Q_UNUSED(isTextBuffer); #endif BITMAPINFO_MASK bmi; memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biSizeImage = 0; if (format == QImage::Format_RGB16) { bmi.bmiHeader.biBitCount = 16; #ifdef Q_WS_WINCE if (isTextBuffer) { bmi.bmiHeader.biCompression = BI_RGB; bmi.redMask = 0; bmi.greenMask = 0; bmi.blueMask = 0; } else #endif { bmi.bmiHeader.biCompression = BI_BITFIELDS; bmi.redMask = 0xF800; bmi.greenMask = 0x07E0; bmi.blueMask = 0x001F; } } else { bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.redMask = 0; bmi.greenMask = 0; bmi.blueMask = 0; } HDC display_dc = GetDC(0); hdc = CreateCompatibleDC(display_dc); ReleaseDC(0, display_dc); Q_ASSERT(hdc); uchar *bits = 0; bitmap = CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO *>(&bmi), DIB_RGB_COLORS, (void**) &bits, 0, 0); Q_ASSERT(bitmap); Q_ASSERT(bits); null_bitmap = (HBITMAP)SelectObject(hdc, bitmap); image = QImage(bits, width, height, format); Q_ASSERT(image.paintEngine()->type() == QPaintEngine::Raster); static_cast<QRasterPaintEngine *>(image.paintEngine())->setDC(hdc); #ifndef Q_WS_WINCE GdiFlush(); #endif } QNativeImage::~QNativeImage() { if (bitmap || hdc) { Q_ASSERT(hdc); Q_ASSERT(bitmap); if (null_bitmap) SelectObject(hdc, null_bitmap); DeleteDC(hdc); DeleteObject(bitmap); } } QImage::Format QNativeImage::systemFormat() { if (QColormap::instance().depth() == 16) return QImage::Format_RGB16; return QImage::Format_RGB32; } #elif defined(Q_WS_X11) && !defined(QT_NO_MITSHM) QNativeImage::QNativeImage(int width, int height, QImage::Format format,bool /* isTextBuffer */, QWidget *widget) : xshmimg(0), xshmpm(0) { if (!X11->use_mitshm) { image = QImage(width, height, format); // follow good coding practice and set xshminfo attributes, though values not used in this case xshminfo.readOnly = true; xshminfo.shmaddr = 0; xshminfo.shmid = 0; xshminfo.shmseg = 0; return; } QX11Info info = widget->x11Info(); int dd = info.depth(); Visual *vis = (Visual*) info.visual(); xshmimg = XShmCreateImage(X11->display, vis, dd, ZPixmap, 0, &xshminfo, width, height); if (!xshmimg) { qWarning("QNativeImage: Unable to create shared XImage."); return; } bool ok; xshminfo.shmid = shmget(IPC_PRIVATE, xshmimg->bytes_per_line * xshmimg->height, IPC_CREAT | 0777); ok = xshminfo.shmid != -1; if (ok) { xshmimg->data = (char*)shmat(xshminfo.shmid, 0, 0); xshminfo.shmaddr = xshmimg->data; if (shmctl(xshminfo.shmid, IPC_RMID, 0) == -1) qWarning() << "Error while marking the shared memory segment to be destroyed"; ok = (xshminfo.shmaddr != (char*)-1); if (ok) image = QImage((uchar *)xshmimg->data, width, height, format); } xshminfo.readOnly = false; if (ok) ok = XShmAttach(X11->display, &xshminfo); if (!ok) { qWarning() << "QNativeImage: Unable to attach to shared memory segment."; if (xshmimg->data) { free(xshmimg->data); xshmimg->data = 0; } XDestroyImage(xshmimg); xshmimg = 0; if (xshminfo.shmaddr) shmdt(xshminfo.shmaddr); if (xshminfo.shmid != -1) shmctl(xshminfo.shmid, IPC_RMID, 0); return; } if (X11->use_mitshm_pixmaps) { xshmpm = XShmCreatePixmap(X11->display, DefaultRootWindow(X11->display), xshmimg->data, &xshminfo, width, height, dd); if (!xshmpm) { qWarning() << "QNativeImage: Unable to create shared Pixmap."; } } } QNativeImage::~QNativeImage() { if (!xshmimg) return; if (xshmpm) { XFreePixmap(X11->display, xshmpm); xshmpm = 0; } XShmDetach(X11->display, &xshminfo); xshmimg->data = 0; XDestroyImage(xshmimg); xshmimg = 0; shmdt(xshminfo.shmaddr); shmctl(xshminfo.shmid, IPC_RMID, 0); } QImage::Format QNativeImage::systemFormat() { if (QX11Info::appDepth() == 16) return QImage::Format_RGB16; return QImage::Format_RGB32; } #elif defined(Q_WS_MAC) QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool /* isTextBuffer */, QWidget *widget) : image(width, height, format) { uint cgflags = kCGImageAlphaNoneSkipFirst; #ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version cgflags |= kCGBitmapByteOrder32Host; #endif cg = CGBitmapContextCreate(image.bits(), width, height, 8, image.bytesPerLine(), QCoreGraphicsPaintEngine::macDisplayColorSpace(widget), cgflags); CGContextTranslateCTM(cg, 0, height); CGContextScaleCTM(cg, 1, -1); Q_ASSERT(image.paintEngine()->type() == QPaintEngine::Raster); static_cast<QRasterPaintEngine *>(image.paintEngine())->setCGContext(cg); } QNativeImage::~QNativeImage() { CGContextRelease(cg); } QImage::Format QNativeImage::systemFormat() { return QImage::Format_RGB32; } #else // other platforms... QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool /* isTextBuffer */, QWidget *) : image(width, height, format) { } QNativeImage::~QNativeImage() { } QImage::Format QNativeImage::systemFormat() { return QImage::Format_RGB32; } #endif // platforms QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "Platform.hpp" #include <boost/log/trivial.hpp> namespace Slic3r { static auto s_platform = Platform::Uninitialized; static auto s_platform_flavor = PlatformFlavor::Uninitialized; void detect_platform() { #if defined(_WIN32) BOOST_LOG_TRIVIAL(info) << "Platform: Windows"; s_platform = Platform::Windows; s_platform_flavor = PlatformFlavor::Generic; #elif defined(__APPLE__) BOOST_LOG_TRIVIAL(info) << "Platform: OSX"; s_platform = Platform::OSX; s_platform_flavor = PlatformFlavor::Generic; #elif defined(__linux__) BOOST_LOG_TRIVIAL(info) << "Platform: Linux"; s_platform = Platform::Linux; s_platform_flavor = PlatformFlavor::GenericLinux; // Test for Chromium. { FILE *f = ::fopen("/proc/version", "rt"); if (f) { char buf[4096]; // Read the 1st line. if (::fgets(buf, 4096, f)) { if (strstr(buf, "Chromium OS") != nullptr) { s_platform_flavor = PlatformFlavor::LinuxOnChromium; BOOST_LOG_TRIVIAL(info) << "Platform flavor: LinuxOnChromium"; } else if (strstr(buf, "microsoft") != nullptr || strstr(buf, "Microsoft") != nullptr) { if (boost::filesystem::exists("/run/WSL") && getenv("WSL_INTEROP") != nullptr) { BOOST_LOG_TRIVIAL(info) << "Platform flavor: WSL2"; s_platform_flavor = PlatformFlavor::WSL2; } else { BOOST_LOG_TRIVIAL(info) << "Platform flavor: WSL"; s_platform_flavor = PlatformFlavor::WSL; } } } ::fclose(f); } } #elif defined(__OpenBSD__) BOOST_LOG_TRIVIAL(info) << "Platform: OpenBSD"; s_platform = Platform::BSDUnix; s_platform_flavor = PlatformFlavor::OpenBSD; #else // This should not happen. BOOST_LOG_TRIVIAL(info) << "Platform: Unknown"; static_assert(false, "Unknown platform detected"); s_platform = Platform::Unknown; s_platform_flavor = PlatformFlavor::Unknown; #endif } Platform platform() { return s_platform; } PlatformFlavor platform_flavor() { return s_platform_flavor; } } // namespace Slic3r <commit_msg>Added a missing include (Linux)<commit_after>#include "Platform.hpp" #include <boost/log/trivial.hpp> #include <boost/filesystem/operations.hpp> namespace Slic3r { static auto s_platform = Platform::Uninitialized; static auto s_platform_flavor = PlatformFlavor::Uninitialized; void detect_platform() { #if defined(_WIN32) BOOST_LOG_TRIVIAL(info) << "Platform: Windows"; s_platform = Platform::Windows; s_platform_flavor = PlatformFlavor::Generic; #elif defined(__APPLE__) BOOST_LOG_TRIVIAL(info) << "Platform: OSX"; s_platform = Platform::OSX; s_platform_flavor = PlatformFlavor::Generic; #elif defined(__linux__) BOOST_LOG_TRIVIAL(info) << "Platform: Linux"; s_platform = Platform::Linux; s_platform_flavor = PlatformFlavor::GenericLinux; // Test for Chromium. { FILE *f = ::fopen("/proc/version", "rt"); if (f) { char buf[4096]; // Read the 1st line. if (::fgets(buf, 4096, f)) { if (strstr(buf, "Chromium OS") != nullptr) { s_platform_flavor = PlatformFlavor::LinuxOnChromium; BOOST_LOG_TRIVIAL(info) << "Platform flavor: LinuxOnChromium"; } else if (strstr(buf, "microsoft") != nullptr || strstr(buf, "Microsoft") != nullptr) { if (boost::filesystem::exists("/run/WSL") && getenv("WSL_INTEROP") != nullptr) { BOOST_LOG_TRIVIAL(info) << "Platform flavor: WSL2"; s_platform_flavor = PlatformFlavor::WSL2; } else { BOOST_LOG_TRIVIAL(info) << "Platform flavor: WSL"; s_platform_flavor = PlatformFlavor::WSL; } } } ::fclose(f); } } #elif defined(__OpenBSD__) BOOST_LOG_TRIVIAL(info) << "Platform: OpenBSD"; s_platform = Platform::BSDUnix; s_platform_flavor = PlatformFlavor::OpenBSD; #else // This should not happen. BOOST_LOG_TRIVIAL(info) << "Platform: Unknown"; static_assert(false, "Unknown platform detected"); s_platform = Platform::Unknown; s_platform_flavor = PlatformFlavor::Unknown; #endif } Platform platform() { return s_platform; } PlatformFlavor platform_flavor() { return s_platform_flavor; } } // namespace Slic3r <|endoftext|>
<commit_before>/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * libparaver-api * * Paraver Main Computing Library * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ /* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\ | @file: $HeadURL$ | @last_commit: $Date$ | @version: $Revision$ \* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */ #include "kwindow.h" #include "intervalcontrolderived.h" KRecordList *IntervalControlDerived::init( TRecordTime initialTime, TCreateList create, KRecordList *displayList ) { TRecordTime myInitTime; SemanticHighInfo info; createList = create; currentValue = 0.0; if ( displayList == NULL ) displayList = &myDisplayList; function = ( SemanticDerived * ) window->getSemanticFunction( level ); setChilds(); if ( begin != NULL ) { delete begin; begin = NULL; } if ( end != NULL ) { delete end; end = NULL; } if ( function->getInitFromBegin() ) myInitTime = 0.0; else myInitTime = initialTime; info.callingInterval = this; childIntervals[ 0 ]->init( myInitTime, createList, displayList ); childIntervals[ 1 ]->init( myInitTime, createList, displayList ); if ( window->getLevel() >= SYSTEM ) { begin = window->copyCPUIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyCPUIterator( childIntervals[ 1 ]->getEnd() ); } else { begin = window->copyThreadIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyThreadIterator( childIntervals[ 1 ]->getEnd() ); } while ( childIntervals[ 0 ]->getEnd()->getTime() < begin->getTime() ) childIntervals[ 0 ]->calcNext( displayList ); if ( childIntervals[ 0 ]->getEnd()->getTime() > begin->getTime() ) { info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( childIntervals[ 0 ]->getEnd()->getTime() < end->getTime() ) { childIntervals[ 0 ]->calcNext( displayList ); info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( end->getTime() < initialTime ) calcNext( displayList ); return displayList; } KRecordList *IntervalControlDerived::calcNext( KRecordList *displayList, bool initCalc ) { SemanticHighInfo info; currentValue = 0; if ( displayList == NULL ) displayList = &myDisplayList; if ( begin != NULL ) { delete begin; begin = NULL; } if ( end != NULL ) { delete end; end = NULL; } info.callingInterval = this; childIntervals[ 1 ]->calcNext( displayList ); if ( window->getLevel() >= SYSTEM ) { begin = window->copyCPUIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyCPUIterator( childIntervals[ 1 ]->getEnd() ); } else { begin = window->copyThreadIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyThreadIterator( childIntervals[ 1 ]->getEnd() ); } if( begin->getTime() == window->getTrace()->getEndTime() ) return displayList; while ( childIntervals[ 0 ]->getEnd()->getTime() <= begin->getTime() ) childIntervals[ 0 ]->calcNext( displayList ); if ( childIntervals[ 0 ]->getEnd()->getTime() > begin->getTime() ) { info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( childIntervals[ 0 ]->getEnd()->getTime() < end->getTime() ) { childIntervals[ 0 ]->calcNext( displayList ); info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } return displayList; } KRecordList *IntervalControlDerived::calcPrev( KRecordList *displayList, bool initCalc ) { SemanticHighInfo info; currentValue = 0; if ( displayList == NULL ) displayList = &myDisplayList; if ( begin != NULL ) { delete begin; begin = NULL; } if ( end != NULL ) { delete end; end = NULL; } info.callingInterval = this; childIntervals[ 1 ]->calcPrev( displayList ); if ( window->getLevel() >= SYSTEM ) { begin = window->copyCPUIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyCPUIterator( childIntervals[ 1 ]->getEnd() ); } else { begin = window->copyThreadIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyThreadIterator( childIntervals[ 1 ]->getEnd() ); } while ( childIntervals[ 0 ]->getEnd()->getTime() <= begin->getTime() ) childIntervals[ 0 ]->calcPrev( displayList ); if ( childIntervals[ 0 ]->getEnd()->getTime() > begin->getTime() ) { info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( childIntervals[ 0 ]->getEnd()->getTime() < end->getTime() ) { childIntervals[ 0 ]->calcPrev( displayList ); info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } return displayList; } TWindowLevel IntervalControlDerived::getWindowLevel() const { return window->getLevel(); } Interval *IntervalControlDerived::getWindowInterval( TWindowLevel whichLevel, TObjectOrder whichOrder ) { return window->getLevelInterval( whichLevel, whichOrder ); } bool IntervalControlDerived::IsDerivedWindow() const { return window->isDerivedWindow(); } TWindowLevel IntervalControlDerived::getComposeLevel( TWindowLevel whichLevel ) const { return window->getComposeLevel( whichLevel ); } KTrace *IntervalControlDerived::getWindowTrace() const { return (KTrace*)window->getTrace(); } void IntervalControlDerived::setChilds() { KWindow *window1; KWindow *window2; TApplOrder tmpAppl; TTaskOrder tmpTask; TThreadOrder tmpThread; TNodeOrder tmpNode; TCPUOrder tmpCPU; childIntervals.clear(); if ( window->getParent( 0 )->getLevel() > window->getParent( 1 )->getLevel() ) { window1 = ( KWindow * ) window->getParent( 0 ); window2 = ( KWindow * ) window->getParent( 1 ); } else { window1 = ( KWindow * ) window->getParent( 1 ); window2 = ( KWindow * ) window->getParent( 0 ); } if ( window1->getLevel() == APPLICATION ) { tmpAppl = order; } else if ( window1->getLevel() == TASK ) { window1->getTrace()->getTaskLocation( order, tmpAppl, tmpTask ); } else if ( window1->getLevel() == THREAD ) { window1->getTrace()->getThreadLocation( order, tmpAppl, tmpTask, tmpThread ); } else if ( window1->getLevel() == NODE ) { tmpNode = order; } else if ( window1->getLevel() == CPU ) { window1->getTrace()->getCPULocation( order, tmpNode, tmpCPU ); } if ( window1 == window->getParent( 0 ) ) childIntervals.push_back( window1->getLevelInterval( TOPCOMPOSE1, order ) ); if ( window2->getLevel() == WORKLOAD ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, 0 ) ); } else if ( window2->getLevel() == APPLICATION ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, tmpAppl ) ); } else if ( window2->getLevel() == TASK ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, window2->getTrace()->getGlobalTask( tmpAppl, tmpTask ) ) ); } else if ( window2->getLevel() == THREAD ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, window2->getTrace()->getGlobalThread( tmpAppl, tmpTask, tmpThread ) ) ); } else if ( window2->getLevel() == SYSTEM ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, 0 ) ); } else if ( window2->getLevel() == NODE ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, tmpNode ) ); } else if ( window2->getLevel() == CPU ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, window2->getTrace()->getGlobalCPU( tmpNode, tmpCPU ) ) ); } if ( window1 == window->getParent( 1 ) ) childIntervals.push_back( window1->getLevelInterval( TOPCOMPOSE1, order ) ); } <commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * libparaver-api * * Paraver Main Computing Library * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ /* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\ | @file: $HeadURL$ | @last_commit: $Date$ | @version: $Revision$ \* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */ #include "kwindow.h" #include "intervalcontrolderived.h" KRecordList *IntervalControlDerived::init( TRecordTime initialTime, TCreateList create, KRecordList *displayList ) { TRecordTime myInitTime; SemanticHighInfo info; createList = create; currentValue = 0.0; if ( displayList == NULL ) displayList = &myDisplayList; function = ( SemanticDerived * ) window->getSemanticFunction( level ); setChilds(); if ( begin != NULL ) { delete begin; begin = NULL; } if ( end != NULL ) { delete end; end = NULL; } if ( function->getInitFromBegin() ) myInitTime = 0.0; else myInitTime = initialTime; info.callingInterval = this; childIntervals[ 1 ]->init( myInitTime, createList, displayList ); childIntervals[ 0 ]->init( childIntervals[ 1 ]->getBegin()->getTime(), createList, displayList ); if ( window->getLevel() >= SYSTEM ) { begin = window->copyCPUIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyCPUIterator( childIntervals[ 1 ]->getEnd() ); } else { begin = window->copyThreadIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyThreadIterator( childIntervals[ 1 ]->getEnd() ); } while ( childIntervals[ 0 ]->getEnd()->getTime() > begin->getTime() ) childIntervals[ 0 ]->calcPrev( displayList ); while ( childIntervals[ 0 ]->getEnd()->getTime() < begin->getTime() ) childIntervals[ 0 ]->calcNext( displayList ); if ( childIntervals[ 0 ]->getEnd()->getTime() > begin->getTime() ) { info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( childIntervals[ 0 ]->getEnd()->getTime() < end->getTime() ) { childIntervals[ 0 ]->calcNext( displayList ); info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( end->getTime() < initialTime ) calcNext( displayList ); return displayList; } KRecordList *IntervalControlDerived::calcNext( KRecordList *displayList, bool initCalc ) { SemanticHighInfo info; currentValue = 0; if ( displayList == NULL ) displayList = &myDisplayList; if ( begin != NULL ) { delete begin; begin = NULL; } if ( end != NULL ) { delete end; end = NULL; } info.callingInterval = this; childIntervals[ 1 ]->calcNext( displayList ); if ( window->getLevel() >= SYSTEM ) { begin = window->copyCPUIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyCPUIterator( childIntervals[ 1 ]->getEnd() ); } else { begin = window->copyThreadIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyThreadIterator( childIntervals[ 1 ]->getEnd() ); } if( begin->getTime() == window->getTrace()->getEndTime() ) return displayList; while ( childIntervals[ 0 ]->getEnd()->getTime() <= begin->getTime() ) childIntervals[ 0 ]->calcNext( displayList ); if ( childIntervals[ 0 ]->getEnd()->getTime() > begin->getTime() ) { info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( childIntervals[ 0 ]->getEnd()->getTime() < end->getTime() ) { childIntervals[ 0 ]->calcNext( displayList ); info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } return displayList; } KRecordList *IntervalControlDerived::calcPrev( KRecordList *displayList, bool initCalc ) { SemanticHighInfo info; currentValue = 0; if ( displayList == NULL ) displayList = &myDisplayList; if ( begin != NULL ) { delete begin; begin = NULL; } if ( end != NULL ) { delete end; end = NULL; } info.callingInterval = this; childIntervals[ 1 ]->calcPrev( displayList ); if ( window->getLevel() >= SYSTEM ) { begin = window->copyCPUIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyCPUIterator( childIntervals[ 1 ]->getEnd() ); } else { begin = window->copyThreadIterator( childIntervals[ 1 ]->getBegin() ); end = window->copyThreadIterator( childIntervals[ 1 ]->getEnd() ); } while ( childIntervals[ 0 ]->getEnd()->getTime() <= begin->getTime() ) childIntervals[ 0 ]->calcPrev( displayList ); if ( childIntervals[ 0 ]->getEnd()->getTime() > begin->getTime() ) { info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } while ( childIntervals[ 0 ]->getEnd()->getTime() < end->getTime() ) { childIntervals[ 0 ]->calcPrev( displayList ); info.values.clear(); info.values.push_back( currentValue ); info.values.push_back( childIntervals[ 0 ]->getValue() * window->getFactor( 0 ) ); currentValue = function->execute( &info ); } return displayList; } TWindowLevel IntervalControlDerived::getWindowLevel() const { return window->getLevel(); } Interval *IntervalControlDerived::getWindowInterval( TWindowLevel whichLevel, TObjectOrder whichOrder ) { return window->getLevelInterval( whichLevel, whichOrder ); } bool IntervalControlDerived::IsDerivedWindow() const { return window->isDerivedWindow(); } TWindowLevel IntervalControlDerived::getComposeLevel( TWindowLevel whichLevel ) const { return window->getComposeLevel( whichLevel ); } KTrace *IntervalControlDerived::getWindowTrace() const { return (KTrace*)window->getTrace(); } void IntervalControlDerived::setChilds() { KWindow *window1; KWindow *window2; TApplOrder tmpAppl; TTaskOrder tmpTask; TThreadOrder tmpThread; TNodeOrder tmpNode; TCPUOrder tmpCPU; childIntervals.clear(); if ( window->getParent( 0 )->getLevel() > window->getParent( 1 )->getLevel() ) { window1 = ( KWindow * ) window->getParent( 0 ); window2 = ( KWindow * ) window->getParent( 1 ); } else { window1 = ( KWindow * ) window->getParent( 1 ); window2 = ( KWindow * ) window->getParent( 0 ); } if ( window1->getLevel() == APPLICATION ) { tmpAppl = order; } else if ( window1->getLevel() == TASK ) { window1->getTrace()->getTaskLocation( order, tmpAppl, tmpTask ); } else if ( window1->getLevel() == THREAD ) { window1->getTrace()->getThreadLocation( order, tmpAppl, tmpTask, tmpThread ); } else if ( window1->getLevel() == NODE ) { tmpNode = order; } else if ( window1->getLevel() == CPU ) { window1->getTrace()->getCPULocation( order, tmpNode, tmpCPU ); } if ( window1 == window->getParent( 0 ) ) childIntervals.push_back( window1->getLevelInterval( TOPCOMPOSE1, order ) ); if ( window2->getLevel() == WORKLOAD ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, 0 ) ); } else if ( window2->getLevel() == APPLICATION ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, tmpAppl ) ); } else if ( window2->getLevel() == TASK ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, window2->getTrace()->getGlobalTask( tmpAppl, tmpTask ) ) ); } else if ( window2->getLevel() == THREAD ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, window2->getTrace()->getGlobalThread( tmpAppl, tmpTask, tmpThread ) ) ); } else if ( window2->getLevel() == SYSTEM ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, 0 ) ); } else if ( window2->getLevel() == NODE ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, tmpNode ) ); } else if ( window2->getLevel() == CPU ) { childIntervals.push_back( window2->getLevelInterval( TOPCOMPOSE1, window2->getTrace()->getGlobalCPU( tmpNode, tmpCPU ) ) ); } if ( window1 == window->getParent( 1 ) ) childIntervals.push_back( window1->getLevelInterval( TOPCOMPOSE1, order ) ); } <|endoftext|>
<commit_before>/***************objectmarker.cpp****************** Object marker for creating a list of ROIs to use for (e.g.) OpenCV cascade training. Requires OpenCV, and various common C/C++ libraries. author: [email protected] originally based on objectmarker.cpp by: [email protected] */ #include <opencv/cv.h> #include <opencv/cvaux.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdio.h> #include <sys/uio.h> #include <string> #include <fstream> #include <sstream> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> using namespace cv; using namespace std; Mat image; Mat image2; Mat image3; int max_height = 800; float scale_factor = 1; int roi_x0=0; int roi_y0=0; int roi_x1=0; int roi_y1=0; int numOfRec=0; int startDraw = 0; int aspect_x = 1; int aspect_y = 1; int mod_x = 0; int mod_y = 0; string window_name=""; void on_mouse(int event,int x,int y,int flag, void *param) { if ( event == CV_EVENT_LBUTTONDOWN ) { if ( !startDraw ) { roi_x0=x; roi_y0=y; startDraw = 1; } else { roi_x1=x; roi_y1=y; // enforce ROI aspect ratio if ( ( (roi_x0 > x) && (roi_y0 > y) ) || ( (roi_x0 < x) && (roi_y0 < y) ) ) roi_x1 = roi_x0 + ( aspect_x * ( roi_y1 - roi_y0 ) / aspect_y ); else roi_x1 = roi_x0 + ( aspect_x * ( roi_y0 - roi_y1 ) / aspect_y ); // redraw ROI selection in green when finished image2 = image3.clone(); rectangle( image2, cvPoint( roi_x0, roi_y0 ), cvPoint( roi_x1, roi_y1 ), CV_RGB(50,255,50), 1 ); imshow( window_name, image2 ); startDraw = 0; } } if ( event == CV_EVENT_MOUSEMOVE && startDraw ) { mod_x = x; mod_y = y; // enforce ROI aspect ratio if ( ( (roi_x0 > x) && (roi_y0 > y) ) || ( (roi_x0 < x) && (roi_y0 < y) ) ) mod_x = roi_x0 + ( aspect_x * ( mod_y - roi_y0 ) / aspect_y ); else mod_x = roi_x0 + ( aspect_x * ( roi_y0 - mod_y ) / aspect_y ); //redraw ROI selection image2 = image3.clone(); rectangle(image2,cvPoint( roi_x0, roi_y0 ),cvPoint( mod_x, mod_y ),CV_RGB(255,0,100),1); imshow(window_name,image2); } if ( event == EVENT_LBUTTONDBLCLK ) { roi_x0 = 0; roi_x1 = 0; roi_y0 = 0; roi_y1 = 0; startDraw = 0; } } int main(int argc, char** argv) { char iKey=0; string strPrefix; string strPostfix; string fullPath; string destPath; string input_directory = "."; string output_directory = "."; string pos_directory = "positive"; string neg_directory = "negative"; string positive_file = "pos.txt"; string negative_file = "neg.txt"; struct stat filestat; int c; while (optind < argc) { if ((c = getopt(argc, argv, "o:m:u:p:n:h:x:y:")) != -1) switch (c) { case 'o': output_directory = optarg; break; case 'm': pos_directory = optarg; break; case 'u': neg_directory = optarg; break; case 'p': positive_file = optarg; break; case 'n': negative_file = optarg; break; case 'h': max_height = std::stoi(optarg); break; case 'x': aspect_x = std::stoi(optarg); break; case 'y': aspect_y = std::stoi(optarg); break; case '?': if (optopt == 'd' || optopt == 'p' || optopt == 'n') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } else { input_directory = argv[optind]; optind++; } } pos_directory = output_directory + "/" + pos_directory; neg_directory = output_directory + "/" + neg_directory; positive_file = pos_directory + "/" + positive_file; negative_file = neg_directory + "/" + negative_file; /* Create output directories if necessary */ DIR *dir_d = opendir( pos_directory.c_str()); if ( dir_d == NULL ) { mkdir( pos_directory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_d); } DIR *dir_e = opendir( neg_directory.c_str()); if ( dir_e == NULL ) { mkdir( neg_directory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_e); } // Open input directory DIR *dir_p = opendir( input_directory.c_str() ); struct dirent *dir_entry_p; if(dir_p == NULL) { fprintf(stderr, "Failed to open directory %s\n", input_directory.c_str()); return -1; } // GUI window_name = "ROI Marking"; namedWindow(window_name,1); setMouseCallback(window_name,on_mouse, NULL); // init output streams ofstream positives(positive_file.c_str(), std::ofstream::out | std::ofstream::app); ofstream negatives(negative_file.c_str(), std::ofstream::out | std::ofstream::app); // Iterate over directory while((dir_entry_p = readdir(dir_p)) != NULL) { // Skip directories string relPath = input_directory + "/" + dir_entry_p->d_name; if ( stat( relPath.c_str(), &filestat ) == -1 ) continue; if (S_ISDIR( filestat.st_mode )) continue; strPostfix = ""; roi_x0 = 0; roi_x1 = 0; roi_y0 = 0; roi_y1 = 0; startDraw = 0; numOfRec = 0; scale_factor = 1; if(strcmp(dir_entry_p->d_name, "")) fprintf(stderr, "Examining file %s\n", dir_entry_p->d_name); strPrefix = dir_entry_p->d_name; fullPath = input_directory + "/" + strPrefix; printf("Loading image %s\n", strPrefix.c_str()); image = imread(fullPath.c_str(),1); if(! image.data ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; continue; } do { // Use scratch version of image for display, scaling down if necessary. Size sz = image.size(); if ( sz.height > max_height ) { scale_factor = (float)max_height / (float)sz.height; resize(image, image3, Size(), scale_factor, scale_factor, INTER_AREA); } else { image3 = image.clone(); } imshow(window_name,image3); // Start taking input iKey=cvWaitKey(0); switch(iKey) { case 27: image.release(); image2.release(); image3.release(); destroyWindow(window_name); closedir(dir_p); return 0; case 32: if ( (startDraw == 0) && (abs( roi_x0 - roi_x1 ) > 0) ) { numOfRec++; printf(" %d. rect x=%d\ty=%d\tx2h=%d\ty2=%d\tscale=%f\tstartDraw=%d\n",numOfRec,roi_x0,roi_y0,roi_x1,roi_y1, scale_factor, startDraw); strPostfix += " " + to_string( int( min(roi_x0,roi_x1) / scale_factor ) ) + " " + to_string( int( min(roi_y0,roi_y1) / scale_factor ) ) + " " + to_string( int( ( abs(roi_x1 - roi_x0) ) / scale_factor ) ) + " " + to_string( int( ( abs(roi_y1 - roi_y0) ) / scale_factor ) ); } break; } } while(iKey!=97); if (iKey==97) { if (numOfRec > 0) { positives << strPrefix << " "<< numOfRec << strPostfix <<"\n"; destPath = pos_directory + "/" + strPrefix; } else { negatives << strPrefix << "\n"; destPath = neg_directory + "/" + strPrefix; } } rename( fullPath.c_str(), destPath.c_str() ); } image.release(); image2.release(); image3.release(); destroyWindow(window_name); closedir(dir_p); return 0; } <commit_msg>Big refactor. More mouse handling improvements. User cv::Rect where appropriate. Keep a vector of ROIs that can be manipulated, rather than just appending each to a string that will get written out to file. This will let us do things like dropping an ROI after confirming it, but before moving on to next image.<commit_after>/***************objectmarker.cpp****************** Object marker for creating a list of ROIs to use for (e.g.) OpenCV cascade training. Requires OpenCV, and various common C/C++ libraries. author: [email protected] originally based on objectmarker.cpp by: [email protected] */ #include <opencv/cv.h> #include <opencv/cvaux.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdio.h> #include <sys/uio.h> #include <string> #include <fstream> #include <sstream> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> using namespace cv; using namespace std; Mat image; // original image Mat image2; // scaled image, where confirmed ROIs are built up for display Mat image3; // scratch copy of image2 to display current drawing on top of other ROIs. std::vector<Rect> rois; int max_height = 800; float scale_factor = 1; int aspect_x = 1; int aspect_y = 1; int startDraw = 0; int roi_x0=0; int roi_y0=0; int mod_x = 0; int mod_y = 0; string windowName=""; void on_mouse(int event,int x,int y,int flag, void *param) { // enforce ROI aspect ratio if ( startDraw ) { mod_y = y; if ( ( (roi_x0 > x) && (roi_y0 > y) ) || ( (roi_x0 < x) && (roi_y0 < y) ) ) mod_x = roi_x0 + ( aspect_x * ( y - roi_y0 ) / aspect_y ); else mod_x = roi_x0 + ( aspect_x * ( roi_y0 - y ) / aspect_y ); } if ( event == CV_EVENT_LBUTTONDOWN ) { if ( !startDraw ) { roi_x0=x; roi_y0=y; startDraw = 1; } else { // redraw putative ROI selection in yellow when finished. will be redrawn in green when confirmed with <space> rectangle( image3, cvPoint( roi_x0, roi_y0 ), cvPoint( mod_x, mod_y ), CV_RGB(255,255,50), 1 ); imshow( windowName, image3 ); startDraw = 0; } } if ( event == CV_EVENT_MOUSEMOVE && startDraw ) { //redraw ROI selection image3 = image2.clone(); rectangle(image3,cvPoint( roi_x0, roi_y0 ),cvPoint( mod_x, mod_y ),CV_RGB(255,5,50),1); imshow(windowName,image3); } if ( event == EVENT_LBUTTONDBLCLK ) { roi_x0 = 0; roi_y0 = 0; mod_x = 0; mod_y = 0; startDraw = 0; } } int main(int argc, char** argv) { char iKey=0; string fileForOutput; string fullPath; string destPath; string inputDirectory = "."; string outputDirectory = "."; string positiveDirectory = "positive"; string negativeDirectory = "negative"; string positiveFile = "pos.txt"; string negativeFile = "neg.txt"; struct stat filestat; int c; while (optind < argc) { if ((c = getopt(argc, argv, "o:m:u:p:n:h:x:y:")) != -1) switch (c) { case 'o': outputDirectory = optarg; break; case 'm': positiveDirectory = optarg; break; case 'u': negativeDirectory = optarg; break; case 'p': positiveFile = optarg; break; case 'n': negativeFile = optarg; break; case 'h': max_height = std::stoi(optarg); break; case 'x': aspect_x = std::stoi(optarg); break; case 'y': aspect_y = std::stoi(optarg); break; case '?': if (optopt == 'd' || optopt == 'p' || optopt == 'n') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } else { inputDirectory = argv[optind]; optind++; } } positiveDirectory = outputDirectory + "/" + positiveDirectory; negativeDirectory = outputDirectory + "/" + negativeDirectory; positiveFile = positiveDirectory + "/" + positiveFile; negativeFile = negativeDirectory + "/" + negativeFile; /* Create output directories if necessary */ DIR *dir_d = opendir( positiveDirectory.c_str()); if ( dir_d == NULL ) { mkdir( positiveDirectory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_d); } DIR *dir_e = opendir( negativeDirectory.c_str()); if ( dir_e == NULL ) { mkdir( negativeDirectory.c_str(), S_IRWXU | S_IRWXG ); } else { closedir(dir_e); } // Open input directory DIR *dir_p = opendir( inputDirectory.c_str() ); struct dirent *dir_entry_p; if(dir_p == NULL) { fprintf(stderr, "Failed to open directory %s\n", inputDirectory.c_str()); return -1; } // GUI windowName = "ROI Marking"; namedWindow(windowName,1); setMouseCallback(windowName,on_mouse,NULL); // init output streams ofstream positives(positiveFile.c_str(), std::ofstream::out | std::ofstream::app); ofstream negatives(negativeFile.c_str(), std::ofstream::out | std::ofstream::app); // Iterate over directory while((dir_entry_p = readdir(dir_p)) != NULL) { // Skip directories string relPath = inputDirectory + "/" + dir_entry_p->d_name; if ( stat( relPath.c_str(), &filestat ) == -1 ) continue; if (S_ISDIR( filestat.st_mode )) continue; // Initialize rois.clear(); roi_x0 = 0; roi_y0 = 0; startDraw = 0; scale_factor = 1; if(strcmp(dir_entry_p->d_name, "")) fprintf(stderr, "Examining file %s\n", dir_entry_p->d_name); fileForOutput = dir_entry_p->d_name; fullPath = inputDirectory + "/" + fileForOutput; printf("Loading image %s\n", fileForOutput.c_str()); image = imread(fullPath.c_str(),1); if(! image.data ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; continue; } // Use scratch version of image for display, scaling down if necessary. Size sz = image.size(); if ( sz.height > max_height ) { scale_factor = (float)max_height / (float)sz.height; resize(image, image2, Size(), scale_factor, scale_factor, INTER_AREA); } else { image2 = image.clone(); } imshow(windowName,image2); // Input loop do { iKey=cvWaitKey(0); switch(iKey) { case 27: image.release(); image2.release(); image3.release(); destroyWindow(windowName); closedir(dir_p); return 0; case 32: // <space> confirms ROI if ( (startDraw == 0) && (abs( roi_x0 - mod_x ) > 0) ) { int origin_x = min(roi_x0, mod_x); int origin_y = min(roi_y0, mod_y); int width = abs(mod_x - roi_x0); int height = abs(mod_y - roi_y0); int terminus_x = origin_x + width; int terminus_y = origin_y + height; // Scale up to map to original size rois.push_back( Rect( int( origin_x / scale_factor ), int( origin_y / scale_factor ), int( width / scale_factor ), int( height / scale_factor ) ) ); // Re-draw in green rectangle( image2, cvPoint( origin_x,origin_y ), cvPoint( terminus_x,terminus_y ), CV_RGB(50,255,50), 1 ); imshow(windowName,image2); } default: imshow(windowName,image2); break; } } while( iKey != 97 ); if ( iKey == 97 ) { if ( rois.size() > 0 ) { positives << fileForOutput << " " << to_string(rois.size()); for(std::vector<Rect>::iterator r = rois.begin(); r != rois.end(); ++r) { positives << " " << to_string(r->x) << " " << to_string(r->y) << " " << to_string(r->width) << " " << to_string(r->height); } positives << "\n"; destPath = positiveDirectory + "/" + fileForOutput; } else { negatives << fileForOutput << "\n"; destPath = negativeDirectory + "/" + fileForOutput; } } rename( fullPath.c_str(), destPath.c_str() ); } image.release(); image2.release(); image3.release(); destroyWindow(windowName); closedir(dir_p); return 0; } <|endoftext|>
<commit_before>/** * @file image_fetcher.hpp * @brief An image fetcher class implementation * @author [email protected] * @date 2013-07-01 * @copyright 2007-2014 [email protected] * @version 1.0 * * @section LICENSE * * Copyright (c) 2007-2014, Seonho Oh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #ifdef USE_OPENCV #include <opencv2/opencv.hpp> #endif #ifdef USE_BOOST #include <boost/filesystem.hpp> // for filesystem access using namespace boost::filesystem; #endif //! An auxiliary interface functions for armadillo library. namespace auxiliary { /// supporting file formats static std::string supported_file_formats("*.bmp;*.dib;*.jpeg;*.jpg;*.jpe;*.jp2;*.png;*.pbm;*.pgm;*.ppm;*.sr;*.ras;*.tiff;*.tif;"); //! defines fetch error exception class fetch_error : public std::runtime_error { public: typedef std::runtime_error _Mybase; explicit fetch_error(const std::string& _Message, const std::string& _File, size_t _Line, const std::string& _Func) : _Mybase(_Message) { std::ostringstream oss; oss << "Fetch error at " << _Func << std::endl; oss << _File << "(" << _Line << "): " << _Message; msg_ = oss.str(); } explicit fetch_error(const char *_Message, const char *_File, size_t _Line, char *_Func) : _Mybase(_Message) { std::ostringstream oss; oss << "Fetch error at " << _Func << std::endl; oss << _File << "(" << _Line << "): " << _Message; msg_ = oss.str(); } ~fetch_error() throw() {} const char* what() const throw() { return msg_.c_str(); } private: std::string msg_; }; #define FETCH_ERROR(msg) throw fetch_error(msg, __FILE__, __LINE__, __FUNCTION__) inline char PathSeparator() { #if defined(_WIN32) || defined(_WIN64) return '\\'; #else return '/'; #endif } //! An implementation of image fetcher. class image_fetcher { public: //! Open file or directory void open(const std::string& path) { #if defined(USE_BOOST) && defined(USE_OPENCV) boost::filesystem::path p(path); if (boost::filesystem::is_directory(p)) { dir_ = path; #ifdef USE_CXX11 std::for_each(boost::filesystem::directory_iterator(p), boost::filesystem::directory_iterator(), [&](boost::filesystem::directory_entry& entry) { #else boost::filesystem::directory_iterator end; for (boost::filesystem::directory_iterator iter(p) ; iter != end ; ++iter) { boost::filesystem::directory_entry& entry = *iter; #endif if (boost::filesystem::is_regular_file(entry.status()) && supported_file_formats.find(entry.path().extension().string()) != std::string::npos) // match the extension files_.push_back(entry.path().string()); #ifdef USE_CXX11 }); #else } #endif if (files_.empty()) FETCH_ERROR("Nothing to fetch"); pos_ = 0; } else if (boost::filesystem::is_regular_file(p)) { cap_.open(path); dir_ = path.substr(0, path.find_last_of(PathSeparator())); // video directory } else FETCH_ERROR("Given path does not exist!"); #elif defined(USE_OPENCV) cap_.open(path); if (cap_.isOpened()) dir_ = path.substr(0, path.find_last_of(PathSeparator())); // video directory else FETCH_ERROR("Given path does not exist!"); #else return open_pack(path); #endif } void open_pack(const std::string& path) { fin_.open(path.c_str(), std::ios::binary); // std::string param is supported C++11 if (fin_.is_open()) { // try to read pack file cout << "Read pack file" << endl; fin_.read((char *)&width_, sizeof(unsigned int)); fin_.read((char *)&height_, sizeof(unsigned int)); fin_.read((char *)&numframes_, sizeof(unsigned int)); dir_ = path.substr(0, path.find_last_of(PathSeparator())); pos_ = 0; } else FETCH_ERROR("Given path does not exist!"); } //! Connect to device void open(int device_id) { #ifdef USE_OPENCV if (!cap_.open(device_id)) FETCH_ERROR("Cannot connect camera"); #ifdef USE_BOOST boost::filesystem::path full_path( boost::filesystem::current_path() ); dir_ = full_path.string(); #else #endif #endif } //! Grabs the next frame from video file or directory. bool grab() { #ifdef USE_OPENCV if (cap_.isOpened()) return cap_.grab(); #endif return files_.empty() ? pos_ < numframes_ : (pos_ < files_.size()); } //! Decodes and returns the grabbed video frame or image. template <typename pixel_type> void retrieve(Image<pixel_type>& image) { #ifdef USE_OPENCV cv::Mat frame; if (cap_.isOpened()) { cap_.retrieve(frame); image = bgr2gray<pixel_type>(frame); } else if(!files_.empty()) { //std::cout << files[pos].c_str() << " "; /*std::endl;*/ frame = cv::imread(files_[pos_++]); #ifdef USE_16BIT_IMAGE // simulate different image format std::cout << "Simulate 16 bit image" << std::endl; frame.clone().convertTo(frame, CV_16U); #endif image = bgr2gray<pixel_type>(frame); } else if (fin_.is_open()) { #else if (fin_.is_open()) { #endif Image<pixel_type> temp(height_, width_); fin_.read((char *)temp.memptr(), sizeof(pixel_type) * width_ * height_); image = Image<pixel_type>(temp.t()); ++pos_; } } //! Get current directory inline std::string current_directory() const { return dir_; } private: #ifdef USE_OPENCV cv::VideoCapture cap_; ///< video capture #endif std::ifstream fin_; ///< unsigned int width_, height_; unsigned int numframes_; std::string dir_; ///< the current directory std::vector<std::string> files_; ///< the image file names size_t pos_; ///< the current frame number }; } <commit_msg>Support 14bit 320x240 images.<commit_after>/** * @file image_fetcher.hpp * @brief An image fetcher class implementation * @author [email protected] * @date 2013-07-01 * @copyright 2007-2014 [email protected] * @version 1.0 * * @section LICENSE * * Copyright (c) 2007-2014, Seonho Oh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <ORGANIZATION> nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #ifdef USE_OPENCV #include <opencv2/opencv.hpp> #endif #ifdef USE_BOOST #include <boost/filesystem.hpp> // for filesystem access using namespace boost::filesystem; #endif //! An auxiliary interface functions for armadillo library. namespace auxiliary { /// supporting file formats static std::string supported_file_formats("*.bmp;*.dib;*.jpeg;*.jpg;*.jpe;*.jp2;*.png;*.pbm;*.pgm;*.ppm;*.sr;*.ras;*.tiff;*.tif;"); //! defines fetch error exception class fetch_error : public std::runtime_error { public: typedef std::runtime_error _Mybase; explicit fetch_error(const std::string& _Message, const std::string& _File, size_t _Line, const std::string& _Func) : _Mybase(_Message) { std::ostringstream oss; oss << "Fetch error at " << _Func << std::endl; oss << _File << "(" << _Line << "): " << _Message; msg_ = oss.str(); } explicit fetch_error(const char *_Message, const char *_File, size_t _Line, char *_Func) : _Mybase(_Message) { std::ostringstream oss; oss << "Fetch error at " << _Func << std::endl; oss << _File << "(" << _Line << "): " << _Message; msg_ = oss.str(); } ~fetch_error() throw() {} const char* what() const throw() { return msg_.c_str(); } private: std::string msg_; }; #define FETCH_ERROR(msg) throw fetch_error(msg, __FILE__, __LINE__, __FUNCTION__) inline char PathSeparator() { #if defined(_WIN32) || defined(_WIN64) return '\\'; #else return '/'; #endif } //! An implementation of image fetcher. class image_fetcher { public: //! Open file or directory void open(const std::string& path) { #if defined(USE_BOOST) && defined(USE_OPENCV) boost::filesystem::path p(path); if (boost::filesystem::is_directory(p)) { dir_ = boost::filesystem::absolute(p).string(); #ifdef USE_CXX11 std::for_each(boost::filesystem::directory_iterator(p), boost::filesystem::directory_iterator(), [&](boost::filesystem::directory_entry& entry) { #else boost::filesystem::directory_iterator end; for (boost::filesystem::directory_iterator iter(p) ; iter != end ; ++iter) { boost::filesystem::directory_entry& entry = *iter; #endif if (boost::filesystem::is_regular_file(entry.status()))// && //supported_file_formats.find(entry.path().extension().string()) != std::string::npos) // match the extension files_.push_back(entry.path().string()); #ifdef USE_CXX11 }); #else } #endif if (files_.empty()) FETCH_ERROR("Nothing to fetch"); pos_ = 0; } else if (boost::filesystem::is_regular_file(p)) { cap_.open(path); dir_ = path.substr(0, path.find_last_of(PathSeparator())); // video directory } else FETCH_ERROR("Given path does not exist!"); #elif defined(USE_OPENCV) cap_.open(path); if (cap_.isOpened()) dir_ = path.substr(0, path.find_last_of(PathSeparator())); // video directory else FETCH_ERROR("Given path does not exist!"); #else return open_pack(path); #endif } void open_pack(const std::string& path) { fin_.open(path.c_str(), std::ios::binary); // std::string param is supported C++11 if (fin_.is_open()) { // try to read pack file cout << "Read pack file" << endl; fin_.read((char *)&width_, sizeof(unsigned int)); fin_.read((char *)&height_, sizeof(unsigned int)); fin_.read((char *)&numframes_, sizeof(unsigned int)); dir_ = path.substr(0, path.find_last_of(PathSeparator())); pos_ = 0; } else FETCH_ERROR("Given path does not exist!"); } //! Connect to device void open(int device_id) { #ifdef USE_OPENCV if (!cap_.open(device_id)) FETCH_ERROR("Cannot connect camera"); #ifdef USE_BOOST boost::filesystem::path full_path( boost::filesystem::current_path() ); dir_ = full_path.string(); #else #endif #endif } //! Grabs the next frame from video file or directory. bool grab() { #ifdef USE_OPENCV if (cap_.isOpened()) return cap_.grab(); #endif return files_.empty() ? pos_ < numframes_ : (pos_ < files_.size()); } //! Decodes and returns the grabbed video frame or image. template <typename pixel_type> void retrieve(Image<pixel_type>& image) { #ifdef USE_OPENCV cv::Mat frame; if (cap_.isOpened()) { cap_.retrieve(frame); image = bgr2gray<pixel_type>(frame); } else if(!files_.empty()) { //std::cout << files[pos].c_str() << " "; /*std::endl;*/ #ifdef USE_16BIT_IMAGE // simulate different image format //std::cout << "Simulate 16 bit image" << std::endl; //frame.clone().convertTo(frame, CV_16U); //frame = cv::Mat(320, 240, cv::DataType<pixel_type>::type); //pixel_type* ptr = frame.ptr<pixel_type>(); arma::Mat<pixel_type> gray(320, 240); pixel_type* ptr = gray.memptr(); FILE* f = fopen(files_[pos_++].c_str(), "r"); for (int r = 0 ; r < 240 ; r++) { for (int c = 0 ; c < 320 ; c++) fscanf(f, "%uh ", ptr++); } fclose(f); image = Image<pixel_type>(gray.t()); #else frame = cv::imread(files_[pos_++]); image = bgr2gray<pixel_type>(frame); #endif } else if (fin_.is_open()) { #else if (fin_.is_open()) { #endif Image<pixel_type> temp(height_, width_); fin_.read((char *)temp.memptr(), sizeof(pixel_type) * width_ * height_); image = Image<pixel_type>(temp.t()); ++pos_; } } //! Get current directory inline std::string current_directory() const { return dir_; } private: #ifdef USE_OPENCV cv::VideoCapture cap_; ///< video capture #endif std::ifstream fin_; ///< unsigned int width_, height_; unsigned int numframes_; std::string dir_; ///< the current directory std::vector<std::string> files_; ///< the image file names size_t pos_; ///< the current frame number }; } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bitvector.h" #include "allocatedbitvector.h" #include "growablebitvector.h" #include "partialbitvector.h" #include <vespa/vespalib/hwaccelrated/iaccelrated.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/fastos/file.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.common.bitvector"); using vespalib::make_string; using vespalib::IllegalArgumentException; using vespalib::hwaccelrated::IAccelrated; using vespalib::Optimized; using vespalib::alloc::Alloc; namespace { void verifyInclusiveStart(const search::BitVector & a, const search::BitVector & b) __attribute__((noinline)); void verifyInclusiveStart(const search::BitVector & a, const search::BitVector & b) { if (a.getStartIndex() < b.getStartIndex()) { throw IllegalArgumentException(make_string("[%d, %d] starts before which is not allowed currently [%d, %d]", a.getStartIndex(), a.size(), b.getStartIndex(), b.size()), VESPA_STRLOC); } } } ///////////////////////////////// namespace search { using vespalib::nbostream; using vespalib::GenerationHeldBase; using vespalib::GenerationHeldAlloc; using vespalib::GenerationHolder; Alloc BitVector::allocatePaddedAndAligned(Index start, Index end, Index capacity) { assert(capacity >= end); uint32_t words = numActiveWords(start, capacity); words += (-words & 15); // Pad to 64 byte alignment const size_t sz(words * sizeof(Word)); Alloc alloc = Alloc::alloc(sz); assert(alloc.size()/sizeof(Word) >= words); // Clear padding size_t usedBytes = numBytes(end - start); memset(static_cast<char *>(alloc.get()) + usedBytes, 0, alloc.size() - usedBytes); return alloc; } BitVector::BitVector(void * buf, Index start, Index end) : _words(static_cast<Word *>(buf) - wordNum(start)), _startOffset(start), _sz(end), _numTrueBits(invalidCount()) { assert((reinterpret_cast<size_t>(_words) & (sizeof(Word) - 1ul)) == 0); } void BitVector::init(void * buf, Index start, Index end) { _words = static_cast<Word *>(buf) - wordNum(start); _startOffset = start; _sz = end; _numTrueBits = invalidCount(); } void BitVector::clear() { memset(getActiveStart(), '\0', getActiveBytes()); setBit(size()); // Guard bit setTrueBits(0); } void BitVector::clearInterval(Index start, Index end) { clearIntervalNoInvalidation(Range(start, end)); invalidateCachedCount(); } void BitVector::clearIntervalNoInvalidation(Range range_in) { Range range = sanitize(range_in); if ( ! range.validNonZero()) return; Index last = range.end() - 1; Index startw = wordNum(range.start()); Index endw = wordNum(last); if (endw > startw) { _words[startw++] &= startBits(range.start()); memset(_words+startw, 0, sizeof(*_words)*(endw-startw)); _words[endw] &= endBits(last); } else { _words[startw] &= (startBits(range.start()) | endBits(last)); } } void BitVector::setInterval(Index start_in, Index end_in) { Range range = sanitize(Range(start_in, end_in)); if ( ! range.validNonZero()) return; Index last = range.end() - 1; Index startw = wordNum(range.start()); Index endw = wordNum(last); if (endw > startw) { _words[startw++] |= checkTab(range.start()); memset(_words + startw, 0xff, sizeof(*_words)*(endw-startw)); _words[endw] |= ~endBits(last); } else { _words[startw] |= ~(startBits(range.start()) | endBits(last)); } invalidateCachedCount(); } BitVector::Index BitVector::count() const { return countInterval(Range(getStartIndex(), size())); } BitVector::Index BitVector::countInterval(Range range_in) const { Range range = sanitize(range_in); if ( ! range.validNonZero()) return 0; Index last = range.end() - 1; // Count bits in range [start..end> Index startw = wordNum(range.start()); Index endw = wordNum(last); Word *bitValues = _words; if (startw == endw) { return Optimized::popCount(bitValues[startw] & ~(startBits(range.start()) | endBits(last))); } Index res = 0; // Limit to full words if ((range.start() & (WordLen - 1)) != 0) { res += Optimized::popCount(bitValues[startw] & ~startBits(range.start())); ++startw; } // Align start to 16 bytes while (startw < endw && (startw & 3) != 0) { res += Optimized::popCount(bitValues[startw]); ++startw; } bool partialEnd = (last & (WordLen - 1)) != (WordLen - 1); if (!partialEnd) { ++endw; } if (startw < endw) { res += IAccelrated::getAccelrator().populationCount(bitValues + startw, endw - startw); } if (partialEnd) { res += Optimized::popCount(bitValues[endw] & ~endBits(last)); } return res; } void BitVector::orWith(const BitVector & right) { verifyInclusiveStart(*this, right); if (right.size() < size()) { if (right.size() > 0) { ssize_t commonBytes = numActiveBytes(getStartIndex(), right.size()) - sizeof(Word); if (commonBytes > 0) { IAccelrated::getAccelrator().orBit(getActiveStart(), right.getWordIndex(getStartIndex()), commonBytes); } Index last(right.size() - 1); getWordIndex(last)[0] |= (right.getWordIndex(last)[0] & ~endBits(last)); } } else { IAccelrated::getAccelrator().orBit(getActiveStart(), right.getWordIndex(getStartIndex()), getActiveBytes()); } repairEnds(); invalidateCachedCount(); } void BitVector::repairEnds() { if (size() != 0) { Index start(getStartIndex()); Index last(size() - 1); getWordIndex(start)[0] &= ~startBits(start); getWordIndex(last)[0] &= ~endBits(last); } setGuardBit(); } void BitVector::andWith(const BitVector & right) { verifyInclusiveStart(*this, right); uint32_t commonBytes = std::min(getActiveBytes(), numActiveBytes(getStartIndex(), right.size())); IAccelrated::getAccelrator().andBit(getActiveStart(), right.getWordIndex(getStartIndex()), commonBytes); if (right.size() < size()) { clearInterval(right.size(), size()); } repairEnds(); invalidateCachedCount(); } void BitVector::andNotWith(const BitVector& right) { verifyInclusiveStart(*this, right); if (right.size() < size()) { if (right.size() > 0) { ssize_t commonBytes = numActiveBytes(getStartIndex(), right.size()) - sizeof(Word); if (commonBytes > 0) { IAccelrated::getAccelrator().andNotBit(getActiveStart(), right.getWordIndex(getStartIndex()), commonBytes); } Index last(right.size() - 1); getWordIndex(last)[0] &= ~(right.getWordIndex(last)[0] & ~endBits(last)); } } else { IAccelrated::getAccelrator().andNotBit(getActiveStart(), right.getWordIndex(getStartIndex()), getActiveBytes()); } repairEnds(); invalidateCachedCount(); } void BitVector::notSelf() { IAccelrated::getAccelrator().notBit(getActiveStart(), getActiveBytes()); setGuardBit(); invalidateCachedCount(); } bool BitVector::operator==(const BitVector &rhs) const { if ((size() != rhs.size()) || (getStartIndex() != rhs.getStartIndex())) { return false; } Index bitVectorSize = numActiveWords(); const Word *words = getActiveStart(); const Word *oWords = rhs.getActiveStart(); for (Index i = 0; i < bitVectorSize; i++) { if (words[i] != oWords[i]) { return false; } } return true; } bool BitVector::hasTrueBitsInternal() const { Index bitVectorSizeL1(numActiveWords() - 1); const Word *words(getActiveStart()); for (Index i = 0; i < bitVectorSizeL1; i++) { if (words[i] != 0) { return true; } } // Ignore guard bit. if ((words[bitVectorSizeL1] & ~mask(size())) != 0) return true; return false; } ////////////////////////////////////////////////////////////////////// // Set new length. Destruction of content ////////////////////////////////////////////////////////////////////// void BitVector::resize(Index) { LOG_ABORT("should not be reached"); } GenerationHeldBase::UP BitVector::grow(Index, Index ) { LOG_ABORT("should not be reached"); } size_t BitVector::getFileBytes(Index bits) { Index bytes = numBytes(bits); bytes += (-bytes & (getAlignment() - 1)); return bytes; } class MMappedBitVector : public BitVector { public: MMappedBitVector(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount); private: void read(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount); }; BitVector::UP BitVector::create(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount) { UP bv; if (file.IsMemoryMapped()) { bv = std::make_unique<MMappedBitVector>(numberOfElements, file, offset, doccount); } else { size_t padbefore, padafter; size_t vectorsize = getFileBytes(numberOfElements); file.DirectIOPadding(offset, vectorsize, padbefore, padafter); assert((padbefore & (getAlignment() - 1)) == 0); AllocatedBitVector::Alloc alloc = Alloc::alloc(padbefore + vectorsize + padafter, 0x1000000, 0x1000); void * alignedBuffer = alloc.get(); file.ReadBuf(alignedBuffer, alloc.size(), offset - padbefore); bv = std::make_unique<AllocatedBitVector>(numberOfElements, std::move(alloc), padbefore); bv->setTrueBits(doccount); // Check guard bit for getNextTrueBit() assert(bv->testBit(bv->size())); } return bv; } BitVector::UP BitVector::create(Index start, Index end) { return (start == 0) ? create(end) : std::make_unique<PartialBitVector>(start, end); } BitVector::UP BitVector::create(const BitVector & org, Index start, Index end) { return ((start == 0) && (end == org.size()) && (org.getStartIndex() == 0)) ? create(org) : std::make_unique<PartialBitVector>(org, start, end); } BitVector::UP BitVector::create(Index numberOfElements) { return std::make_unique<AllocatedBitVector>(numberOfElements); } BitVector::UP BitVector::create(const BitVector & rhs) { return std::make_unique<AllocatedBitVector>(rhs); } BitVector::UP BitVector::create(Index numberOfElements, Index newCapacity, GenerationHolder &generationHolder) { return std::make_unique<GrowableBitVector>(numberOfElements, newCapacity, generationHolder); } MMappedBitVector::MMappedBitVector(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount) : BitVector() { read(numberOfElements, file, offset, doccount); } void MMappedBitVector::read(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount) { assert((offset & (getAlignment() - 1)) == 0); void *mapptr = file.MemoryMapPtr(offset); assert(mapptr != nullptr); if (mapptr != nullptr) { init(mapptr, 0, numberOfElements); } setTrueBits(doccount); } nbostream & operator<<(nbostream &out, const BitVector &bv) { uint64_t size = bv.size(); uint64_t cachedHits = bv.countTrueBits(); uint64_t fileBytes = bv.getFileBytes(); assert(size <= std::numeric_limits<BitVector::Index>::max()); assert(cachedHits <= size || ! bv.isValidCount(cachedHits)); assert(bv.testBit(size)); out << size << cachedHits << fileBytes; out.write(bv.getStart(), bv.getFileBytes()); return out; } nbostream & operator>>(nbostream &in, BitVector &bv) { uint64_t size; uint64_t cachedHits; uint64_t fileBytes; in >> size >> cachedHits >> fileBytes; assert(size <= std::numeric_limits<BitVector::Index>::max()); assert(cachedHits <= size || ! bv.isValidCount(cachedHits)); if (bv.size() != size) bv.resize(size); assert(bv.getFileBytes() == fileBytes); in.read(bv.getStart(), bv.getFileBytes()); assert(bv.testBit(size)); bv.setTrueBits(cachedHits); return in; } } // namespace search <commit_msg>Add braces<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bitvector.h" #include "allocatedbitvector.h" #include "growablebitvector.h" #include "partialbitvector.h" #include <vespa/vespalib/hwaccelrated/iaccelrated.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/fastos/file.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.common.bitvector"); using vespalib::make_string; using vespalib::IllegalArgumentException; using vespalib::hwaccelrated::IAccelrated; using vespalib::Optimized; using vespalib::alloc::Alloc; namespace { void verifyInclusiveStart(const search::BitVector & a, const search::BitVector & b) __attribute__((noinline)); void verifyInclusiveStart(const search::BitVector & a, const search::BitVector & b) { if (a.getStartIndex() < b.getStartIndex()) { throw IllegalArgumentException(make_string("[%d, %d] starts before which is not allowed currently [%d, %d]", a.getStartIndex(), a.size(), b.getStartIndex(), b.size()), VESPA_STRLOC); } } } ///////////////////////////////// namespace search { using vespalib::nbostream; using vespalib::GenerationHeldBase; using vespalib::GenerationHeldAlloc; using vespalib::GenerationHolder; Alloc BitVector::allocatePaddedAndAligned(Index start, Index end, Index capacity) { assert(capacity >= end); uint32_t words = numActiveWords(start, capacity); words += (-words & 15); // Pad to 64 byte alignment const size_t sz(words * sizeof(Word)); Alloc alloc = Alloc::alloc(sz); assert(alloc.size()/sizeof(Word) >= words); // Clear padding size_t usedBytes = numBytes(end - start); memset(static_cast<char *>(alloc.get()) + usedBytes, 0, alloc.size() - usedBytes); return alloc; } BitVector::BitVector(void * buf, Index start, Index end) : _words(static_cast<Word *>(buf) - wordNum(start)), _startOffset(start), _sz(end), _numTrueBits(invalidCount()) { assert((reinterpret_cast<size_t>(_words) & (sizeof(Word) - 1ul)) == 0); } void BitVector::init(void * buf, Index start, Index end) { _words = static_cast<Word *>(buf) - wordNum(start); _startOffset = start; _sz = end; _numTrueBits = invalidCount(); } void BitVector::clear() { memset(getActiveStart(), '\0', getActiveBytes()); setBit(size()); // Guard bit setTrueBits(0); } void BitVector::clearInterval(Index start, Index end) { clearIntervalNoInvalidation(Range(start, end)); invalidateCachedCount(); } void BitVector::clearIntervalNoInvalidation(Range range_in) { Range range = sanitize(range_in); if ( ! range.validNonZero()) { return; } Index last = range.end() - 1; Index startw = wordNum(range.start()); Index endw = wordNum(last); if (endw > startw) { _words[startw++] &= startBits(range.start()); memset(_words+startw, 0, sizeof(*_words)*(endw-startw)); _words[endw] &= endBits(last); } else { _words[startw] &= (startBits(range.start()) | endBits(last)); } } void BitVector::setInterval(Index start_in, Index end_in) { Range range = sanitize(Range(start_in, end_in)); if ( ! range.validNonZero()) { return; } Index last = range.end() - 1; Index startw = wordNum(range.start()); Index endw = wordNum(last); if (endw > startw) { _words[startw++] |= checkTab(range.start()); memset(_words + startw, 0xff, sizeof(*_words)*(endw-startw)); _words[endw] |= ~endBits(last); } else { _words[startw] |= ~(startBits(range.start()) | endBits(last)); } invalidateCachedCount(); } BitVector::Index BitVector::count() const { return countInterval(Range(getStartIndex(), size())); } BitVector::Index BitVector::countInterval(Range range_in) const { Range range = sanitize(range_in); if ( ! range.validNonZero()) { return 0; } Index last = range.end() - 1; // Count bits in range [start..end> Index startw = wordNum(range.start()); Index endw = wordNum(last); Word *bitValues = _words; if (startw == endw) { return Optimized::popCount(bitValues[startw] & ~(startBits(range.start()) | endBits(last))); } Index res = 0; // Limit to full words if ((range.start() & (WordLen - 1)) != 0) { res += Optimized::popCount(bitValues[startw] & ~startBits(range.start())); ++startw; } // Align start to 16 bytes while (startw < endw && (startw & 3) != 0) { res += Optimized::popCount(bitValues[startw]); ++startw; } bool partialEnd = (last & (WordLen - 1)) != (WordLen - 1); if (!partialEnd) { ++endw; } if (startw < endw) { res += IAccelrated::getAccelrator().populationCount(bitValues + startw, endw - startw); } if (partialEnd) { res += Optimized::popCount(bitValues[endw] & ~endBits(last)); } return res; } void BitVector::orWith(const BitVector & right) { verifyInclusiveStart(*this, right); if (right.size() < size()) { if (right.size() > 0) { ssize_t commonBytes = numActiveBytes(getStartIndex(), right.size()) - sizeof(Word); if (commonBytes > 0) { IAccelrated::getAccelrator().orBit(getActiveStart(), right.getWordIndex(getStartIndex()), commonBytes); } Index last(right.size() - 1); getWordIndex(last)[0] |= (right.getWordIndex(last)[0] & ~endBits(last)); } } else { IAccelrated::getAccelrator().orBit(getActiveStart(), right.getWordIndex(getStartIndex()), getActiveBytes()); } repairEnds(); invalidateCachedCount(); } void BitVector::repairEnds() { if (size() != 0) { Index start(getStartIndex()); Index last(size() - 1); getWordIndex(start)[0] &= ~startBits(start); getWordIndex(last)[0] &= ~endBits(last); } setGuardBit(); } void BitVector::andWith(const BitVector & right) { verifyInclusiveStart(*this, right); uint32_t commonBytes = std::min(getActiveBytes(), numActiveBytes(getStartIndex(), right.size())); IAccelrated::getAccelrator().andBit(getActiveStart(), right.getWordIndex(getStartIndex()), commonBytes); if (right.size() < size()) { clearInterval(right.size(), size()); } repairEnds(); invalidateCachedCount(); } void BitVector::andNotWith(const BitVector& right) { verifyInclusiveStart(*this, right); if (right.size() < size()) { if (right.size() > 0) { ssize_t commonBytes = numActiveBytes(getStartIndex(), right.size()) - sizeof(Word); if (commonBytes > 0) { IAccelrated::getAccelrator().andNotBit(getActiveStart(), right.getWordIndex(getStartIndex()), commonBytes); } Index last(right.size() - 1); getWordIndex(last)[0] &= ~(right.getWordIndex(last)[0] & ~endBits(last)); } } else { IAccelrated::getAccelrator().andNotBit(getActiveStart(), right.getWordIndex(getStartIndex()), getActiveBytes()); } repairEnds(); invalidateCachedCount(); } void BitVector::notSelf() { IAccelrated::getAccelrator().notBit(getActiveStart(), getActiveBytes()); setGuardBit(); invalidateCachedCount(); } bool BitVector::operator==(const BitVector &rhs) const { if ((size() != rhs.size()) || (getStartIndex() != rhs.getStartIndex())) { return false; } Index bitVectorSize = numActiveWords(); const Word *words = getActiveStart(); const Word *oWords = rhs.getActiveStart(); for (Index i = 0; i < bitVectorSize; i++) { if (words[i] != oWords[i]) { return false; } } return true; } bool BitVector::hasTrueBitsInternal() const { Index bitVectorSizeL1(numActiveWords() - 1); const Word *words(getActiveStart()); for (Index i = 0; i < bitVectorSizeL1; i++) { if (words[i] != 0) { return true; } } // Ignore guard bit. if ((words[bitVectorSizeL1] & ~mask(size())) != 0) return true; return false; } ////////////////////////////////////////////////////////////////////// // Set new length. Destruction of content ////////////////////////////////////////////////////////////////////// void BitVector::resize(Index) { LOG_ABORT("should not be reached"); } GenerationHeldBase::UP BitVector::grow(Index, Index ) { LOG_ABORT("should not be reached"); } size_t BitVector::getFileBytes(Index bits) { Index bytes = numBytes(bits); bytes += (-bytes & (getAlignment() - 1)); return bytes; } class MMappedBitVector : public BitVector { public: MMappedBitVector(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount); private: void read(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount); }; BitVector::UP BitVector::create(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount) { UP bv; if (file.IsMemoryMapped()) { bv = std::make_unique<MMappedBitVector>(numberOfElements, file, offset, doccount); } else { size_t padbefore, padafter; size_t vectorsize = getFileBytes(numberOfElements); file.DirectIOPadding(offset, vectorsize, padbefore, padafter); assert((padbefore & (getAlignment() - 1)) == 0); AllocatedBitVector::Alloc alloc = Alloc::alloc(padbefore + vectorsize + padafter, 0x1000000, 0x1000); void * alignedBuffer = alloc.get(); file.ReadBuf(alignedBuffer, alloc.size(), offset - padbefore); bv = std::make_unique<AllocatedBitVector>(numberOfElements, std::move(alloc), padbefore); bv->setTrueBits(doccount); // Check guard bit for getNextTrueBit() assert(bv->testBit(bv->size())); } return bv; } BitVector::UP BitVector::create(Index start, Index end) { return (start == 0) ? create(end) : std::make_unique<PartialBitVector>(start, end); } BitVector::UP BitVector::create(const BitVector & org, Index start, Index end) { return ((start == 0) && (end == org.size()) && (org.getStartIndex() == 0)) ? create(org) : std::make_unique<PartialBitVector>(org, start, end); } BitVector::UP BitVector::create(Index numberOfElements) { return std::make_unique<AllocatedBitVector>(numberOfElements); } BitVector::UP BitVector::create(const BitVector & rhs) { return std::make_unique<AllocatedBitVector>(rhs); } BitVector::UP BitVector::create(Index numberOfElements, Index newCapacity, GenerationHolder &generationHolder) { return std::make_unique<GrowableBitVector>(numberOfElements, newCapacity, generationHolder); } MMappedBitVector::MMappedBitVector(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount) : BitVector() { read(numberOfElements, file, offset, doccount); } void MMappedBitVector::read(Index numberOfElements, FastOS_FileInterface &file, int64_t offset, Index doccount) { assert((offset & (getAlignment() - 1)) == 0); void *mapptr = file.MemoryMapPtr(offset); assert(mapptr != nullptr); if (mapptr != nullptr) { init(mapptr, 0, numberOfElements); } setTrueBits(doccount); } nbostream & operator<<(nbostream &out, const BitVector &bv) { uint64_t size = bv.size(); uint64_t cachedHits = bv.countTrueBits(); uint64_t fileBytes = bv.getFileBytes(); assert(size <= std::numeric_limits<BitVector::Index>::max()); assert(cachedHits <= size || ! bv.isValidCount(cachedHits)); assert(bv.testBit(size)); out << size << cachedHits << fileBytes; out.write(bv.getStart(), bv.getFileBytes()); return out; } nbostream & operator>>(nbostream &in, BitVector &bv) { uint64_t size; uint64_t cachedHits; uint64_t fileBytes; in >> size >> cachedHits >> fileBytes; assert(size <= std::numeric_limits<BitVector::Index>::max()); assert(cachedHits <= size || ! bv.isValidCount(cachedHits)); if (bv.size() != size) bv.resize(size); assert(bv.getFileBytes() == fileBytes); in.read(bv.getStart(), bv.getFileBytes()); assert(bv.testBit(size)); bv.setTrueBits(cachedHits); return in; } } // namespace search <|endoftext|>
<commit_before>#include "Hieralign.h" Hieralign::Hieralign(const string &beamsize) { beam_width = stoi(beamsize); } Hieralign::~Hieralign() { } void Hieralign::setFilter(const double &filter) { sigma_filter = filter; } void Hieralign::setHyperParameters(const double &theta, const double &delta, const double &p0) { sigma_theta = theta; sigma_delta = delta; sigma_p0 = p0; cerr << "Parameters: \t[theta: " << sigma_theta << ", delta: " << sigma_delta << ", p0: " << sigma_p0 << "]" << endl; } void Hieralign::LoadTranslationTable(const TranslationTable &other) { ttable = other; } void Hieralign::Align(ParallelCorpus &parallelCorpus) { AlignmentList link_list(parallelCorpus.size()); int count = 0; #pragma omp parallel for schedule(dynamic) reduction(+ : count) for (size_t i = 0; i < parallelCorpus.size(); i++) { if (i % 10000 == 0 && i != 0) { cerr << '.'; } if (i % 100000 == 0 && i != 0) { cerr << " \t[" << i << "]\n" << flush; } Alignment links; SentencePair sentence_pair = parallelCorpus[i]; const unsigned m = static_cast<int>(sentence_pair.first->size()); const unsigned n = static_cast<int>(sentence_pair.second->size()); if (m == 1 || n == 1) { for (unsigned i = 0; i < m; i++) for (unsigned j = 0; j < n; j++) links.emplace_back(i, j); } else { Matrix softMatrix(m, n); BuildSoftAlignmentMatrix(sentence_pair, m, n, &softMatrix); //softMatrix.PrintMatrix(); Matrix accumMatrix(m + 1, n + 1); BuildAccumMatrix(softMatrix, &accumMatrix); vector<ParserAction> bestActions; Parse(accumMatrix, m, n, &bestActions); ActionToAlignment(bestActions, m, n, &links, softMatrix); } link_list[i] = links; count += 1; } cerr << "Total: \t[" << count << "]" << flush; cerr << "\n# outputing result ..." << endl; PrintAlignmentList(link_list); } void Hieralign::ActionToAlignment(const vector<ParserAction> &bestActions, const unsigned &m, const unsigned &n, Alignment *links, const Matrix &softMatrix) { vector<ParserBlock> stack; stack.emplace_back(0, 0, m, n); for (size_t k = 0; k < bestActions.size(); k++) { const ParserAction &action = bestActions[k]; const ParserBlock block = stack.back(); stack.pop_back(); if (action.option) { //inverted if (action.x - block.i1 >= 2 && block.j2 - action.y >= 2) stack.emplace_back(block.i1, action.y, action.x, block.j2); else if (action.x - block.i1 == 1 || block.j2 - action.y == 1) for (unsigned i = block.i1; i < action.x; i++) for (unsigned j = action.y; j < block.j2; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } if (block.i2 - action.x >= 2 && action.y - block.j1 >= 2) stack.emplace_back(action.x, block.j1, block.i2, action.y); else if (block.i2 - action.x == 1 || action.y - block.j1 == 1) for (unsigned i = action.x; i < block.i2; i++) for (unsigned j = block.j1; j < action.y; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } } else { if (action.x - block.i1 >= 2 && action.y - block.j1 >= 2) stack.emplace_back(block.i1, block.j1, action.x, action.y); else if (action.x - block.i1 == 1 || action.y - block.j1 == 1) for (unsigned i = block.i1; i < action.x; i++) for (unsigned j = block.j1; j < action.y; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } if (block.i2 - action.x >= 2 && block.j2 - action.y >= 2) stack.emplace_back(action.x, action.y, block.i2, block.j2); else if (block.i2 - action.x == 1 || block.j2 - action.y == 1) for (unsigned i = action.x; i < block.i2; i++) for (unsigned j = action.y; j < block.j2; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } } } } void Hieralign::PrintAlignmentList(const AlignmentList &linksList) { for (size_t k = 0; k < linksList.size(); k++) { const Alignment &links = linksList[k]; for (size_t i = 0; i < links.size(); i++) { if (i == links.size() - 1) cout << links[i].first << "-" << links[i].second << endl; else cout << links[i].first << "-" << links[i].second << " "; } } } void Hieralign::BuildSoftAlignmentMatrix(const SentencePair &sentence_pair, const unsigned &m, const unsigned &n, Matrix *softMatrix) { const Sentence *src = sentence_pair.first; const Sentence *trg = sentence_pair.second; #pragma omp parallel for schedule(dynamic) for (unsigned i = 0; i < m; i++) { for (unsigned j = 0; j < n; j++) { const unsigned sw = (*src)[i]; const unsigned tw = (*trg)[j]; const double theta = log(max(ttable.safe_Prob(sw, tw), sigma_p0)) / sigma_theta; double score; if (sigma_delta < 0.001) { score = (1.0 - sigma_p0) * exp(theta); } else { const double offset = abs(static_cast<double>(i) / m - static_cast<double>(j) / n); const double delta = log(max(1.0 - offset, sigma_p0)) / sigma_delta; score = (1.0 - sqrt(sigma_p0)) * exp(theta + delta); } (*softMatrix)(i, j) = score; } } } void Hieralign::BuildAccumMatrix(const Matrix &softMatrix, Matrix *accumMatrix) { #pragma omp parallel for schedule(dynamic) for (size_t i = 0; i < softMatrix.width(); i++) { for (size_t j = 0; j < softMatrix.height(); j++) { (*accumMatrix)(i + 1, j + 1) = (*accumMatrix)(i, j + 1) + (*accumMatrix)(i + 1, j) - (*accumMatrix)(i, j) + softMatrix(i, j); } } } void Hieralign::Parse(const Matrix &accumMatrix, const unsigned &m, const unsigned &n, vector<ParserAction> *bestActions) { //const int maxblocksize = 3; Agenda old_agenda; Agenda new_agenda; //top is the smallest // Add the initial parser state to the agenda. old_agenda.push(ParserState(m, n)); double current_score = DBL_MAX; for (unsigned transition = 0; transition < min(m, n); transition++) { if (old_agenda.empty()) continue; while (!old_agenda.empty()) { const ParserState &state = old_agenda.top(); if (state.terminal) { if (state.score < current_score) { current_score = state.score; *bestActions = state.actions; } old_agenda.pop(); continue; } const ParserBlock &block = state.stack.back(); BestParserActions bestParserActions; SearchBestPartition(accumMatrix, &bestParserActions, block.i1, block.j1, block.i2, block.j2); int top = 0; while (!bestParserActions.empty() && top++ < 3) { const ParserAction &action = bestParserActions.top(); ParserState new_state = ParserState(state); new_state.Advance(action); const double threshold = new_agenda.empty() ? DBL_MAX : new_agenda.top().score; if (new_agenda.size() <= static_cast<size_t>(beam_width)) { new_agenda.push(new_state); } else { if (new_state.score <= threshold) { new_agenda.pop(); new_agenda.push(new_state); } } bestParserActions.pop(); } old_agenda.pop(); } if (!new_agenda.empty()) { old_agenda.swap(new_agenda); } else { break; } } // Incremental top-down parsing with beam search. } void Hieralign::SearchBestPartition(const Matrix &accumMatrix, BestParserActions *bestParserActions, const unsigned &i1, const unsigned &j1, const unsigned &i2, const unsigned &j2) { for (unsigned i = i1 + 1; i < i2; i++) { for (unsigned j = j1 + 1; j < j2; j++) { double score, score_; // const int x = i-i1; // const int y = i2-i; // const int p = j-j1; // const int q = j2-j; //if(y-x < 3 ) //FmeasureXY(accumMatrix, i1, j1, i, j, i2, j2, &score, &score_); Ncut(accumMatrix, i1, j1, i, j, i2, j2, &score, &score_); //if (x <= 3 && abs((i2-i)-(j2-j))<=3) bestParserActions->emplace(i, j, false, score); //else if(|| (i1+5< i<i2-5 && j1+5< j<j2-5))) //if (abs((i-i1)-(j2-j))<=3 && abs((i2-i)-(j-j1))<=3 || (i1+5< i<i2-5 && j1+5< j<j2-5)) bestParserActions->emplace(i, j, true, score_); } } } void Hieralign::FmeasureXY(const Matrix &accumMatrix, const unsigned &i1, const unsigned &j1, const unsigned &i2, const unsigned &j2, const unsigned &i3, const unsigned &j3, double *score, double *score_) { const double Pi1j1 = accumMatrix(i1, j1); const double Pi1j2 = accumMatrix(i1, j2); const double Pi1j3 = accumMatrix(i1, j3); const double Pi2j1 = accumMatrix(i2, j1); const double Pi2j2 = accumMatrix(i2, j2); const double Pi2j3 = accumMatrix(i2, j3); const double Pi3j1 = accumMatrix(i3, j1); const double Pi3j2 = accumMatrix(i3, j2); const double Pi3j3 = accumMatrix(i3, j3); const double WAB = Pi2j2 + Pi1j1 - Pi2j1 - Pi1j2; const double W_A_B = Pi3j3 + Pi2j2 - Pi2j3 - Pi3j2; const double W_AB = Pi2j3 + Pi1j2 - Pi1j3 - Pi2j2; const double WA_B = Pi3j2 + Pi2j1 - Pi3j1 - Pi2j2; const double W_ABA_B = WA_B + W_AB; const double W_A_BAB = WAB + W_A_B; *score = 2 - (WAB / (W_ABA_B + WAB + WAB) + W_A_B / (W_ABA_B + W_A_B + W_A_B)); *score_ = 2 - (W_AB / (W_A_BAB + W_AB + W_AB) + WA_B / (W_A_BAB + WA_B + WA_B)); // *score = 2- WAB /(WAB + W_ABA_B) + W_A_B/(W_A_B + W_ABA_B); // *score_ = 2- W_AB/(W_AB + W_A_BAB) + WA_B/(WA_B + W_A_BAB); } void Hieralign::Ncut(const Matrix &accumMatrix, const unsigned &i1, const unsigned &j1, const unsigned &i2, const unsigned &j2, const unsigned &i3, const unsigned &j3, double *score, double *score_) { const double Pi1j1 = accumMatrix(i1, j1); const double Pi1j2 = accumMatrix(i1, j2); const double Pi1j3 = accumMatrix(i1, j3); const double Pi2j1 = accumMatrix(i2, j1); const double Pi2j2 = accumMatrix(i2, j2); const double Pi2j3 = accumMatrix(i2, j3); const double Pi3j1 = accumMatrix(i3, j1); const double Pi3j2 = accumMatrix(i3, j2); const double Pi3j3 = accumMatrix(i3, j3); const double WXY = Pi2j2 + Pi1j1 - Pi2j1 - Pi1j2; const double W_X_Y = Pi3j3 + Pi2j2 - Pi2j3 - Pi3j2; const double W_XY = Pi2j3 + Pi1j2 - Pi1j3 - Pi2j2; const double WX_Y = Pi3j2 + Pi2j1 - Pi3j1 - Pi2j2; //case 1: A (X, Y) B (_X, _Y) const double cutAB = W_XY + WX_Y; const double assoAV = W_XY + WX_Y + WXY + WXY; const double assoBV = W_XY + WX_Y + W_X_Y + W_X_Y; *score = cutAB / assoAV + cutAB / assoBV; //case 2: A (X, _Y) B (_X, Y) const double cutAB_ = WXY + W_X_Y; const double assoAV_ = WXY + W_X_Y + W_XY + W_XY; const double assoBV_ = WXY + W_X_Y + WX_Y + WX_Y; *score_ = cutAB_ / assoAV_ + cutAB_ / assoBV_; } <commit_msg>solve the bugs in Hieralign.cc<commit_after>#include "Hieralign.h" Hieralign::Hieralign(const string &beamsize) { beam_width = stoi(beamsize); } Hieralign::~Hieralign() { } void Hieralign::setFilter(const double &filter) { sigma_filter = filter; } void Hieralign::setHyperParameters(const double &theta, const double &delta, const double &p0) { sigma_theta = theta; sigma_delta = delta; sigma_p0 = p0; cerr << "Parameters: \t[theta: " << sigma_theta << ", delta: " << sigma_delta << ", p0: " << sigma_p0 << "]" << endl; } void Hieralign::LoadTranslationTable(const TranslationTable &other) { ttable = other; } void Hieralign::Align(ParallelCorpus &parallelCorpus) { AlignmentList link_list(parallelCorpus.size()); int count = 0; #pragma omp parallel for schedule(dynamic) reduction(+ : count) for (size_t i = 0; i < parallelCorpus.size(); i++) { if (i % 10000 == 0 && i != 0) { cerr << '.'; } if (i % 100000 == 0 && i != 0) { cerr << " \t[" << i << "]\n" << flush; } Alignment links; SentencePair sentence_pair = parallelCorpus[i]; const unsigned m = static_cast<int>(sentence_pair.first->size()); const unsigned n = static_cast<int>(sentence_pair.second->size()); if (m == 1 || n == 1) { for (unsigned i = 0; i < m; i++) for (unsigned j = 0; j < n; j++) links.emplace_back(i, j); } else { Matrix softMatrix(m, n); BuildSoftAlignmentMatrix(sentence_pair, m, n, &softMatrix); //softMatrix.PrintMatrix(); Matrix accumMatrix(m + 1, n + 1); BuildAccumMatrix(softMatrix, &accumMatrix); vector<ParserAction> bestActions; Parse(accumMatrix, m, n, &bestActions); ActionToAlignment(bestActions, m, n, &links, softMatrix); } link_list[i] = links; count += 1; } cerr << "Total: \t[" << count << "]" << flush; cerr << "\n# outputing result ..." << endl; PrintAlignmentList(link_list); } void Hieralign::ActionToAlignment(const vector<ParserAction> &bestActions, const unsigned &m, const unsigned &n, Alignment *links, const Matrix &softMatrix) { vector<ParserBlock> stack; stack.emplace_back(0, 0, m, n); for (size_t k = 0; k < bestActions.size(); k++) { const ParserAction &action = bestActions[k]; const ParserBlock block = stack.back(); stack.pop_back(); if (action.option) { //inverted if (action.x - block.i1 >= 2 && block.j2 - action.y >= 2) stack.emplace_back(block.i1, action.y, action.x, block.j2); else if (action.x - block.i1 == 1 || block.j2 - action.y == 1) for (unsigned i = block.i1; i < action.x; i++) for (unsigned j = action.y; j < block.j2; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } if (block.i2 - action.x >= 2 && action.y - block.j1 >= 2) stack.emplace_back(action.x, block.j1, block.i2, action.y); else if (block.i2 - action.x == 1 || action.y - block.j1 == 1) for (unsigned i = action.x; i < block.i2; i++) for (unsigned j = block.j1; j < action.y; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } } else { if (action.x - block.i1 >= 2 && action.y - block.j1 >= 2) stack.emplace_back(block.i1, block.j1, action.x, action.y); else if (action.x - block.i1 == 1 || action.y - block.j1 == 1) for (unsigned i = block.i1; i < action.x; i++) for (unsigned j = block.j1; j < action.y; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } if (block.i2 - action.x >= 2 && block.j2 - action.y >= 2) stack.emplace_back(action.x, action.y, block.i2, block.j2); else if (block.i2 - action.x == 1 || block.j2 - action.y == 1) for (unsigned i = action.x; i < block.i2; i++) for (unsigned j = action.y; j < block.j2; j++) { if (softMatrix(i, j) > sigma_filter) (*links).emplace_back(i, j); } } } } void Hieralign::PrintAlignmentList(const AlignmentList &linksList) { for (size_t k = 0; k < linksList.size(); k++) { const Alignment &links = linksList[k]; if (links.empty()) { cout << endl; } else { for (size_t i = 0; i < links.size(); i++) { if (i == links.size() - 1) cout << links[i].first << "-" << links[i].second << endl; else cout << links[i].first << "-" << links[i].second << " "; } } } } void Hieralign::BuildSoftAlignmentMatrix(const SentencePair &sentence_pair, const unsigned &m, const unsigned &n, Matrix *softMatrix) { const Sentence *src = sentence_pair.first; const Sentence *trg = sentence_pair.second; #pragma omp parallel for schedule(dynamic) for (unsigned i = 0; i < m; i++) { for (unsigned j = 0; j < n; j++) { const unsigned sw = (*src)[i]; const unsigned tw = (*trg)[j]; const double theta = log(max(ttable.safe_Prob(sw, tw), sigma_p0)) / sigma_theta; double score; if (sigma_delta < 0.001) { score = (1.0 - sigma_p0) * exp(theta); } else { const double offset = abs(static_cast<double>(i) / m - static_cast<double>(j) / n); const double delta = log(max(1.0 - offset, sigma_p0)) / sigma_delta; score = (1.0 - sqrt(sigma_p0)) * exp(theta + delta); } (*softMatrix)(i, j) = score; } } } void Hieralign::BuildAccumMatrix(const Matrix &softMatrix, Matrix *accumMatrix) { #pragma omp parallel for schedule(dynamic) for (size_t i = 0; i < softMatrix.width(); i++) { for (size_t j = 0; j < softMatrix.height(); j++) { (*accumMatrix)(i + 1, j + 1) = (*accumMatrix)(i, j + 1) + (*accumMatrix)(i + 1, j) - (*accumMatrix)(i, j) + softMatrix(i, j); } } } void Hieralign::Parse(const Matrix &accumMatrix, const unsigned &m, const unsigned &n, vector<ParserAction> *bestActions) { //const int maxblocksize = 3; Agenda old_agenda; Agenda new_agenda; //top is the smallest // Add the initial parser state to the agenda. old_agenda.push(ParserState(m, n)); double current_score = DBL_MAX; for (unsigned transition = 0; transition < min(m, n); transition++) { if (old_agenda.empty()) continue; while (!old_agenda.empty()) { const ParserState &state = old_agenda.top(); if (state.terminal) { if (state.score < current_score) { current_score = state.score; *bestActions = state.actions; } old_agenda.pop(); continue; } const ParserBlock &block = state.stack.back(); BestParserActions bestParserActions; SearchBestPartition(accumMatrix, &bestParserActions, block.i1, block.j1, block.i2, block.j2); int top = 0; while (!bestParserActions.empty() && top++ < 3) { const ParserAction &action = bestParserActions.top(); ParserState new_state = ParserState(state); new_state.Advance(action); const double threshold = new_agenda.empty() ? DBL_MAX : new_agenda.top().score; if (new_agenda.size() <= static_cast<size_t>(beam_width)) { new_agenda.push(new_state); } else { if (new_state.score <= threshold) { new_agenda.pop(); new_agenda.push(new_state); } } bestParserActions.pop(); } old_agenda.pop(); } if (!new_agenda.empty()) { old_agenda.swap(new_agenda); } else { break; } } // Incremental top-down parsing with beam search. } void Hieralign::SearchBestPartition(const Matrix &accumMatrix, BestParserActions *bestParserActions, const unsigned &i1, const unsigned &j1, const unsigned &i2, const unsigned &j2) { for (unsigned i = i1 + 1; i < i2; i++) { for (unsigned j = j1 + 1; j < j2; j++) { double score, score_; // const int x = i-i1; // const int y = i2-i; // const int p = j-j1; // const int q = j2-j; //if(y-x < 3 ) //FmeasureXY(accumMatrix, i1, j1, i, j, i2, j2, &score, &score_); Ncut(accumMatrix, i1, j1, i, j, i2, j2, &score, &score_); //if (x <= 3 && abs((i2-i)-(j2-j))<=3) bestParserActions->emplace(i, j, false, score); //else if(|| (i1+5< i<i2-5 && j1+5< j<j2-5))) //if (abs((i-i1)-(j2-j))<=3 && abs((i2-i)-(j-j1))<=3 || (i1+5< i<i2-5 && j1+5< j<j2-5)) bestParserActions->emplace(i, j, true, score_); } } } void Hieralign::FmeasureXY(const Matrix &accumMatrix, const unsigned &i1, const unsigned &j1, const unsigned &i2, const unsigned &j2, const unsigned &i3, const unsigned &j3, double *score, double *score_) { const double Pi1j1 = accumMatrix(i1, j1); const double Pi1j2 = accumMatrix(i1, j2); const double Pi1j3 = accumMatrix(i1, j3); const double Pi2j1 = accumMatrix(i2, j1); const double Pi2j2 = accumMatrix(i2, j2); const double Pi2j3 = accumMatrix(i2, j3); const double Pi3j1 = accumMatrix(i3, j1); const double Pi3j2 = accumMatrix(i3, j2); const double Pi3j3 = accumMatrix(i3, j3); const double WAB = Pi2j2 + Pi1j1 - Pi2j1 - Pi1j2; const double W_A_B = Pi3j3 + Pi2j2 - Pi2j3 - Pi3j2; const double W_AB = Pi2j3 + Pi1j2 - Pi1j3 - Pi2j2; const double WA_B = Pi3j2 + Pi2j1 - Pi3j1 - Pi2j2; const double W_ABA_B = WA_B + W_AB; const double W_A_BAB = WAB + W_A_B; *score = 2 - (WAB / (W_ABA_B + WAB + WAB) + W_A_B / (W_ABA_B + W_A_B + W_A_B)); *score_ = 2 - (W_AB / (W_A_BAB + W_AB + W_AB) + WA_B / (W_A_BAB + WA_B + WA_B)); // *score = 2- WAB /(WAB + W_ABA_B) + W_A_B/(W_A_B + W_ABA_B); // *score_ = 2- W_AB/(W_AB + W_A_BAB) + WA_B/(WA_B + W_A_BAB); } void Hieralign::Ncut(const Matrix &accumMatrix, const unsigned &i1, const unsigned &j1, const unsigned &i2, const unsigned &j2, const unsigned &i3, const unsigned &j3, double *score, double *score_) { const double Pi1j1 = accumMatrix(i1, j1); const double Pi1j2 = accumMatrix(i1, j2); const double Pi1j3 = accumMatrix(i1, j3); const double Pi2j1 = accumMatrix(i2, j1); const double Pi2j2 = accumMatrix(i2, j2); const double Pi2j3 = accumMatrix(i2, j3); const double Pi3j1 = accumMatrix(i3, j1); const double Pi3j2 = accumMatrix(i3, j2); const double Pi3j3 = accumMatrix(i3, j3); const double WXY = Pi2j2 + Pi1j1 - Pi2j1 - Pi1j2; const double W_X_Y = Pi3j3 + Pi2j2 - Pi2j3 - Pi3j2; const double W_XY = Pi2j3 + Pi1j2 - Pi1j3 - Pi2j2; const double WX_Y = Pi3j2 + Pi2j1 - Pi3j1 - Pi2j2; //case 1: A (X, Y) B (_X, _Y) const double cutAB = W_XY + WX_Y; const double assoAV = W_XY + WX_Y + WXY + WXY; const double assoBV = W_XY + WX_Y + W_X_Y + W_X_Y; *score = cutAB / assoAV + cutAB / assoBV; //case 2: A (X, _Y) B (_X, Y) const double cutAB_ = WXY + W_X_Y; const double assoAV_ = WXY + W_X_Y + W_XY + W_XY; const double assoBV_ = WXY + W_X_Y + WX_Y + WX_Y; *score_ = cutAB_ / assoAV_ + cutAB_ / assoBV_; } <|endoftext|>
<commit_before>#include "Histogram.h" #include "Matrix.h" void Histogram::Init(Local<Object> target) { Nan::Persistent<Object> inner; Local<Object> obj = Nan::New<Object>(); inner.Reset(obj); Nan::SetMethod(obj, "calcHist", CalcHist); Nan::SetMethod(obj, "emd", Emd); target->Set(Nan::New("histogram").ToLocalChecked(), obj); } NAN_METHOD(Histogram::CalcHist) { Nan::EscapableHandleScope scope; try { // Arg 0 is the image Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat inputImage = m0->mat; // Arg 1 is the channel Local<Array> nodeChannels = Local<Array>::Cast(info[1]->ToObject()); const unsigned int dims = nodeChannels->Length(); int channels[dims]; for (unsigned int i = 0; i < dims; i++) { channels[i] = nodeChannels->Get(i)->IntegerValue(); } // Arg 2 is histogram sizes in each dimension Local<Array> nodeHistSizes = Local<Array>::Cast(info[2]->ToObject()); int histSize[dims]; for (unsigned int i = 0; i < dims; i++) { histSize[i] = nodeHistSizes->Get(i)->IntegerValue(); } // Arg 3 is array of the histogram bin boundaries in each dimension Local<Array> nodeRanges = Local<Array>::Cast(info[3]->ToObject()); /// Set the ranges ( for B,G,R) ) float histRanges[dims][2]; const float* ranges[dims]; for (unsigned int i = 0; i < dims; i++) { Local<Array> nodeRange = Local<Array>::Cast(nodeRanges->Get(i)->ToObject()); float lower = nodeRange->Get(0)->NumberValue(); float higher = nodeRange->Get(1)->NumberValue(); histRanges[i][0] = lower; histRanges[i][1] = higher; ranges[i] = histRanges[i]; } // Arg 4 is uniform flag bool uniform = info[4]->BooleanValue(); // Make a mat to hold the result image cv::Mat outputHist; // Perform calcHist cv::calcHist(&inputImage, 1, channels, cv::Mat(), outputHist, dims, histSize, ranges, uniform); v8::Local<v8::Array> arr = Nan::New<Array>(histSize[0]); if(dims < 1 || dims > 3){ return Nan::ThrowTypeError("OPENCV nodejs binding error : only dimensions from 1 to 3 are allowed"); } for (unsigned int i=0; i < (unsigned int) histSize[0]; i++) { if(dims <= 1){ arr->Set(i, Nan::New<Number>(outputHist.at<float>(i))); } else { v8::Local<v8::Array> arr2 = Nan::New<Array>(dims); for (unsigned int j=0; j < (unsigned int) histSize[1]; j++) { if(dims <= 2){ arr2->Set(j, Nan::New<Number>(outputHist.at<float>(i,j))); } else { v8::Local<v8::Array> arr3 = Nan::New<Array>(dims); for (unsigned int k=0; k < (unsigned int) histSize[1]; k++) { arr3->Set(k, Nan::New<Number>(outputHist.at<float>(i,j,k))); } arr2->Set(j, arr3); } } arr->Set(i, arr2); } } info.GetReturnValue().Set(arr); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } std::vector<std::vector<float>> nodeArrayToVec(Local<Object> input){ std::vector<std::vector<float>> ret; Local<Array> nodeMatrix = Local<Array>::Cast(input); const unsigned int size = nodeMatrix->Length(); for (unsigned int i = 0; i < size; i++) { Local<Array> nodeRow = Local<Array>::Cast(nodeMatrix->Get(i)->ToObject()); std::vector<float> row; const unsigned int size2 = nodeRow->Length(); for (unsigned int j = 0; j < size2; j++) { row.push_back(nodeRow->Get(j)->NumberValue()); } ret.push_back(row); } return ret; } // cv::distanceTransform NAN_METHOD(Histogram::Emd) { Nan::EscapableHandleScope scope; try { // Arg 0 is the first signature //std::vector<std::vector<float>> sig1 = nodeArrayToVec(info[0]->ToObject()); Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat sig1 = m0->mat; // Arg 1 is the second signature //std::vector<std::vector<float>> sig2 = nodeArrayToVec(info[1]->ToObject()); Matrix* m1 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject()); cv::Mat sig2 = m1->mat; // Arg 2 is the distance type int distType = info[2]->IntegerValue(); float emd; // Arg 3 is the cost matrix if (info.Length() > 3) { Matrix* m3 = Nan::ObjectWrap::Unwrap<Matrix>(info[3]->ToObject()); cv::Mat costs = m3->mat; emd = cv::EMD(sig1, sig2, distType, costs); info.GetReturnValue().Set(emd); } else { emd = cv::EMD(sig1, sig2, distType); } //printf("similarity %5.5f %%\n, DistanceType is %i\n", (1-emd)*100, distType); info.GetReturnValue().Set(emd); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } <commit_msg>rm useless function nodeArrayToVec<commit_after>#include "Histogram.h" #include "Matrix.h" void Histogram::Init(Local<Object> target) { Nan::Persistent<Object> inner; Local<Object> obj = Nan::New<Object>(); inner.Reset(obj); Nan::SetMethod(obj, "calcHist", CalcHist); Nan::SetMethod(obj, "emd", Emd); target->Set(Nan::New("histogram").ToLocalChecked(), obj); } NAN_METHOD(Histogram::CalcHist) { Nan::EscapableHandleScope scope; try { // Arg 0 is the image Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat inputImage = m0->mat; // Arg 1 is the channel Local<Array> nodeChannels = Local<Array>::Cast(info[1]->ToObject()); const unsigned int dims = nodeChannels->Length(); int channels[dims]; for (unsigned int i = 0; i < dims; i++) { channels[i] = nodeChannels->Get(i)->IntegerValue(); } // Arg 2 is histogram sizes in each dimension Local<Array> nodeHistSizes = Local<Array>::Cast(info[2]->ToObject()); int histSize[dims]; for (unsigned int i = 0; i < dims; i++) { histSize[i] = nodeHistSizes->Get(i)->IntegerValue(); } // Arg 3 is array of the histogram bin boundaries in each dimension Local<Array> nodeRanges = Local<Array>::Cast(info[3]->ToObject()); /// Set the ranges ( for B,G,R) ) float histRanges[dims][2]; const float* ranges[dims]; for (unsigned int i = 0; i < dims; i++) { Local<Array> nodeRange = Local<Array>::Cast(nodeRanges->Get(i)->ToObject()); float lower = nodeRange->Get(0)->NumberValue(); float higher = nodeRange->Get(1)->NumberValue(); histRanges[i][0] = lower; histRanges[i][1] = higher; ranges[i] = histRanges[i]; } // Arg 4 is uniform flag bool uniform = info[4]->BooleanValue(); // Make a mat to hold the result image cv::Mat outputHist; // Perform calcHist cv::calcHist(&inputImage, 1, channels, cv::Mat(), outputHist, dims, histSize, ranges, uniform); v8::Local<v8::Array> arr = Nan::New<Array>(histSize[0]); if(dims < 1 || dims > 3){ return Nan::ThrowTypeError("OPENCV nodejs binding error : only dimensions from 1 to 3 are allowed"); } for (unsigned int i=0; i < (unsigned int) histSize[0]; i++) { if(dims <= 1){ arr->Set(i, Nan::New<Number>(outputHist.at<float>(i))); } else { v8::Local<v8::Array> arr2 = Nan::New<Array>(dims); for (unsigned int j=0; j < (unsigned int) histSize[1]; j++) { if(dims <= 2){ arr2->Set(j, Nan::New<Number>(outputHist.at<float>(i,j))); } else { v8::Local<v8::Array> arr3 = Nan::New<Array>(dims); for (unsigned int k=0; k < (unsigned int) histSize[1]; k++) { arr3->Set(k, Nan::New<Number>(outputHist.at<float>(i,j,k))); } arr2->Set(j, arr3); } } arr->Set(i, arr2); } } info.GetReturnValue().Set(arr); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } // cv::distanceTransform NAN_METHOD(Histogram::Emd) { Nan::EscapableHandleScope scope; try { // Arg 0 is the first signature //std::vector<std::vector<float>> sig1 = nodeArrayToVec(info[0]->ToObject()); Matrix* m0 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); cv::Mat sig1 = m0->mat; // Arg 1 is the second signature //std::vector<std::vector<float>> sig2 = nodeArrayToVec(info[1]->ToObject()); Matrix* m1 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject()); cv::Mat sig2 = m1->mat; // Arg 2 is the distance type int distType = info[2]->IntegerValue(); float emd; // Arg 3 is the cost matrix if (info.Length() > 3) { Matrix* m3 = Nan::ObjectWrap::Unwrap<Matrix>(info[3]->ToObject()); cv::Mat costs = m3->mat; emd = cv::EMD(sig1, sig2, distType, costs); info.GetReturnValue().Set(emd); } else { emd = cv::EMD(sig1, sig2, distType); } //printf("similarity %5.5f %%\n, DistanceType is %i\n", (1-emd)*100, distType); info.GetReturnValue().Set(emd); } catch (cv::Exception &e) { const char *err_msg = e.what(); Nan::ThrowError(err_msg); return; } } <|endoftext|>
<commit_before>/* * Copyright (c) ICG. All rights reserved. * * Institute for Computer Graphics and Vision * Graz University of Technology / Austria * * * This software is distributed WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the above copyright notices for more information. * * * Project : ImageUtilities * Module : IO Module * Class : Wrapper * Language : C * Description : Implementation of public interfaces to IO module * * Author : Manuel Werlberger * EMail : [email protected] * */ #include "iuio.h" #include "iuio/imageio.h" #include "iuio/imageiopgm.h" namespace iu { /* *************************************************************************** read 2d image * ***************************************************************************/ iu::ImageCpu_8u_C1* imread_8u_C1(const std::string& filename) { return iuprivate::imread_8u_C1(filename); } iu::ImageCpu_8u_C3* imread_8u_C3(const std::string& filename) { return iuprivate::imread_8u_C3(filename); } iu::ImageCpu_8u_C4* imread_8u_C4(const std::string& filename) { return iuprivate::imread_8u_C4(filename); } iu::ImageCpu_32f_C1* imread_32f_C1(const std::string& filename) { return iuprivate::imread_32f_C1(filename); } iu::ImageCpu_32f_C3* imread_32f_C3(const std::string& filename) { return iuprivate::imread_32f_C3(filename); } iu::ImageCpu_32f_C4* imread_32f_C4(const std::string& filename) { return iuprivate::imread_32f_C4(filename); } iu::ImageGpu_8u_C1* imread_cu8u_C1(const std::string& filename) { return iuprivate::imread_cu8u_C1(filename); } iu::ImageGpu_8u_C4* imread_cu8u_C4(const std::string& filename) { return iuprivate::imread_cu8u_C4(filename); } iu::ImageGpu_32f_C1* imread_cu32f_C1(const std::string& filename) { return iuprivate::imread_cu32f_C1(filename); } iu::ImageGpu_32f_C4* imread_cu32f_C4(const std::string& filename) { return iuprivate::imread_cu32f_C4(filename); } /* *************************************************************************** write 2d image * ***************************************************************************/ bool imsave(iu::ImageCpu_8u_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageCpu_8u_C3* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageCpu_8u_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageCpu_32f_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageCpu_32f_C3* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageCpu_32f_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageGpu_8u_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageGpu_8u_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageGpu_32f_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } bool imsave(iu::ImageGpu_32f_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename); } /* *************************************************************************** show 2d image * ***************************************************************************/ void imshow(iu::ImageCpu_8u_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_8u_C3* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_8u_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_32f_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_32f_C3* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_32f_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_8u_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_8u_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_32f_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_32f_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } } // namespace iu <commit_msg><commit_after>/* * Copyright (c) ICG. All rights reserved. * * Institute for Computer Graphics and Vision * Graz University of Technology / Austria * * * This software is distributed WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the above copyright notices for more information. * * * Project : ImageUtilities * Module : IO Module * Class : Wrapper * Language : C * Description : Implementation of public interfaces to IO module * * Author : Manuel Werlberger * EMail : [email protected] * */ #include "iuio.h" #include "iuio/imageio.h" #include "iuio/imageiopgm.h" namespace iu { /* *************************************************************************** read 2d image * ***************************************************************************/ iu::ImageCpu_8u_C1* imread_8u_C1(const std::string& filename) { return iuprivate::imread_8u_C1(filename); } iu::ImageCpu_8u_C3* imread_8u_C3(const std::string& filename) { return iuprivate::imread_8u_C3(filename); } iu::ImageCpu_8u_C4* imread_8u_C4(const std::string& filename) { return iuprivate::imread_8u_C4(filename); } iu::ImageCpu_32f_C1* imread_32f_C1(const std::string& filename) { return iuprivate::imread_32f_C1(filename); } iu::ImageCpu_32f_C3* imread_32f_C3(const std::string& filename) { return iuprivate::imread_32f_C3(filename); } iu::ImageCpu_32f_C4* imread_32f_C4(const std::string& filename) { return iuprivate::imread_32f_C4(filename); } iu::ImageGpu_8u_C1* imread_cu8u_C1(const std::string& filename) { return iuprivate::imread_cu8u_C1(filename); } iu::ImageGpu_8u_C4* imread_cu8u_C4(const std::string& filename) { return iuprivate::imread_cu8u_C4(filename); } iu::ImageGpu_32f_C1* imread_cu32f_C1(const std::string& filename) { return iuprivate::imread_cu32f_C1(filename); } iu::ImageGpu_32f_C4* imread_cu32f_C4(const std::string& filename) { return iuprivate::imread_cu32f_C4(filename); } /* *************************************************************************** write 2d image * ***************************************************************************/ bool imsave(iu::ImageCpu_8u_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageCpu_8u_C3* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageCpu_8u_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageCpu_32f_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageCpu_32f_C3* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageCpu_32f_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageGpu_8u_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageGpu_8u_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageGpu_32f_C1* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } bool imsave(iu::ImageGpu_32f_C4* image, const std::string& filename, const bool& normalize) { return iuprivate::imsave(image, filename, normalize); } /* *************************************************************************** show 2d image * ***************************************************************************/ void imshow(iu::ImageCpu_8u_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_8u_C3* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_8u_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_32f_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_32f_C3* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageCpu_32f_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_8u_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_8u_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_32f_C1* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } void imshow(iu::ImageGpu_32f_C4* image, const std::string& winname, const bool& normalize) { iuprivate::imshow(image, winname, normalize); } } // namespace iu <|endoftext|>
<commit_before>#include "NumpyStorage.h" NumpyStorage::NumpyStorage(CacheTable *cache, CacheTable *read_cache, std::map<std::string, std::string> &config) : ArrayDataStore(cache, read_cache, config) { } NumpyStorage::~NumpyStorage() { }; std::list<std::vector<uint32_t> > NumpyStorage::generate_coords(PyObject * coord) const { std::vector<uint32_t> crd_inner = {}; std::list<std::vector<uint32_t> > crd = {}; crd_inner.resize((PyTuple_Size(PyList_GetItem(coord, 0)))); if (PyList_Check(coord)) { PyObject *value = nullptr; for (Py_ssize_t i = 0; i < PyList_Size(coord); i++) { value = PyList_GetItem(coord, i); for (Py_ssize_t j = 0; j < PyTuple_Size(value); j++) { crd_inner[j] = (PyLong_AsLong(PyTuple_GetItem(value, j))); } crd.push_back(crd_inner); } } return crd; } void NumpyStorage::store_numpy_after_set(const uint64_t *storage_id, PyArrayObject *numpy, PyObject *coord) const { ArrayMetadata *np_metas = this->get_np_metadata(numpy); np_metas->partition_type = ZORDER_ALGORITHM; void *data = PyArray_DATA(numpy); std::list<std::vector<uint32_t> > crd = {}; if (coord != Py_None) crd = generate_coords(coord); this->store_numpy_to_cas(storage_id, np_metas, data, crd); this->update_metadata(storage_id, np_metas); delete (np_metas); } void NumpyStorage::store_numpy(const uint64_t *storage_id, PyArrayObject *numpy) const { ArrayMetadata *np_metas = this->get_np_metadata(numpy); np_metas->partition_type = ZORDER_ALGORITHM; void *data = PyArray_BYTES(numpy); this->store(storage_id, np_metas, data); this->update_metadata(storage_id, np_metas); delete (np_metas); } void *NumpyStorage::coord_list_to_numpy(const uint64_t *storage_id, PyObject *coord, PyArrayObject *save) { ArrayMetadata *np_metas = this->get_np_metadata(save); np_metas->partition_type = ZORDER_ALGORITHM; void *data = PyArray_DATA(save); std::list<std::vector<uint32_t> > crd = {}; if (coord != Py_None) crd = generate_coords(coord); this->read_n_coord(storage_id, np_metas, crd, data); this->update_metadata(storage_id, np_metas); delete (np_metas); } PyObject *NumpyStorage::reserve_numpy_space(const uint64_t *storage_id) { ArrayMetadata *np_metas = this->read_metadata(storage_id); npy_intp *dims = new npy_intp[np_metas->dims.size()]; for (uint32_t i = 0; i < np_metas->dims.size(); ++i) { dims[i] = np_metas->dims[i]; } PyObject *resulting_array; try { resulting_array = PyArray_ZEROS((int32_t) np_metas->dims.size(), dims, np_metas->inner_type, 0); PyArrayObject *converted_array; PyArray_OutputConverter(resulting_array, &converted_array); PyArray_ENABLEFLAGS(converted_array, NPY_ARRAY_OWNDATA); } catch (std::exception e) { if (PyErr_Occurred()) PyErr_Print(); PyErr_SetString(PyExc_RuntimeError, e.what()); return NULL; } delete (np_metas); return resulting_array; } PyObject *NumpyStorage::get_row_elements(const uint64_t *storage_id) { ArrayMetadata *np_metas = this->read_metadata(storage_id); uint32_t ndims = (uint32_t) np_metas->dims.size(); uint64_t block_size = BLOCK_SIZE - (BLOCK_SIZE % np_metas->elem_size); uint32_t row_elements = (uint32_t) std::floor(pow(block_size / np_metas->elem_size, (1.0 / ndims))); return Py_BuildValue("i",row_elements); } /*** * Reads a numpy ndarray by fetching the clusters indipendently * @param storage_id of the array to retrieve * @return Numpy ndarray as a Python object */ PyObject *NumpyStorage::read_numpy(const uint64_t *storage_id, PyArrayObject *save) { void *data = PyArray_DATA(save); ArrayMetadata *np_metas = this->get_np_metadata(save); np_metas->partition_type = ZORDER_ALGORITHM; this->read_n_coord(storage_id, np_metas, {}, data); this->update_metadata(storage_id, np_metas); delete (np_metas); } /*** * Extract the metadatas of the given numpy ndarray and return a new ArrayMetadata with its representation * @param numpy Ndarray to extract the metadata * @return ArrayMetadata defining the information to reconstruct a numpy ndarray */ ArrayMetadata *NumpyStorage::get_np_metadata(PyArrayObject *numpy) const { int64_t ndims = PyArray_NDIM(numpy); npy_intp *shape = PyArray_SHAPE(numpy); ArrayMetadata *shape_and_type = new ArrayMetadata(); shape_and_type->inner_type = PyArray_TYPE(numpy); //TODO implement as a union if (shape_and_type->inner_type == NPY_INT8) shape_and_type->elem_size = sizeof(int8_t); else if (shape_and_type->inner_type == NPY_UINT8) shape_and_type->elem_size = sizeof(uint8_t); else if (shape_and_type->inner_type == NPY_INT16) shape_and_type->elem_size = sizeof(int16_t); else if (shape_and_type->inner_type == NPY_UINT16) shape_and_type->elem_size = sizeof(uint16_t); else if (shape_and_type->inner_type == NPY_INT32) shape_and_type->elem_size = sizeof(int32_t); else if (shape_and_type->inner_type == NPY_UINT32) shape_and_type->elem_size = sizeof(uint32_t); else if (shape_and_type->inner_type == NPY_INT64) shape_and_type->elem_size = sizeof(int64_t); else if (shape_and_type->inner_type == NPY_LONGLONG) shape_and_type->elem_size = sizeof(int64_t); else if (shape_and_type->inner_type == NPY_UINT64) shape_and_type->elem_size = sizeof(uint64_t); else if (shape_and_type->inner_type == NPY_ULONGLONG) shape_and_type->elem_size = sizeof(uint64_t); else if (shape_and_type->inner_type == NPY_DOUBLE) shape_and_type->elem_size = sizeof(npy_double); else if (shape_and_type->inner_type == NPY_FLOAT16) shape_and_type->elem_size = sizeof(npy_float16); else if (shape_and_type->inner_type == NPY_FLOAT32) shape_and_type->elem_size = sizeof(npy_float32); else if (shape_and_type->inner_type == NPY_FLOAT64) shape_and_type->elem_size = sizeof(npy_float64); else if (shape_and_type->inner_type == NPY_FLOAT128) shape_and_type->elem_size = sizeof(npy_float128); else if (shape_and_type->inner_type == NPY_BOOL) shape_and_type->elem_size = sizeof(bool); else if (shape_and_type->inner_type == NPY_BYTE) shape_and_type->elem_size = sizeof(char); else if (shape_and_type->inner_type == NPY_LONG) shape_and_type->elem_size = sizeof(long); else if (shape_and_type->inner_type == NPY_LONGLONG) shape_and_type->elem_size = sizeof(long long); else if (shape_and_type->inner_type == NPY_SHORT) shape_and_type->elem_size = sizeof(short); else throw ModuleException("Numpy data type still not supported"); // Copy elements per dimension shape_and_type->dims = std::vector<uint32_t>((uint64_t) ndims);//PyArray_SHAPE() for (int32_t dim = 0; dim < ndims; ++dim) { shape_and_type->dims[dim] = (uint32_t) shape[dim]; } return shape_and_type; } <commit_msg>better an assignation to an specific pointer than general processing pointer<commit_after>#include "NumpyStorage.h" NumpyStorage::NumpyStorage(CacheTable *cache, CacheTable *read_cache, std::map<std::string, std::string> &config) : ArrayDataStore(cache, read_cache, config) { } NumpyStorage::~NumpyStorage() { }; std::list<std::vector<uint32_t> > NumpyStorage::generate_coords(PyObject * coord) const { std::vector<uint32_t> crd_inner = {}; std::list<std::vector<uint32_t> > crd = {}; crd_inner.resize((PyTuple_Size(PyList_GetItem(coord, 0)))); if (PyList_Check(coord)) { PyObject *value = nullptr; for (Py_ssize_t i = 0; i < PyList_Size(coord); i++) { value = PyList_GetItem(coord, i); for (Py_ssize_t j = 0; j < PyTuple_Size(value); j++) { crd_inner[j] = (PyLong_AsLong(PyTuple_GetItem(value, j))); } crd.push_back(crd_inner); } } return crd; } void NumpyStorage::store_numpy_after_set(const uint64_t *storage_id, PyArrayObject *numpy, PyObject *coord) const { ArrayMetadata *np_metas = this->get_np_metadata(numpy); np_metas->partition_type = ZORDER_ALGORITHM; void *data = PyArray_DATA(numpy); std::list<std::vector<uint32_t> > crd = {}; if (coord != Py_None) crd = generate_coords(coord); this->store_numpy_to_cas(storage_id, np_metas, data, crd); this->update_metadata(storage_id, np_metas); delete (np_metas); } void NumpyStorage::store_numpy(const uint64_t *storage_id, PyArrayObject *numpy) const { ArrayMetadata *np_metas = this->get_np_metadata(numpy); np_metas->partition_type = ZORDER_ALGORITHM; void *data = PyArray_DATA(numpy); this->store(storage_id, np_metas, data); this->update_metadata(storage_id, np_metas); delete (np_metas); } void *NumpyStorage::coord_list_to_numpy(const uint64_t *storage_id, PyObject *coord, PyArrayObject *save) { ArrayMetadata *np_metas = this->get_np_metadata(save); np_metas->partition_type = ZORDER_ALGORITHM; void *data = PyArray_DATA(save); std::list<std::vector<uint32_t> > crd = {}; if (coord != Py_None) crd = generate_coords(coord); this->read_n_coord(storage_id, np_metas, crd, data); this->update_metadata(storage_id, np_metas); delete (np_metas); } PyObject *NumpyStorage::reserve_numpy_space(const uint64_t *storage_id) { ArrayMetadata *np_metas = this->read_metadata(storage_id); npy_intp *dims = new npy_intp[np_metas->dims.size()]; for (uint32_t i = 0; i < np_metas->dims.size(); ++i) { dims[i] = np_metas->dims[i]; } PyObject *resulting_array; try { resulting_array = PyArray_ZEROS((int32_t) np_metas->dims.size(), dims, np_metas->inner_type, 0); PyArrayObject *converted_array; PyArray_OutputConverter(resulting_array, &converted_array); PyArray_ENABLEFLAGS(converted_array, NPY_ARRAY_OWNDATA); } catch (std::exception e) { if (PyErr_Occurred()) PyErr_Print(); PyErr_SetString(PyExc_RuntimeError, e.what()); return NULL; } delete (np_metas); return resulting_array; } PyObject *NumpyStorage::get_row_elements(const uint64_t *storage_id) { ArrayMetadata *np_metas = this->read_metadata(storage_id); uint32_t ndims = (uint32_t) np_metas->dims.size(); uint64_t block_size = BLOCK_SIZE - (BLOCK_SIZE % np_metas->elem_size); uint32_t row_elements = (uint32_t) std::floor(pow(block_size / np_metas->elem_size, (1.0 / ndims))); return Py_BuildValue("i",row_elements); } /*** * Reads a numpy ndarray by fetching the clusters indipendently * @param storage_id of the array to retrieve * @return Numpy ndarray as a Python object */ PyObject *NumpyStorage::read_numpy(const uint64_t *storage_id, PyArrayObject *save) { void *data = PyArray_DATA(save); ArrayMetadata *np_metas = this->get_np_metadata(save); np_metas->partition_type = ZORDER_ALGORITHM; this->read_n_coord(storage_id, np_metas, {}, data); this->update_metadata(storage_id, np_metas); delete (np_metas); } /*** * Extract the metadatas of the given numpy ndarray and return a new ArrayMetadata with its representation * @param numpy Ndarray to extract the metadata * @return ArrayMetadata defining the information to reconstruct a numpy ndarray */ ArrayMetadata *NumpyStorage::get_np_metadata(PyArrayObject *numpy) const { int64_t ndims = PyArray_NDIM(numpy); npy_intp *shape = PyArray_SHAPE(numpy); ArrayMetadata *shape_and_type = new ArrayMetadata(); shape_and_type->inner_type = PyArray_TYPE(numpy); //TODO implement as a union if (shape_and_type->inner_type == NPY_INT8) shape_and_type->elem_size = sizeof(int8_t); else if (shape_and_type->inner_type == NPY_UINT8) shape_and_type->elem_size = sizeof(uint8_t); else if (shape_and_type->inner_type == NPY_INT16) shape_and_type->elem_size = sizeof(int16_t); else if (shape_and_type->inner_type == NPY_UINT16) shape_and_type->elem_size = sizeof(uint16_t); else if (shape_and_type->inner_type == NPY_INT32) shape_and_type->elem_size = sizeof(int32_t); else if (shape_and_type->inner_type == NPY_UINT32) shape_and_type->elem_size = sizeof(uint32_t); else if (shape_and_type->inner_type == NPY_INT64) shape_and_type->elem_size = sizeof(int64_t); else if (shape_and_type->inner_type == NPY_LONGLONG) shape_and_type->elem_size = sizeof(int64_t); else if (shape_and_type->inner_type == NPY_UINT64) shape_and_type->elem_size = sizeof(uint64_t); else if (shape_and_type->inner_type == NPY_ULONGLONG) shape_and_type->elem_size = sizeof(uint64_t); else if (shape_and_type->inner_type == NPY_DOUBLE) shape_and_type->elem_size = sizeof(npy_double); else if (shape_and_type->inner_type == NPY_FLOAT16) shape_and_type->elem_size = sizeof(npy_float16); else if (shape_and_type->inner_type == NPY_FLOAT32) shape_and_type->elem_size = sizeof(npy_float32); else if (shape_and_type->inner_type == NPY_FLOAT64) shape_and_type->elem_size = sizeof(npy_float64); else if (shape_and_type->inner_type == NPY_FLOAT128) shape_and_type->elem_size = sizeof(npy_float128); else if (shape_and_type->inner_type == NPY_BOOL) shape_and_type->elem_size = sizeof(bool); else if (shape_and_type->inner_type == NPY_BYTE) shape_and_type->elem_size = sizeof(char); else if (shape_and_type->inner_type == NPY_LONG) shape_and_type->elem_size = sizeof(long); else if (shape_and_type->inner_type == NPY_LONGLONG) shape_and_type->elem_size = sizeof(long long); else if (shape_and_type->inner_type == NPY_SHORT) shape_and_type->elem_size = sizeof(short); else throw ModuleException("Numpy data type still not supported"); // Copy elements per dimension shape_and_type->dims = std::vector<uint32_t>((uint64_t) ndims);//PyArray_SHAPE() for (int32_t dim = 0; dim < ndims; ++dim) { shape_and_type->dims[dim] = (uint32_t) shape[dim]; } return shape_and_type; } <|endoftext|>
<commit_before>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "Sk64.h" #include "SkCornerPathEffect.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkKernel33MaskFilter.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkXfermode.h" #include "SkStream.h" #include "SkXMLParser.h" #include "SkColorPriv.h" #include "SkImageDecoder.h" #include "SkBlurMaskFilter.h" static void test_gradient2(SkCanvas* canvas) { /* ctx.fillStyle = '#f00'; ctx.fillRect(0, 0, 100, 50); var g = ctx.createRadialGradient(-80, 25, 70, 0, 25, 150); g.addColorStop(0, '#f00'); g.addColorStop(0.01, '#0f0'); g.addColorStop(0.99, '#0f0'); g.addColorStop(1, '#f00'); ctx.fillStyle = g; ctx.fillRect(0, 0, 100, 50); */ SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorGREEN, SK_ColorRED }; SkScalar pos[] = { 0, SkFloatToScalar(0.01f), SkFloatToScalar(0.99f), SK_Scalar1 }; SkPoint c0 = { -80, 25 }; SkScalar r0 = 70; SkPoint c1 = { 0, 25 }; SkScalar r1 = 150; SkShader* s = SkGradientShader::CreateTwoPointRadial(c0, r0, c1, r1, colors, pos, SK_ARRAY_COUNT(pos), SkShader::kClamp_TileMode); SkPaint paint; paint.setShader(s)->unref(); canvas->drawPaint(paint); paint.setShader(NULL); paint.setStyle(SkPaint::kStroke_Style); SkRect r = { 0, 0, 100, 50 }; canvas->drawRect(r, paint); } static void setNamedTypeface(SkPaint* paint, const char name[]) { SkTypeface* face = SkTypeface::CreateFromName(name, SkTypeface::kNormal); paint->setTypeface(face); SkSafeUnref(face); } static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF }; class XfermodesBlurView : public SampleView { SkBitmap fBG; SkBitmap fSrcB, fDstB; void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha, SkScalar x, SkScalar y) { SkPaint p; SkMaskFilter* mf = SkBlurMaskFilter::Create(5, SkBlurMaskFilter::kNormal_BlurStyle, 0); p.setMaskFilter(mf)->unref(); SkScalar ww = SkIntToScalar(W); SkScalar hh = SkIntToScalar(H); // draw a circle covering the upper // left three quarters of the canvas p.setColor(0xFFCC44FF); SkRect r; r.set(0, 0, ww*3/4, hh*3/4); r.offset(x, y); canvas->drawOval(r, p); p.setXfermode(mode); // draw a square overlapping the circle // in the lower right of the canvas p.setColor(0x00AA6633 | alpha << 24); r.set(ww/3, hh/3, ww*19/20, hh*19/20); r.offset(x, y); canvas->drawRect(r, p); } public: const static int W = 64; const static int H = 64; XfermodesBlurView() { const int W = 64; const int H = 64; fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4); fBG.setPixels(gBG); fBG.setIsOpaque(true); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "XfermodesBlur"); return true; } return this->INHERITED::onQuery(evt); } virtual void onDrawContent(SkCanvas* canvas) { if (false) { test_gradient2(canvas); return; } canvas->translate(SkIntToScalar(10), SkIntToScalar(20)); const struct { SkXfermode::Mode fMode; const char* fLabel; } gModes[] = { { SkXfermode::kClear_Mode, "Clear" }, { SkXfermode::kSrc_Mode, "Src" }, { SkXfermode::kDst_Mode, "Dst" }, { SkXfermode::kSrcOver_Mode, "SrcOver" }, { SkXfermode::kDstOver_Mode, "DstOver" }, { SkXfermode::kSrcIn_Mode, "SrcIn" }, { SkXfermode::kDstIn_Mode, "DstIn" }, { SkXfermode::kSrcOut_Mode, "SrcOut" }, { SkXfermode::kDstOut_Mode, "DstOut" }, { SkXfermode::kSrcATop_Mode, "SrcATop" }, { SkXfermode::kDstATop_Mode, "DstATop" }, { SkXfermode::kXor_Mode, "Xor" }, { SkXfermode::kPlus_Mode, "Plus" }, /*{ SkXfermode::kMultiply_Mode, "Multiply" }, { SkXfermode::kScreen_Mode, "Screen" }, { SkXfermode::kOverlay_Mode, "Overlay" }, { SkXfermode::kDarken_Mode, "Darken" }, { SkXfermode::kLighten_Mode, "Lighten" }, { SkXfermode::kColorDodge_Mode, "ColorDodge" }, { SkXfermode::kColorBurn_Mode, "ColorBurn" }, { SkXfermode::kHardLight_Mode, "HardLight" }, { SkXfermode::kSoftLight_Mode, "SoftLight" }, { SkXfermode::kDifference_Mode, "Difference" }, { SkXfermode::kExclusion_Mode, "Exclusion" },*/ }; const SkScalar w = SkIntToScalar(W); const SkScalar h = SkIntToScalar(H); SkShader* s = SkShader::CreateBitmapShader(fBG, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix m; m.setScale(SkIntToScalar(6), SkIntToScalar(6)); s->setLocalMatrix(m); SkPaint labelP; labelP.setAntiAlias(true); labelP.setLCDRenderText(true); labelP.setTextAlign(SkPaint::kCenter_Align); setNamedTypeface(&labelP, "Menlo Regular"); const int W = 5; SkScalar x0 = 0; for (int twice = 0; twice < 2; twice++) { SkScalar x = x0, y = 0; for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) { SkXfermode* mode = SkXfermode::Create(gModes[i].fMode); SkAutoUnref aur(mode); SkRect r; r.set(x, y, x+w, y+h); SkPaint p; p.setStyle(SkPaint::kFill_Style); p.setShader(s); canvas->drawRect(r, p); canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag); draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop); canvas->restore(); r.inset(-SK_ScalarHalf, -SK_ScalarHalf); p.setStyle(SkPaint::kStroke_Style); p.setShader(NULL); canvas->drawRect(r, p); canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel), x + w/2, y - labelP.getTextSize()/2, labelP); x += w + SkIntToScalar(10); if ((i % W) == W - 1) { x = x0; y += h + SkIntToScalar(30); } } x0 += SkIntToScalar(400); } s->unref(); } private: typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new XfermodesBlurView; } static SkViewRegister reg(MyFactory); <commit_msg>add option to test 1x1 bitmapshader<commit_after>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "Sk64.h" #include "SkCornerPathEffect.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkKernel33MaskFilter.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkXfermode.h" #include "SkStream.h" #include "SkXMLParser.h" #include "SkColorPriv.h" #include "SkImageDecoder.h" #include "SkBlurMaskFilter.h" static void test_gradient2(SkCanvas* canvas) { #if 1 SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, 1, 1); bm.allocPixels(); *bm.getAddr32(0, 0) = SkPackARGB32(0xFF, 0, 0xFF, 0); SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); #else /* ctx.fillStyle = '#f00'; ctx.fillRect(0, 0, 100, 50); var g = ctx.createRadialGradient(-80, 25, 70, 0, 25, 150); g.addColorStop(0, '#f00'); g.addColorStop(0.01, '#0f0'); g.addColorStop(0.99, '#0f0'); g.addColorStop(1, '#f00'); ctx.fillStyle = g; ctx.fillRect(0, 0, 100, 50); */ SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorGREEN, SK_ColorRED }; SkScalar pos[] = { 0, SkFloatToScalar(0.01f), SkFloatToScalar(0.99f), SK_Scalar1 }; SkPoint c0 = { -80, 25 }; SkScalar r0 = 70; SkPoint c1 = { 0, 25 }; SkScalar r1 = 150; SkShader* s = SkGradientShader::CreateTwoPointRadial(c0, r0, c1, r1, colors, pos, SK_ARRAY_COUNT(pos), SkShader::kClamp_TileMode); #endif SkPaint paint; paint.setShader(s)->unref(); canvas->drawPaint(paint); paint.setShader(NULL); paint.setStyle(SkPaint::kStroke_Style); SkRect r = { 0, 0, 100, 50 }; canvas->drawRect(r, paint); } static void setNamedTypeface(SkPaint* paint, const char name[]) { SkTypeface* face = SkTypeface::CreateFromName(name, SkTypeface::kNormal); paint->setTypeface(face); SkSafeUnref(face); } static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF }; class XfermodesBlurView : public SampleView { SkBitmap fBG; SkBitmap fSrcB, fDstB; void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha, SkScalar x, SkScalar y) { SkPaint p; SkMaskFilter* mf = SkBlurMaskFilter::Create(5, SkBlurMaskFilter::kNormal_BlurStyle, 0); p.setMaskFilter(mf)->unref(); SkScalar ww = SkIntToScalar(W); SkScalar hh = SkIntToScalar(H); // draw a circle covering the upper // left three quarters of the canvas p.setColor(0xFFCC44FF); SkRect r; r.set(0, 0, ww*3/4, hh*3/4); r.offset(x, y); canvas->drawOval(r, p); p.setXfermode(mode); // draw a square overlapping the circle // in the lower right of the canvas p.setColor(0x00AA6633 | alpha << 24); r.set(ww/3, hh/3, ww*19/20, hh*19/20); r.offset(x, y); canvas->drawRect(r, p); } public: const static int W = 64; const static int H = 64; XfermodesBlurView() { const int W = 64; const int H = 64; fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4); fBG.setPixels(gBG); fBG.setIsOpaque(true); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "XfermodesBlur"); return true; } return this->INHERITED::onQuery(evt); } virtual void onDrawContent(SkCanvas* canvas) { if (false) { test_gradient2(canvas); return; } canvas->translate(SkIntToScalar(10), SkIntToScalar(20)); const struct { SkXfermode::Mode fMode; const char* fLabel; } gModes[] = { { SkXfermode::kClear_Mode, "Clear" }, { SkXfermode::kSrc_Mode, "Src" }, { SkXfermode::kDst_Mode, "Dst" }, { SkXfermode::kSrcOver_Mode, "SrcOver" }, { SkXfermode::kDstOver_Mode, "DstOver" }, { SkXfermode::kSrcIn_Mode, "SrcIn" }, { SkXfermode::kDstIn_Mode, "DstIn" }, { SkXfermode::kSrcOut_Mode, "SrcOut" }, { SkXfermode::kDstOut_Mode, "DstOut" }, { SkXfermode::kSrcATop_Mode, "SrcATop" }, { SkXfermode::kDstATop_Mode, "DstATop" }, { SkXfermode::kXor_Mode, "Xor" }, { SkXfermode::kPlus_Mode, "Plus" }, /*{ SkXfermode::kMultiply_Mode, "Multiply" }, { SkXfermode::kScreen_Mode, "Screen" }, { SkXfermode::kOverlay_Mode, "Overlay" }, { SkXfermode::kDarken_Mode, "Darken" }, { SkXfermode::kLighten_Mode, "Lighten" }, { SkXfermode::kColorDodge_Mode, "ColorDodge" }, { SkXfermode::kColorBurn_Mode, "ColorBurn" }, { SkXfermode::kHardLight_Mode, "HardLight" }, { SkXfermode::kSoftLight_Mode, "SoftLight" }, { SkXfermode::kDifference_Mode, "Difference" }, { SkXfermode::kExclusion_Mode, "Exclusion" },*/ }; const SkScalar w = SkIntToScalar(W); const SkScalar h = SkIntToScalar(H); SkShader* s = SkShader::CreateBitmapShader(fBG, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); SkMatrix m; m.setScale(SkIntToScalar(6), SkIntToScalar(6)); s->setLocalMatrix(m); SkPaint labelP; labelP.setAntiAlias(true); labelP.setLCDRenderText(true); labelP.setTextAlign(SkPaint::kCenter_Align); setNamedTypeface(&labelP, "Menlo Regular"); const int W = 5; SkScalar x0 = 0; for (int twice = 0; twice < 2; twice++) { SkScalar x = x0, y = 0; for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) { SkXfermode* mode = SkXfermode::Create(gModes[i].fMode); SkAutoUnref aur(mode); SkRect r; r.set(x, y, x+w, y+h); SkPaint p; p.setStyle(SkPaint::kFill_Style); p.setShader(s); canvas->drawRect(r, p); canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag); draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop); canvas->restore(); r.inset(-SK_ScalarHalf, -SK_ScalarHalf); p.setStyle(SkPaint::kStroke_Style); p.setShader(NULL); canvas->drawRect(r, p); canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel), x + w/2, y - labelP.getTextSize()/2, labelP); x += w + SkIntToScalar(10); if ((i % W) == W - 1) { x = x0; y += h + SkIntToScalar(30); } } x0 += SkIntToScalar(400); } s->unref(); } private: typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new XfermodesBlurView; } static SkViewRegister reg(MyFactory); <|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 SHAPEFILE_HPP #define SHAPEFILE_HPP // stl #include <cstring> #include <fstream> #include <stdexcept> // mapnik #include <mapnik/global.hpp> #include <mapnik/utils.hpp> #include <mapnik/box2d.hpp> #ifdef SHAPE_MEMORY_MAPPED_FILE #include <boost/interprocess/mapped_region.hpp> #include <mapnik/mapped_memory_cache.hpp> #endif #include <mapnik/noncopyable.hpp> // boost #include <boost/cstdint.hpp> #include <boost/interprocess/streams/bufferstream.hpp> using mapnik::box2d; using mapnik::read_int32_ndr; using mapnik::read_int32_xdr; using mapnik::read_double_ndr; using mapnik::read_double_xdr; struct RecordTag { typedef char* data_type; static data_type alloc(unsigned size) { return static_cast<data_type>(::operator new(sizeof(char)*size)); } static void dealloc(data_type data) { ::operator delete(data); } }; struct MappedRecordTag { typedef const char* data_type; static data_type alloc(unsigned) { return 0; } static void dealloc(data_type ) {} }; template <typename Tag> struct shape_record { typename Tag::data_type data; size_t size; mutable size_t pos; explicit shape_record(size_t size_) : data(Tag::alloc(size_)), size(size_), pos(0) {} ~shape_record() { Tag::dealloc(data); } void set_data(typename Tag::data_type data_) { data = data_; } typename Tag::data_type get_data() { return data; } void skip(unsigned n) { pos += n; } int read_ndr_integer() { boost::int32_t val; read_int32_ndr(&data[pos], val); pos += 4; return val; } int read_xdr_integer() { boost::int32_t val; read_int32_xdr(&data[pos], val); pos += 4; return val; } double read_double() { double val; read_double_ndr(&data[pos], val); pos += 8; return val; } long remains() { return (size - pos); } }; using namespace boost::interprocess; class shape_file : mapnik::noncopyable { public: #ifdef SHAPE_MEMORY_MAPPED_FILE typedef ibufferstream file_source_type; typedef shape_record<MappedRecordTag> record_type; mapnik::mapped_region_ptr mapped_region_; #else typedef std::ifstream file_source_type; typedef shape_record<RecordTag> record_type; #endif file_source_type file_; shape_file() {} shape_file(std::string const& file_name) : #ifdef SHAPE_MEMORY_MAPPED_FILE file_() #elif defined (_WINDOWS) file_(mapnik::utf8_to_utf16(file_name), std::ios::in | std::ios::binary) #else file_(file_name.c_str(), std::ios::in | std::ios::binary) #endif { #ifdef SHAPE_MEMORY_MAPPED_FILE boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(file_name,true); if (memory) { mapped_region_ = *memory; file_.buffer(static_cast<char*>((*memory)->get_address()),(*memory)->get_size()); } else { throw std::runtime_error("could not create file mapping for "+file_name); } #endif } ~shape_file() {} inline file_source_type& file() { return file_; } inline bool is_open() { #ifdef SHAPE_MEMORY_MAPPED_FILE return (file_.buffer().second > 0); #else return file_.is_open(); #endif } inline void read_record(record_type& rec) { #ifdef SHAPE_MEMORY_MAPPED_FILE rec.set_data(file_.buffer().first + file_.tellg()); file_.seekg(rec.size, std::ios::cur); #else file_.read(rec.get_data(), rec.size); #endif } inline int read_xdr_integer() { char b[4]; file_.read(b, 4); boost::int32_t val; read_int32_xdr(b, val); return val; } inline int read_ndr_integer() { char b[4]; file_.read(b, 4); boost::int32_t val; read_int32_ndr(b, val); return val; } inline double read_double() { double val; #ifndef MAPNIK_BIG_ENDIAN file_.read(reinterpret_cast<char*>(&val), 8); #else char b[8]; file_.read(b, 8); read_double_ndr(b, val); #endif return val; } inline void read_envelope(box2d<double>& envelope) { #ifndef MAPNIK_BIG_ENDIAN file_.read(reinterpret_cast<char*>(&envelope), sizeof(envelope)); #else char data[4 * 8]; file_.read(data,4 * 8); double minx, miny, maxx, maxy; read_double_ndr(data + 0 * 8, minx); read_double_ndr(data + 1 * 8, miny); read_double_ndr(data + 2 * 8, maxx); read_double_ndr(data + 3 * 8, maxy); envelope.init(minx, miny, maxx, maxy); #endif } inline void skip(std::streampos bytes) { file_.seekg(bytes, std::ios::cur); } inline void rewind() { seek(100); } inline void seek(std::streampos pos) { file_.seekg(pos, std::ios::beg); } inline std::streampos pos() { return file_.tellg(); } inline bool is_eof() { return file_.eof(); } }; #endif // SHAPEFILE_HPP <commit_msg>shape.input: conditionally include boost interprocess<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 SHAPEFILE_HPP #define SHAPEFILE_HPP // stl #include <cstring> #include <fstream> #include <stdexcept> // mapnik #include <mapnik/global.hpp> #include <mapnik/utils.hpp> #include <mapnik/box2d.hpp> #ifdef SHAPE_MEMORY_MAPPED_FILE #include <boost/interprocess/mapped_region.hpp> #include <mapnik/mapped_memory_cache.hpp> #include <boost/interprocess/streams/bufferstream.hpp> #endif #include <mapnik/noncopyable.hpp> // boost #include <boost/cstdint.hpp> using mapnik::box2d; using mapnik::read_int32_ndr; using mapnik::read_int32_xdr; using mapnik::read_double_ndr; using mapnik::read_double_xdr; struct RecordTag { typedef char* data_type; static data_type alloc(unsigned size) { return static_cast<data_type>(::operator new(sizeof(char)*size)); } static void dealloc(data_type data) { ::operator delete(data); } }; struct MappedRecordTag { typedef const char* data_type; static data_type alloc(unsigned) { return 0; } static void dealloc(data_type ) {} }; template <typename Tag> struct shape_record { typename Tag::data_type data; size_t size; mutable size_t pos; explicit shape_record(size_t size_) : data(Tag::alloc(size_)), size(size_), pos(0) {} ~shape_record() { Tag::dealloc(data); } void set_data(typename Tag::data_type data_) { data = data_; } typename Tag::data_type get_data() { return data; } void skip(unsigned n) { pos += n; } int read_ndr_integer() { boost::int32_t val; read_int32_ndr(&data[pos], val); pos += 4; return val; } int read_xdr_integer() { boost::int32_t val; read_int32_xdr(&data[pos], val); pos += 4; return val; } double read_double() { double val; read_double_ndr(&data[pos], val); pos += 8; return val; } long remains() { return (size - pos); } }; class shape_file : mapnik::noncopyable { public: #ifdef SHAPE_MEMORY_MAPPED_FILE typedef boost::interprocess::ibufferstream file_source_type; typedef shape_record<MappedRecordTag> record_type; mapnik::mapped_region_ptr mapped_region_; #else typedef std::ifstream file_source_type; typedef shape_record<RecordTag> record_type; #endif file_source_type file_; shape_file() {} shape_file(std::string const& file_name) : #ifdef SHAPE_MEMORY_MAPPED_FILE file_() #elif defined (_WINDOWS) file_(mapnik::utf8_to_utf16(file_name), std::ios::in | std::ios::binary) #else file_(file_name.c_str(), std::ios::in | std::ios::binary) #endif { #ifdef SHAPE_MEMORY_MAPPED_FILE boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(file_name,true); if (memory) { mapped_region_ = *memory; file_.buffer(static_cast<char*>((*memory)->get_address()),(*memory)->get_size()); } else { throw std::runtime_error("could not create file mapping for "+file_name); } #endif } ~shape_file() {} inline file_source_type& file() { return file_; } inline bool is_open() { #ifdef SHAPE_MEMORY_MAPPED_FILE return (file_.buffer().second > 0); #else return file_.is_open(); #endif } inline void read_record(record_type& rec) { #ifdef SHAPE_MEMORY_MAPPED_FILE rec.set_data(file_.buffer().first + file_.tellg()); file_.seekg(rec.size, std::ios::cur); #else file_.read(rec.get_data(), rec.size); #endif } inline int read_xdr_integer() { char b[4]; file_.read(b, 4); boost::int32_t val; read_int32_xdr(b, val); return val; } inline int read_ndr_integer() { char b[4]; file_.read(b, 4); boost::int32_t val; read_int32_ndr(b, val); return val; } inline double read_double() { double val; #ifndef MAPNIK_BIG_ENDIAN file_.read(reinterpret_cast<char*>(&val), 8); #else char b[8]; file_.read(b, 8); read_double_ndr(b, val); #endif return val; } inline void read_envelope(box2d<double>& envelope) { #ifndef MAPNIK_BIG_ENDIAN file_.read(reinterpret_cast<char*>(&envelope), sizeof(envelope)); #else char data[4 * 8]; file_.read(data,4 * 8); double minx, miny, maxx, maxy; read_double_ndr(data + 0 * 8, minx); read_double_ndr(data + 1 * 8, miny); read_double_ndr(data + 2 * 8, maxx); read_double_ndr(data + 3 * 8, maxy); envelope.init(minx, miny, maxx, maxy); #endif } inline void skip(std::streampos bytes) { file_.seekg(bytes, std::ios::cur); } inline void rewind() { seek(100); } inline void seek(std::streampos pos) { file_.seekg(pos, std::ios::beg); } inline std::streampos pos() { return file_.tellg(); } inline bool is_eof() { return file_.eof(); } }; #endif // SHAPEFILE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Helper program to analyze the time that Chrome's renderers spend in system // calls. Start Chrome like this: // // SECCOMP_SANDBOX_DEBUGGING=1 chrome --enable-seccomp-sandbox 2>&1 | timestats // // The program prints CPU time (0-100%) spent within system calls. This gives // a general idea of where it is worthwhile to spend effort optimizing Chrome. // // Caveats: // - there currently is no way to estimate what the overhead is for running // inside of the sandbox vs. running without a sandbox. // - we currently use a very simple heuristic to decide whether a system call // is blocking or not. Blocking system calls should not be included in the // computations. But it is quite possible for the numbers to be somewhat // wrong, because the heuristic failed. // - in order to collect this data, we have to turn on sandbox debugging. // There is a measurable performance penalty to doing so. Production numbers // are strictly better than the numbers reported by this tool. #include <set> #include <vector> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <time.h> static const int kAvgWindowSizeMs = 500; static const int kPeakWindowSizeMs = 2*1000; // Class containing information on a single system call. Most notably, it // contains the time when the system call happened, and the time that it // took to complete. class Datum { friend class Data; public: Datum(const char* name, double ms) : name_(name), ms_(ms) { struct timeval tv; gettimeofday(&tv, NULL); timestamp_ = tv.tv_sec*1000.0 + tv.tv_usec/1000.0; } virtual ~Datum() { } double operator-(const Datum& b) { return timestamp_ - b.timestamp_; } protected: const char* name_; double ms_; double timestamp_; }; // Class containing data on the most recent system calls. It maintains // sliding averages for total CPU time used, and it also maintains a peak // CPU usage. The peak usage is usually updated slower than the average // usage, as that makes it easier to inspect visually. class Data { public: Data() { } virtual ~Data() { } void addData(const char* name, double ms) { average_.push_back(Datum(name, ms)); peak_.push_back(Datum(name, ms)); // Prune entries outside of the window std::vector<Datum>::iterator iter; for (iter = average_.begin(); *average_.rbegin() - *iter > kAvgWindowSizeMs; ++iter) { } average_.erase(average_.begin(), iter); for (iter = peak_.begin(); *peak_.rbegin() - *iter > kPeakWindowSizeMs; ++iter){ } peak_.erase(peak_.begin(), iter); // Add the total usage of all system calls inside of the window double total = 0; for (iter = average_.begin(); iter != average_.end(); ++iter) { total += iter->ms_; } // Compute the peak CPU usage during the last window double peak = 0; double max = 0; std::vector<Datum>::iterator tail = peak_.begin(); for (iter = tail; iter != peak_.end(); ++iter) { while (*iter - *tail > kAvgWindowSizeMs) { peak -= tail->ms_; ++tail; } peak += iter->ms_; if (peak > max) { max = peak; } } // Print the average CPU usage in the last window char buf[80]; total *= 100.0/kAvgWindowSizeMs; max *= 100.0/kAvgWindowSizeMs; sprintf(buf, "%6.2f%% (peak=%6.2f%%) ", total, max); // Animate the actual usage, displaying both average and peak values int len = strlen(buf); int space = sizeof(buf) - len - 1; int mark = (total * space + 50)/100; int bar = (max * space + 50)/100; for (int i = 0; i < mark; ++i) { buf[len++] = '*'; } if (mark == bar) { if (bar) { len--; } } else { for (int i = 0; i < bar - mark - 1; ++i) { buf[len++] = ' '; } } buf[len++] = '|'; while (len < static_cast<int>(sizeof(buf))) { buf[len++] = ' '; } strcpy(buf + len, "\r"); fwrite(buf, len + 1, 1, stdout); fflush(stdout); } private: std::vector<Datum> average_; std::vector<Datum> peak_; }; static Data data; int main(int argc, char *argv[]) { char buf[80]; bool expensive = false; while (fgets(buf, sizeof(buf), stdin)) { // Allow longer delays for expensive system calls if (strstr(buf, "This is an expensive system call")) { expensive = true; continue; } // Parse the string and extract the elapsed time const char elapsed[] = "Elapsed time: "; char* ms_string = strstr(buf, elapsed); char* endptr; double ms; char* colon = strchr(buf, ':'); // If this string doesn't match, then it must be some other type of // message. Just ignore it. // It is quite likely that we will regularly encounter debug messages // that either should be parsed by a completely different tool, or // messages that were intended for humans to read. if (!ms_string || ((ms = strtod(ms_string + sizeof(elapsed) - 1, &endptr)), endptr == ms_string) || !colon) { continue; } // Filter out system calls that were probably just blocking // TODO(markus): automatically compute the cut-off for blocking calls if (!expensive && ms > 0.05) { continue; } expensive = false; // Extract the name of the system call *colon = '\000'; // Add the data point and update the display data.addData(buf, ms); } puts(""); return 0; } <commit_msg>Add #include to fix compile errors on "Linux Perf (webkit.org)" bot.<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. // Helper program to analyze the time that Chrome's renderers spend in system // calls. Start Chrome like this: // // SECCOMP_SANDBOX_DEBUGGING=1 chrome --enable-seccomp-sandbox 2>&1 | timestats // // The program prints CPU time (0-100%) spent within system calls. This gives // a general idea of where it is worthwhile to spend effort optimizing Chrome. // // Caveats: // - there currently is no way to estimate what the overhead is for running // inside of the sandbox vs. running without a sandbox. // - we currently use a very simple heuristic to decide whether a system call // is blocking or not. Blocking system calls should not be included in the // computations. But it is quite possible for the numbers to be somewhat // wrong, because the heuristic failed. // - in order to collect this data, we have to turn on sandbox debugging. // There is a measurable performance penalty to doing so. Production numbers // are strictly better than the numbers reported by this tool. #include <set> #include <vector> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> static const int kAvgWindowSizeMs = 500; static const int kPeakWindowSizeMs = 2*1000; // Class containing information on a single system call. Most notably, it // contains the time when the system call happened, and the time that it // took to complete. class Datum { friend class Data; public: Datum(const char* name, double ms) : name_(name), ms_(ms) { struct timeval tv; gettimeofday(&tv, NULL); timestamp_ = tv.tv_sec*1000.0 + tv.tv_usec/1000.0; } virtual ~Datum() { } double operator-(const Datum& b) { return timestamp_ - b.timestamp_; } protected: const char* name_; double ms_; double timestamp_; }; // Class containing data on the most recent system calls. It maintains // sliding averages for total CPU time used, and it also maintains a peak // CPU usage. The peak usage is usually updated slower than the average // usage, as that makes it easier to inspect visually. class Data { public: Data() { } virtual ~Data() { } void addData(const char* name, double ms) { average_.push_back(Datum(name, ms)); peak_.push_back(Datum(name, ms)); // Prune entries outside of the window std::vector<Datum>::iterator iter; for (iter = average_.begin(); *average_.rbegin() - *iter > kAvgWindowSizeMs; ++iter) { } average_.erase(average_.begin(), iter); for (iter = peak_.begin(); *peak_.rbegin() - *iter > kPeakWindowSizeMs; ++iter){ } peak_.erase(peak_.begin(), iter); // Add the total usage of all system calls inside of the window double total = 0; for (iter = average_.begin(); iter != average_.end(); ++iter) { total += iter->ms_; } // Compute the peak CPU usage during the last window double peak = 0; double max = 0; std::vector<Datum>::iterator tail = peak_.begin(); for (iter = tail; iter != peak_.end(); ++iter) { while (*iter - *tail > kAvgWindowSizeMs) { peak -= tail->ms_; ++tail; } peak += iter->ms_; if (peak > max) { max = peak; } } // Print the average CPU usage in the last window char buf[80]; total *= 100.0/kAvgWindowSizeMs; max *= 100.0/kAvgWindowSizeMs; sprintf(buf, "%6.2f%% (peak=%6.2f%%) ", total, max); // Animate the actual usage, displaying both average and peak values int len = strlen(buf); int space = sizeof(buf) - len - 1; int mark = (total * space + 50)/100; int bar = (max * space + 50)/100; for (int i = 0; i < mark; ++i) { buf[len++] = '*'; } if (mark == bar) { if (bar) { len--; } } else { for (int i = 0; i < bar - mark - 1; ++i) { buf[len++] = ' '; } } buf[len++] = '|'; while (len < static_cast<int>(sizeof(buf))) { buf[len++] = ' '; } strcpy(buf + len, "\r"); fwrite(buf, len + 1, 1, stdout); fflush(stdout); } private: std::vector<Datum> average_; std::vector<Datum> peak_; }; static Data data; int main(int argc, char *argv[]) { char buf[80]; bool expensive = false; while (fgets(buf, sizeof(buf), stdin)) { // Allow longer delays for expensive system calls if (strstr(buf, "This is an expensive system call")) { expensive = true; continue; } // Parse the string and extract the elapsed time const char elapsed[] = "Elapsed time: "; char* ms_string = strstr(buf, elapsed); char* endptr; double ms; char* colon = strchr(buf, ':'); // If this string doesn't match, then it must be some other type of // message. Just ignore it. // It is quite likely that we will regularly encounter debug messages // that either should be parsed by a completely different tool, or // messages that were intended for humans to read. if (!ms_string || ((ms = strtod(ms_string + sizeof(elapsed) - 1, &endptr)), endptr == ms_string) || !colon) { continue; } // Filter out system calls that were probably just blocking // TODO(markus): automatically compute the cut-off for blocking calls if (!expensive && ms > 0.05) { continue; } expensive = false; // Extract the name of the system call *colon = '\000'; // Add the data point and update the display data.addData(buf, ms); } puts(""); return 0; } <|endoftext|>