text
stringlengths 5
1.04M
|
|---|
/*
* mainwindow.cpp
*
* Created on: May 03, 2012
* @author Ralph Schurade
*/
#include "mainwindow.h"
#include "views/datasetinfoview.h"
#include "widgets/glwidget.h"
#include "widgets/fndockwidget.h"
#include "widgets/datasetpropertywidget.h"
#include "widgets/roipropertywidget.h"
#include "widgets/globalpropertywidget.h"
#include "widgets/docknavglwidget.h"
#include "widgets/combinednavglwidget.h"
#include "widgets/singleshwidget.h"
#include "widgets/roiwidget.h"
#include "widgets/datasetlistwidget.h"
#include "widgets/navglwidget.h"
#include "widgets/combinednavglwidget.h"
#include "widgets/toolbar.h"
#include "widgets/statusbar.h"
#include "widgets/shadereditwidget.h"
#include "widgets/colormapeditwidget.h"
#include "gl/glfunctions.h"
#include "gl/colormapfunctions.h"
#include "../data/loader.h"
#include "../data/writer.h"
#include "../data/vptr.h"
#include "../data/enums.h"
#include "../data/models.h"
#include <QtGui>
#include <QWebView>
int MainWindow::screenshotNumber = 0;
MainWindow::MainWindow( bool debug ) :
QMainWindow(),
m_debug( debug )
{
m_centralWidget = new QMainWindow();
m_centralWidget->setObjectName( "central widget" );
m_centralWidget->setDockOptions( QMainWindow::AnimatedDocks | QMainWindow::AllowNestedDocks | QMainWindow::AllowTabbedDocks );
m_centralWidget->setDocumentMode( true );
setCentralWidget( m_centralWidget );
loadColormaps();
createActions();
createMenus();
createToolBars();
createDockWindows();
// this needs to be done after the view is created
m_toolsToolBar->setSelectionModel( m_datasetWidget->selectionModel() );
createStatusBar();
setWindowTitle( tr( "Fibernavigator 2" ) );
setUnifiedTitleAndToolBarOnMac( true );
loadSettings();
}
void MainWindow::closeEvent( QCloseEvent *event )
{
saveSettings();
}
void MainWindow::saveSettings()
{
QSettings settings;
settings.setValue( "mainWindowGeometry", saveGeometry() );
settings.setValue( "mainWindowState", saveState() );
settings.setValue( "centralWidgetGeometry", m_centralWidget->saveGeometry() );
settings.setValue( "centralWidgetState", m_centralWidget->saveState() );
settings.setValue( "lockDockTitles", lockDockTitlesAct->isChecked() );
settings.setValue( Fn::Global2String::s( Fn::Global::LAST_PATH ), Models::g()->data( Models::g()->index( (int)Fn::Global::LAST_PATH, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::SCREENSHOT_PATH ), Models::g()->data( Models::g()->index( (int)Fn::Global::SCREENSHOT_PATH, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::BACKGROUND_COLOR_MAIN ), Models::g()->data( Models::g()->index( (int)Fn::Global::BACKGROUND_COLOR_MAIN, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::BACKGROUND_COLOR_COMBINED ), Models::g()->data( Models::g()->index( (int)Fn::Global::BACKGROUND_COLOR_COMBINED, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::BACKGROUND_COLOR_NAV1 ), Models::g()->data( Models::g()->index( (int)Fn::Global::BACKGROUND_COLOR_NAV1, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::BACKGROUND_COLOR_NAV2 ), Models::g()->data( Models::g()->index( (int)Fn::Global::BACKGROUND_COLOR_NAV2, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::BACKGROUND_COLOR_NAV3 ), Models::g()->data( Models::g()->index( (int)Fn::Global::BACKGROUND_COLOR_NAV3, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::CROSSHAIR_COLOR ), Models::g()->data( Models::g()->index( (int)Fn::Global::CROSSHAIR_COLOR, 0 ) ) );
settings.setValue( Fn::Global2String::s( Fn::Global::SHOW_NAV_SLIDERS ), Models::g()->data( Models::g()->index( (int)Fn::Global::SHOW_NAV_SLIDERS, 0 ) ) );
QByteArray ar;
QDataStream out( &ar, QIODevice::WriteOnly ); // write the data
out << ColormapFunctions::size();
for ( int i = 0; i < ColormapFunctions::size(); ++i )
{
ColormapBase c = ColormapFunctions::get( i );
out << c.getName();
out << c.size();
for ( int k = 0; k < c.size(); ++k )
{
out << c.get( k ).value;
out << c.get( k ).color;
}
}
settings.setValue( "colormaps", ar );
}
void MainWindow::loadSettings()
{
QSettings settings;
restoreGeometry( settings.value( "mainWindowGeometry" ).toByteArray() );
restoreState( settings.value( "mainWindowState" ).toByteArray() );
m_centralWidget->restoreGeometry( settings.value( "centralWidgetGeometry" ).toByteArray() );
m_centralWidget->restoreState( settings.value( "centralWidgetState" ).toByteArray() );
if ( settings.contains( "lockDockTitles") )
{
if ( settings.value( "lockDockTitles" ).toBool() )
{
lockDockTitlesAct->activate( QAction::Trigger );
}
}
loadSetting( settings, Fn::Global::LAST_PATH );
loadSetting( settings, Fn::Global::SCREENSHOT_PATH );
loadSetting( settings, Fn::Global::BACKGROUND_COLOR_MAIN );
loadSetting( settings, Fn::Global::BACKGROUND_COLOR_COMBINED );
loadSetting( settings, Fn::Global::BACKGROUND_COLOR_NAV1 );
loadSetting( settings, Fn::Global::BACKGROUND_COLOR_NAV2 );
loadSetting( settings, Fn::Global::BACKGROUND_COLOR_NAV3 );
loadSetting( settings, Fn::Global::CROSSHAIR_COLOR );
loadSetting( settings, Fn::Global::SHOW_NAV_SLIDERS );
}
void MainWindow::loadSetting( QSettings &settings, Fn::Global setting )
{
if ( settings.contains( Fn::Global2String::s( setting) ) )
{
QVariant s = settings.value( Fn::Global2String::s( setting ) );
Models::g()->setData( Models::g()->index( (int)setting, 0 ), s );
}
}
void MainWindow::loadColormaps()
{
QSettings settings;
if ( settings.contains( "colormaps" ) )
{
qDebug() << "restore colormaps";
QByteArray ar = settings.value( "colormaps" ).toByteArray();
QDataStream in( &ar,QIODevice::ReadOnly );
int countColormaps;
in >> countColormaps;
for ( int i = 0; i < countColormaps; ++i )
{
QString name;
QVector< ColormapPair >values;
in >> name;
int cmapSize;
in >> cmapSize;
for ( int k = 0; k < cmapSize; ++k)
{
ColormapPair pair;
in >> pair.value;
in >> pair.color;
values.push_back( pair );
}
ColormapBase cmap( name, values );
ColormapFunctions::addColormap( cmap );
}
}
else
{
qDebug() << "create colormaps";
ColormapBase colormap( "grey", QColor( 3, 3, 3 ), QColor( 255, 255, 255 ) );
ColormapFunctions::addColormap( colormap );
ColormapBase cmap( "rainbow", QColor( 0, 0, 255 ), QColor( 255, 0, 0 ) );
cmap.insertValue( 0.25, QColor( 0, 255, 255 ) );
cmap.insertValue( 0.5, QColor( 0, 255, 0 ) );
cmap.insertValue( 0.75, QColor( 255, 255, 0 ) );
ColormapFunctions::addColormap( cmap );
ColormapBase cmap2( "rainbow 2", QColor( 0, 0, 255 ), QColor( 255, 0, 255 ) );
cmap2.insertValue( 0.2, QColor( 0, 255, 255 ) );
cmap2.insertValue( 0.4, QColor( 0, 255, 0 ) );
cmap2.insertValue( 0.6, QColor( 255, 255, 0 ) );
cmap2.insertValue( 0.8, QColor( 255, 0, 0 ) );
ColormapFunctions::addColormap( cmap2 );
ColormapBase cmap3( "blue white red", QColor( 0, 0, 255 ), QColor( 255, 0, 0 ) );
cmap3.insertValue( 0.5, QColor( 255, 255, 255 ) );
ColormapFunctions::addColormap( cmap3 );
}
}
void MainWindow::print()
{
}
void MainWindow::open()
{
QString fn = Models::g()->data( Models::g()->index( (int)Fn::Global::LAST_PATH, 0 ) ).toString();
QStringList fileNames = QFileDialog::getOpenFileNames( this, "Open File", fn );
for ( int i = 0; i < fileNames.size(); ++i )
{
load( fileNames[i] );
}
}
void MainWindow::openRecentFile()
{
QAction *action = qobject_cast< QAction * >( sender() );
if ( action )
{
load( action->data().toString() );
}
}
void MainWindow::load( QString fileName )
{
if ( !fileName.isEmpty() )
{
Loader loader;
loader.setFilename( QDir( fileName ) );
if ( loader.load() )
{
for ( int k = 0; k < loader.getNumDatasets(); ++k )
{
Models::d()->setData( Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::NEW_DATASET ), VPtr<Dataset>::asQVariant( loader.getDataset( k ) ), Qt::DisplayRole );
}
QFileInfo fi( fileName );
QDir dir = fi.absoluteDir();
QString lastPath = dir.absolutePath();
Models::g()->setData( Models::g()->index( (int)Fn::Global::LAST_PATH, 0 ), lastPath );
setCurrentFile(fileName);
}
}
}
void MainWindow::setCurrentFile( const QString &fileName )
{
curFile = fileName;
setWindowFilePath( curFile );
QSettings settings;
QStringList files = settings.value( "recentFileList" ).toStringList();
files.removeAll( fileName );
files.prepend( fileName );
while ( files.size() > MaxRecentFiles )
files.removeLast();
settings.setValue( "recentFileList", files );
foreach (QWidget *widget, QApplication::topLevelWidgets())
{
MainWindow *mainWin = qobject_cast< MainWindow * >( widget );
if ( mainWin )
mainWin->updateRecentFileActions();
}
}
void MainWindow::updateRecentFileActions()
{
QSettings settings;
QStringList files = settings.value( "recentFileList" ).toStringList();
int numRecentFiles = qMin( files.size(), (int) MaxRecentFiles );
for ( int i = 0; i < numRecentFiles; ++i )
{
QString text = tr( "&%1 %2" ).arg( i + 1 ).arg( strippedName( files[ i ] ) );
recentFileActs[ i ]->setText( text );
recentFileActs[ i ]->setData( files[ i ] );
recentFileActs[ i ]->setVisible( true );
}
for ( int j = numRecentFiles; j < MaxRecentFiles; ++j )
recentFileActs[ j ]->setVisible( false );
separatorAct->setVisible( numRecentFiles > 0 );
}
QString MainWindow::strippedName( const QString &fullFileName )
{
return QFileInfo( fullFileName ).fileName();
}
void MainWindow::save()
{
QString fn = Models::g()->data( Models::g()->index( (int)Fn::Global::LAST_PATH, 0 ) ).toString();
QString fileName = QFileDialog::getSaveFileName( this, "Save File", fn );
if ( !fileName.isEmpty() )
{
QDir dir;
if ( dir.exists( fileName ) )
{
QMessageBox msgBox;
msgBox.setText("File already exists.");
msgBox.setInformativeText("Do you want to overwrite it?");
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Save);
int ret = msgBox.exec();
switch ( ret )
{
case QMessageBox::Save :
{
Dataset* ds = VPtr<Dataset>::asPtr( Models::d()->data( Models::d()->index( m_datasetWidget->getSelected(), (int)Fn::Property::DATASET_POINTER) ) );
Writer writer( ds, fileName );
writer.save();
break;
}
case QMessageBox::Cancel :
break;
}
}
else
{
Dataset* ds = VPtr<Dataset>::asPtr( Models::d()->data( Models::d()->index( m_datasetWidget->getSelected(), (int)Fn::Property::DATASET_POINTER) ) );
Writer writer( ds, fileName );
writer.save();
}
QFileInfo fi( fileName );
dir = fi.absoluteDir();
QString lastPath = dir.absolutePath();
Models::g()->setData( Models::g()->index( (int)Fn::Global::LAST_PATH, 0 ), lastPath );
}
}
void MainWindow::undo()
{
}
void MainWindow::about()
{
QMessageBox::about( this, tr( "About Fibernavigator 2" ),
tr( "The <b>Fibernavigator 2</b> will be the replacement "
"of Fibernavigator and so much more." ) );
}
void MainWindow::createActions()
{
openAct = new QAction( QIcon( ":/icons/open.png" ), tr( "&Open..." ), this );
openAct->setShortcuts( QKeySequence::Open );
openAct->setStatusTip( tr( "Load Dataset" ) );
connect( openAct, SIGNAL(triggered()), this, SLOT(open()) );
saveAct = new QAction( QIcon( ":/icons/save.png" ), tr( "&Save..." ), this );
saveAct->setShortcuts( QKeySequence::Save );
saveAct->setStatusTip( tr( "Save the current form letter" ) );
connect( saveAct, SIGNAL(triggered()), this, SLOT(save()) );
printAct = new QAction( QIcon( ":/icons/print.png" ), tr( "&Print..." ), this );
printAct->setShortcuts( QKeySequence::Print );
printAct->setStatusTip( tr( "Print the current form letter" ) );
connect( printAct, SIGNAL(triggered()), this, SLOT(print()) );
quitAct = new QAction( tr( "&Quit" ), this );
quitAct->setShortcuts( QKeySequence::Quit );
quitAct->setStatusTip( tr( "Quit the application" ) );
connect( quitAct, SIGNAL(triggered()), this, SLOT(close()) );
screenshotAct = new QAction( tr( "Screenshot" ), this );
screenshotAct->setStatusTip( tr( "Sreenshot" ) );
connect( screenshotAct, SIGNAL(triggered()), this, SLOT(screenshot()) );
resetSettingsAct = new QAction( tr( "Reset Settings" ), this );
resetSettingsAct->setStatusTip( tr( "Reset Settings" ) );
connect( resetSettingsAct, SIGNAL(triggered()), this, SLOT(resetSettings()) );
aboutAct = new QAction( tr( "&About" ), this );
aboutAct->setStatusTip( tr( "Show the application's About box" ) );
connect( aboutAct, SIGNAL(triggered()), this, SLOT(about()) );
aboutQtAct = new QAction( tr( "About &Qt" ), this );
aboutQtAct->setStatusTip( tr( "Show the Qt library's About box" ) );
connect( aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()) );
showAxialAct = new QAction( QIcon( ":/icons/axial.png" ), tr( "Show Axial Slice" ), this );
showAxialAct->setStatusTip( tr( "Toggle rendering of the axial slice." ) );
showAxialAct->setCheckable( true );
showAxialAct->setChecked( true );
connect( showAxialAct, SIGNAL( toggled( bool ) ), this, SLOT( slotToggleAxialSlice() ) );
showCoronalAct = new QAction( QIcon( ":/icons/coronal.png" ), tr( "Show Coronal Slice" ), this );
showCoronalAct->setStatusTip( tr( "Toggle rendering of the coronal slice." ) );
showCoronalAct->setCheckable( true );
showCoronalAct->setChecked( true );
connect( showCoronalAct, SIGNAL( toggled( bool ) ), this, SLOT( slotToggleCoronalSlice() ) );
showSagittalAct = new QAction( QIcon( ":/icons/sagittal.png" ), tr( "Show Sagittal Slice" ), this );
showSagittalAct->setStatusTip( tr( "Toggle rendering of the sagittal slice." ) );
showSagittalAct->setCheckable( true );
showSagittalAct->setChecked( true );
connect( showSagittalAct, SIGNAL( toggled( bool ) ), this, SLOT( slotToggleSagittalSlice() ) );
standardViewAxialAct = new QAction( QIcon( ":/icons/axial.png" ), tr( "Axial View" ), this );
standardViewAxialAct->setStatusTip( tr( "Toggle rendering of the axial slice." ) );
connect( standardViewAxialAct, SIGNAL( triggered() ), this, SLOT( slotStandardAxialView() ) );
standardViewCoronalAct = new QAction( QIcon( ":/icons/coronal.png" ), tr( "Coronal View" ), this );
standardViewCoronalAct->setStatusTip( tr( "Toggle rendering of the coronal slice." ) );
connect( standardViewCoronalAct, SIGNAL( triggered() ), this, SLOT( slotStandardCoronalView() ) );
standardViewSagittalAct = new QAction( QIcon( ":/icons/sagittal.png" ), tr( "Sagittal view" ), this );
standardViewSagittalAct->setStatusTip( tr( "Toggle rendering of the sagittal slice." ) );
connect( standardViewSagittalAct, SIGNAL( triggered() ), this, SLOT( slotStandardSagittalView() ) );
toggleShaderEditAct = new QAction( QIcon( ":/icons/cat.png" ), tr( "Toggle shader edit" ), this );
toggleShaderEditAct->setStatusTip( tr( "Toggle the shader edit widget." ) );
connect( toggleShaderEditAct, SIGNAL( triggered() ), this, SLOT( slotToggleShaderEdit() ) );
lockDockTitlesAct = new QAction( tr( "Lock Widgets" ), this );
lockDockTitlesAct->setStatusTip( tr( "Lock all dock widgets in place" ) );
lockDockTitlesAct->setCheckable( true );
lockDockTitlesAct->setChecked( false );
renderCrosshairsAct = new QAction( tr( "Render Crosshairs" ), this );
renderCrosshairsAct->setStatusTip( tr( "render crosshairs in navigation widgets." ) );
renderCrosshairsAct->setCheckable( true );
renderCrosshairsAct->setChecked( true );
connect( renderCrosshairsAct, SIGNAL( toggled( bool ) ), this, SLOT( slotRenderCrosshairs( bool ) ) );
newSelectionBoxAct = new QAction( QIcon( ":/icons/box.png" ), tr( "New ROI" ), this );
newSelectionBoxAct->setStatusTip( tr( "Add a new ROI." ) );
#ifndef __WINDOWS__
dilbertAct = new QAction( QIcon( ":/icons/box.png" ), tr( "Dilbert" ), this );
dilbertAct->setStatusTip( tr( "Dilbert" ) );
connect( dilbertAct, SIGNAL( triggered() ), this, SLOT( slotDilbert() ) );
#endif
for ( int i = 0; i < MaxRecentFiles; ++i )
{
recentFileActs[ i ] = new QAction( this );
recentFileActs[ i ]->setVisible( false );
connect( recentFileActs[ i ], SIGNAL(triggered()), this, SLOT(openRecentFile()) );
}
}
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu( tr( "&File" ) );
fileMenu->addAction( openAct );
fileMenu->addAction( saveAct );
fileMenu->addAction( printAct );
separatorAct = fileMenu->addSeparator();
for ( int i = 0; i < MaxRecentFiles; ++i )
{
fileMenu->addAction( recentFileActs[ i ] );
}
fileMenu->addSeparator();
fileMenu->addAction( quitAct );
updateRecentFileActions();
optionMenu = menuBar()->addMenu( tr( "&Options" ) );
optionMenu->addAction( lockDockTitlesAct );
optionMenu->addAction( renderCrosshairsAct );
viewMenu = menuBar()->addMenu( tr( "&View" ) );
menuBar()->addSeparator();
helpMenu = menuBar()->addMenu( tr( "&Help" ) );
// helpMenu->addAction( screenshotAct );
helpMenu->addAction( resetSettingsAct );
#ifndef __WINDOWS__
helpMenu->addAction( dilbertAct );
#endif
helpMenu->addAction( aboutAct );
helpMenu->addAction( aboutQtAct );
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar( tr( "File" ) );
fileToolBar->addAction( openAct );
fileToolBar->addAction( saveAct );
//fileToolBar->addAction( printAct );
if ( m_debug )
{
fileToolBar->addAction( toggleShaderEditAct );
}
fileToolBar->setObjectName( "fileToolbar");
editToolBar = addToolBar( tr( "Edit" ) );
editToolBar->addAction( showAxialAct );
editToolBar->addAction( showCoronalAct );
editToolBar->addAction( showSagittalAct );
editToolBar->addAction( standardViewAxialAct );
editToolBar->addAction( standardViewCoronalAct );
editToolBar->addAction( standardViewSagittalAct );
editToolBar->addAction( newSelectionBoxAct );
editToolBar->setObjectName( "editToolbar");
m_toolsToolBar = new ToolBar( tr( "Tools" ), this );
addToolBar( m_toolsToolBar );
}
void MainWindow::createStatusBar()
{
StatusBar* sbar = new StatusBar( this );
sbar->setSelectionModel( m_datasetWidget->selectionModel() );
this->setStatusBar( sbar );
}
void MainWindow::createDockWindows()
{
m_datasetWidget = new DatasetListWidget();
FNDockWidget* dockDSW = new FNDockWidget( QString("Dataset List"), m_datasetWidget, this );
addDockWidget( Qt::LeftDockWidgetArea, dockDSW );
viewMenu->addAction( dockDSW->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockDSW, SLOT( toggleTitleWidget() ) );
connect( m_datasetWidget, SIGNAL( moveSelectedItemUp( int ) ), Models::d(), SLOT( moveItemUp( int ) ) );
connect( m_datasetWidget, SIGNAL( moveSelectedItemDown( int ) ), Models::d(), SLOT( moveItemDown( int ) ) );
connect( m_datasetWidget, SIGNAL( deleteSelectedItem( int ) ), Models::d(), SLOT( deleteItem( int ) ) );
ColormapEditWidget* colormapEditWidget = new ColormapEditWidget( this );
FNDockWidget* dockCE = new FNDockWidget( QString("colormap edit"), colormapEditWidget, this );
addDockWidget( Qt::LeftDockWidgetArea, dockCE );
viewMenu->addAction( dockCE->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockCE, SLOT( toggleTitleWidget() ) );
dockCE->hide();
ROIWidget* m_roiWidget = new ROIWidget( this );
FNDockWidget* dockSBW = new FNDockWidget( QString("ROIs"), m_roiWidget, this );
addDockWidget( Qt::RightDockWidgetArea, dockSBW );
viewMenu->addAction( dockSBW->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockSBW, SLOT( toggleTitleWidget() ) );
connect( newSelectionBoxAct, SIGNAL( triggered() ), m_roiWidget, SLOT( addBox() ) );
DatasetPropertyWidget* dsProperties = new DatasetPropertyWidget( this );
FNDockWidget* dockDSP = new FNDockWidget( QString("dataset properties"), dsProperties, this );
addDockWidget( Qt::LeftDockWidgetArea, dockDSP );
dsProperties->setSelectionModel( m_datasetWidget->selectionModel() );
viewMenu->addAction( dockDSP->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockDSP, SLOT( toggleTitleWidget() ) );
connect( colormapEditWidget, SIGNAL( signalUpdate() ), dsProperties, SLOT( update() ) );
ROIPropertyWidget* roiProperties = new ROIPropertyWidget( this );
FNDockWidget* dockRP = new FNDockWidget( QString("roi properties"), roiProperties, this );
addDockWidget( Qt::RightDockWidgetArea, dockRP );
roiProperties->setModel( Models::r() );
roiProperties->setSelectionModel( m_roiWidget->selectionModel() );
viewMenu->addAction( dockRP->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockRP, SLOT( toggleTitleWidget() ) );
GlobalPropertyWidget* globalProperties = new GlobalPropertyWidget( this );
FNDockWidget* dockGP = new FNDockWidget( QString("Global Properties"), globalProperties, this );
addDockWidget( Qt::LeftDockWidgetArea, dockGP );
globalProperties->setModel( Models::g() );
viewMenu->addAction( dockGP->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockGP, SLOT( toggleTitleWidget() ) );
DatasetInfoView *dsInfo = new DatasetInfoView( this );
FNDockWidget* dockDSI = new FNDockWidget( QString("dataset info"), dsInfo, this );
addDockWidget( Qt::BottomDockWidgetArea, dockDSI );
dsInfo->setModel( Models::d() );
dsInfo->setSelectionModel( m_datasetWidget->selectionModel() );
viewMenu->addAction( dockDSI->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockDSI, SLOT( toggleTitleWidget() ) );
dockDSI->hide();
tabifyDockWidget( dockGP, dockDSP );
tabifyDockWidget( dockGP, dockCE );
// GL Widgets
mainGLWidget = new GLWidget( m_roiWidget->selectionModel() );
FNDockWidget* dockMainGL = new FNDockWidget( QString("main gl"), mainGLWidget, this );
m_centralWidget->addDockWidget( Qt::LeftDockWidgetArea, dockMainGL );
viewMenu->addAction( dockMainGL->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockMainGL, SLOT( toggleTitleWidget() ) );
connect( colormapEditWidget, SIGNAL( signalUpdate() ), mainGLWidget, SLOT( update() ) );
DockNavGLWidget* nav1 = new DockNavGLWidget( QString("axial"), 2, this, mainGLWidget );
FNDockWidget* dockNav1 = new FNDockWidget( QString("axial"), nav1, this );
m_centralWidget->addDockWidget( Qt::RightDockWidgetArea, dockNav1 );
viewMenu->addAction( dockNav1->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockNav1, SLOT( toggleTitleWidget() ) );
connect( colormapEditWidget, SIGNAL( signalUpdate() ), nav1, SLOT( update() ) );
connect( dockNav1, SIGNAL( visibilityChanged( bool) ), nav1, SLOT( setWidgetVisible( bool) ) );
DockNavGLWidget* nav2 = new DockNavGLWidget( QString( "sagittal" ), 0, this, mainGLWidget );
FNDockWidget* dockNav2 = new FNDockWidget( QString("sagittal"), nav2, this );
m_centralWidget->addDockWidget( Qt::RightDockWidgetArea, dockNav2 );
viewMenu->addAction( dockNav2->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockNav2, SLOT( toggleTitleWidget() ) );
connect( colormapEditWidget, SIGNAL( signalUpdate() ), nav2, SLOT( update() ) );
connect( dockNav2, SIGNAL( visibilityChanged( bool) ), nav2, SLOT( setWidgetVisible( bool) ) );
DockNavGLWidget* nav3 = new DockNavGLWidget( QString( "coronal" ), 1, this, mainGLWidget );
FNDockWidget* dockNav3 = new FNDockWidget( QString("coronal"), nav3, this );
m_centralWidget->addDockWidget( Qt::RightDockWidgetArea, dockNav3 );
viewMenu->addAction( dockNav3->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockNav3, SLOT( toggleTitleWidget() ) );
connect( colormapEditWidget, SIGNAL( signalUpdate() ), nav3, SLOT( update() ) );
connect( dockNav3, SIGNAL( visibilityChanged( bool) ), nav3, SLOT( setWidgetVisible( bool ) ) );
CombinedNavGLWidget* nav4 = new CombinedNavGLWidget( QString( "combined" ), this, mainGLWidget );
FNDockWidget* dockNav4 = new FNDockWidget( QString("Combined Nav"), nav4, this );
m_centralWidget->addDockWidget( Qt::LeftDockWidgetArea, dockNav4 );
viewMenu->addAction( dockNav4->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockNav4, SLOT( toggleTitleWidget() ) );
connect( colormapEditWidget, SIGNAL( signalUpdate() ), nav4, SLOT( update() ) );
connect( dockNav4, SIGNAL( visibilityChanged( bool) ), nav4, SLOT( setWidgetVisible( bool ) ) );
dockNav1->hide();
dockNav2->hide();
dockNav3->hide();
dockNav4->hide();
SingleSHWidget* sshw = new SingleSHWidget( QString( "single sh" ), this, mainGLWidget );
FNDockWidget* dockSSHW = new FNDockWidget( QString("single sh" ), sshw, this );
m_centralWidget->addDockWidget( Qt::LeftDockWidgetArea, dockSSHW );
viewMenu->addAction( dockSSHW->toggleViewAction() );
connect( lockDockTitlesAct, SIGNAL( triggered() ), dockSSHW, SLOT( toggleTitleWidget() ) );
dockSSHW->hide();
m_centralWidget->tabifyDockWidget( dockSSHW, dockNav4 );
m_centralWidget->tabifyDockWidget( dockNav4, dockMainGL );
}
void MainWindow::slotToggleAxialSlice()
{
Models::g()->setData( Models::g()->index( (int)Fn::Global::SHOW_AXIAL, 0 ), showAxialAct->isChecked() );
}
void MainWindow::slotToggleCoronalSlice()
{
Models::g()->setData( Models::g()->index( (int)Fn::Global::SHOW_CORONAL, 0 ), showCoronalAct->isChecked() );
}
void MainWindow::slotToggleSagittalSlice()
{
Models::g()->setData( Models::g()->index( (int)Fn::Global::SHOW_SAGITTAL, 0 ), showSagittalAct->isChecked() );
}
void MainWindow::slotStandardAxialView()
{
Models::g()->setData( Models::g()->index( (int)Fn::Global::VIEW, 0 ), (int)Fn::Orient::AXIAL );
mainGLWidget->setView( Fn::Orient::AXIAL );
}
void MainWindow::slotStandardCoronalView()
{
Models::g()->setData( Models::g()->index( (int)Fn::Global::VIEW, 0 ), (int)Fn::Orient::CORONAL );
mainGLWidget->setView( Fn::Orient::CORONAL );
}
void MainWindow::slotStandardSagittalView()
{
Models::g()->setData( Models::g()->index( (int)Fn::Global::VIEW, 0 ), (int)Fn::Orient::SAGITTAL );
mainGLWidget->setView( Fn::Orient::SAGITTAL );
}
void MainWindow::slotToggleShaderEdit()
{
m_shaderEditWidget = new ShaderEditWidget( this );
FNDockWidget* dockSEW = new FNDockWidget( QString("shader edit" ), m_shaderEditWidget, this );
viewMenu->addAction( dockSEW->toggleViewAction() );
addDockWidget( Qt::RightDockWidgetArea, dockSEW );
}
void MainWindow::slotRenderCrosshairs( bool value )
{
Models::g()->setData( Models::g()->index( (int)Fn::Global::RENDER_CROSSHAIRS, 0 ), value );
}
void MainWindow::screenshot()
{
QImage* image = mainGLWidget->screenshot();
QString path = Models::g()->data( Models::g()->index( (int)Fn::Global::SCREENSHOT_PATH, 0 ) ).toString();
if ( !path.endsWith( '/') )
{
path += '/';
}
QString numberString = QString::number( screenshotNumber++ );
int nss = numberString.size();
for ( int i = 0; i < 4 - nss; ++i )
{
numberString = "0" + numberString;
}
image->save( path +
QString("screenshot_") +
numberString +
QString( ".png" ), "PNG" );
delete image;
}
void MainWindow::resetSettings()
{
QMessageBox msgBox;
msgBox.setText("Reset settings.");
msgBox.setInformativeText("This will shut down fibernavigator 2. Continue?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Yes);
int ret = msgBox.exec();
switch ( ret )
{
case QMessageBox::Yes :
{
QSettings settings;
settings.clear();
settings.sync();
exit( 0 );
break;
}
case QMessageBox::Cancel :
break;
}
}
void MainWindow::slotDilbert()
{
#ifndef __WINDOWS__
QWidget* widget = new QWidget();
QVBoxLayout* vLayout = new QVBoxLayout();
vLayout->setContentsMargins( 1, 1, 1, 1 );
vLayout->setSpacing( 1 );
QWebView* wv = new QWebView( this );
wv->setUrl( QUrl( "http://www.dilbert.com/fast/") );
vLayout->addWidget( wv );
widget->setLayout( vLayout );
widget->show();
#endif
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: Oculus.Platform.Models
namespace Oculus::Platform::Models {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: Oculus.Platform.Models.AssetFileDownloadResult
class AssetFileDownloadResult : public ::Il2CppObject {
public:
// public readonly System.UInt64 AssetId
// Size: 0x8
// Offset: 0x10
uint64_t AssetId;
// Field size check
static_assert(sizeof(uint64_t) == 0x8);
// public readonly System.String Filepath
// Size: 0x8
// Offset: 0x18
::Il2CppString* Filepath;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: AssetFileDownloadResult
AssetFileDownloadResult(uint64_t AssetId_ = {}, ::Il2CppString* Filepath_ = {}) noexcept : AssetId{AssetId_}, Filepath{Filepath_} {}
// public System.Void .ctor(System.IntPtr o)
// Offset: 0x14B226C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AssetFileDownloadResult* New_ctor(System::IntPtr o) {
static auto ___internal__logger = ::Logger::get().WithContext("Oculus::Platform::Models::AssetFileDownloadResult::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AssetFileDownloadResult*, creationType>(o)));
}
}; // Oculus.Platform.Models.AssetFileDownloadResult
#pragma pack(pop)
static check_size<sizeof(AssetFileDownloadResult), 24 + sizeof(::Il2CppString*)> __Oculus_Platform_Models_AssetFileDownloadResultSizeCheck;
static_assert(sizeof(AssetFileDownloadResult) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::Models::AssetFileDownloadResult*, "Oculus.Platform.Models", "AssetFileDownloadResult");
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/graph-reducer.h"
#include <functional>
#include "src/compiler/graph-inl.h"
namespace v8 {
namespace internal {
namespace compiler {
GraphReducer::GraphReducer(Graph* graph)
: graph_(graph), reducers_(graph->zone()) {}
static bool NodeIdIsLessThan(const Node* node, NodeId id) {
return node->id() < id;
}
void GraphReducer::ReduceNode(Node* node) {
static const unsigned kMaxAttempts = 16;
bool reduce = true;
for (unsigned attempts = 0; attempts <= kMaxAttempts; ++attempts) {
if (!reduce) return;
reduce = false; // Assume we don't need to rerun any reducers.
int before = graph_->NodeCount();
for (ZoneVector<Reducer*>::iterator i = reducers_.begin();
i != reducers_.end(); ++i) {
Reduction reduction = (*i)->Reduce(node);
Node* replacement = reduction.replacement();
if (replacement == NULL) {
// No change from this reducer.
} else if (replacement == node) {
// {replacement == node} represents an in-place reduction.
// Rerun all the reducers for this node, as now there may be more
// opportunities for reduction.
reduce = true;
break;
} else {
if (node == graph_->start()) graph_->SetStart(replacement);
if (node == graph_->end()) graph_->SetEnd(replacement);
// If {node} was replaced by an old node, unlink {node} and assume that
// {replacement} was already reduced and finish.
if (replacement->id() < before) {
node->ReplaceUses(replacement);
node->Kill();
return;
}
// Otherwise, {node} was replaced by a new node. Replace all old uses of
// {node} with {replacement}. New nodes created by this reduction can
// use {node}.
node->ReplaceUsesIf(
std::bind2nd(std::ptr_fun(&NodeIdIsLessThan), before), replacement);
// Unlink {node} if it's no longer used.
if (node->uses().empty()) {
node->Kill();
}
// Rerun all the reductions on the {replacement}.
node = replacement;
reduce = true;
break;
}
}
}
}
// A helper class to reuse the node traversal algorithm.
struct GraphReducerVisitor FINAL : public NullNodeVisitor {
explicit GraphReducerVisitor(GraphReducer* reducer) : reducer_(reducer) {}
void Post(Node* node) { reducer_->ReduceNode(node); }
GraphReducer* reducer_;
};
void GraphReducer::ReduceGraph() {
GraphReducerVisitor visitor(this);
// Perform a post-order reduction of all nodes starting from the end.
graph()->VisitNodeInputsFromEnd(&visitor);
}
// TODO(titzer): partial graph reductions.
} // namespace compiler
} // namespace internal
} // namespace v8
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#include "../JuceDemoHeader.h"
//==============================================================================
struct LiveConstantDemoComponent : public Component
{
LiveConstantDemoComponent() {}
void paint (Graphics& g)
{
g.fillAll (JUCE_LIVE_CONSTANT (Colour (0xffe5e7a7)));
g.setColour (JUCE_LIVE_CONSTANT (Colours::red.withAlpha (0.2f)));
int blockWidth = JUCE_LIVE_CONSTANT (0x120);
int blockHeight = JUCE_LIVE_CONSTANT (200);
g.fillRect ((getWidth() - blockWidth) / 2, (getHeight() - blockHeight) / 2, blockWidth, blockHeight);
Colour fontColour = JUCE_LIVE_CONSTANT (Colour (0xff000a55));
float fontSize = JUCE_LIVE_CONSTANT (30.0f);
g.setColour (fontColour);
g.setFont (fontSize);
g.drawFittedText (getDemoText(), getLocalBounds(), Justification::centred, 2);
}
static String getDemoText()
{
return JUCE_LIVE_CONSTANT ("Hello world!");
}
};
//==============================================================================
class LiveConstantEditorDemo : public Component,
private ButtonListener
{
public:
LiveConstantEditorDemo()
: startButton ("Begin Demo")
{
descriptionLabel.setMinimumHorizontalScale (1.0f);
descriptionLabel.setText ("This demonstrates the JUCE_LIVE_CONSTANT macro, which allows you to quickly "
"adjust primitive values at runtime by just wrapping them in a macro.\n\n"
"To understand what's going on in this demo, you should have a look at the "
"LiveConstantDemoComponent class in LiveConstantDemo.cpp, where you can see "
"the code that's invoking the demo below...",
dontSendNotification);
addAndMakeVisible (descriptionLabel);
addAndMakeVisible (startButton);
addChildComponent (demoComp);
startButton.addListener (this);
}
void paint (Graphics& g) override
{
fillStandardDemoBackground (g);
}
void resized() override
{
Rectangle<int> r (getLocalBounds().reduced (10));
demoComp.setBounds (r);
descriptionLabel.setBounds (r.removeFromTop (200));
startButton.setBounds (r.removeFromTop (22).removeFromLeft (250));
demoComp.setBounds (r.withTrimmedTop (10));
}
private:
Label descriptionLabel;
TextButton startButton;
LiveConstantDemoComponent demoComp;
void buttonClicked (Button*) override
{
startButton.setVisible (false);
demoComp.setVisible (true);
descriptionLabel.setText ("Tweak some of the colours and values in the pop-up window to see what "
"the effect of your changes would be on the component below...",
dontSendNotification);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LiveConstantEditorDemo)
};
#if ! (JUCE_IOS || JUCE_ANDROID)
// This static object will register this demo type in a global list of demos..
static JuceDemoType<LiveConstantEditorDemo> demo ("10 Components: Live Constants");
#endif
|
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <local_notifier/local_notifier_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
LocalNotifierPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("LocalNotifierPlugin"));
}
|
#include "vapor/VAssert.h"
#include <sstream>
#include <algorithm>
#include <set>
#include <vapor/UDUnitsClass.h>
#include <vapor/NetCDFCollection.h>
#include <vapor/utils.h>
#include <vapor/WASP.h>
#include <vapor/DerivedVar.h>
using namespace VAPoR;
using namespace Wasp;
namespace {
#ifdef UNUSED_FUNCTION
size_t numBlocks(
size_t min, size_t max, size_t bs
) {
size_t b0 = min / bs;
size_t b1 = max / bs;
return(b1-b0+1);
}
#endif
#ifdef UNUSED_FUNCTION
size_t numBlocks(
const vector <size_t> &min, const vector <size_t> &max,
const vector <size_t> &bs
) {
VAssert(min.size() == max.size());
VAssert(min.size() == bs.size());
size_t nblocks = 1;
for (int i=0; i<bs.size(); i++) {
nblocks *= numBlocks(min[i], max[i], bs[i]);
}
return(nblocks);
}
#endif
#ifdef UNUSED_FUNCTION
size_t numBlocks(
const vector <size_t> &dims, const vector <size_t> &bs
) {
VAssert(dims.size() == bs.size());
size_t nblocks = 1;
for (int i=0; i<bs.size(); i++) {
VAssert(dims[i] != 0);
nblocks *= (((dims[i] - 1) / bs[i]) + 1);
}
return(nblocks);
}
#endif
size_t numElements(
const vector <size_t> &min, const vector <size_t> &max
) {
VAssert(min.size() == max.size());
size_t nElements = 1;
for (int i=0; i<min.size(); i++) {
nElements *= (max[i] - min[i] + 1);
}
return(nElements);
}
#ifdef UNUSED_FUNCTION
size_t blockSize(const vector <size_t> &bs) {
size_t sz = 1;
for (int i=0; i<bs.size(); i++) {
sz *= bs[i];
}
return(sz);
}
#endif
#ifdef UNUSED_FUNCTION
vector <size_t> increment(vector <size_t> dims, vector <size_t> coord) {
VAssert(dims.size() == coord.size());
for (int i=0; i<coord.size(); i++) {
coord[i] += 1;
if (coord[i] < (dims[i])) {
break;
}
coord[i] = 0;
}
return(coord);
}
#endif
// Product of elements in a vector
//
size_t vproduct(vector <size_t> a) {
size_t ntotal = 1;
for (int i=0; i<a.size(); i++) ntotal *= a[i];
return(ntotal);
}
#ifdef UNUSED_FUNCTION
void extractBlock(
const float *data, const vector <size_t> &dims,
const vector <size_t> &bcoords, const vector <size_t> &bs, float *block
) {
VAssert(dims.size() == bcoords.size());
VAssert(dims.size() == bs.size());
// Block dimensions
//
size_t bz = bs.size() > 2 ? bs[2] : 1;
size_t by = bs.size() > 1 ? bs[1] : 1;
size_t bx = bs.size() > 0 ? bs[0] : 1;
// Data dimensions
//
size_t nz = dims.size() > 2 ? dims[2] : 1;
size_t ny = dims.size() > 1 ? dims[1] : 1;
size_t nx = dims.size() > 0 ? dims[0] : 1;
// Data dimensions
//
size_t bcz = bcoords.size() > 2 ? bcoords[2] : 0;
size_t bcy = bcoords.size() > 1 ? bcoords[1] : 0;
size_t bcx = bcoords.size() > 0 ? bcoords[0] : 0;
size_t z = bcz * bz;
for (size_t zb=0; zb<bz && z<nz; zb++, z++) {
size_t y = bcy * by;
for (size_t yb=0; yb<by && y<ny; yb++, y++) {
size_t x = bcx * bx;
for (size_t xb=0; xb<bx && x<nx; xb++, x++) {
block[bx*by*zb + bx*yb + xb] = data[nx*ny*z + nx*y + x];
}
}
}
}
#endif
#ifdef UNUSED_FUNCTION
void blockit(
const float *data, const vector <size_t> &dims,
const vector <size_t> &bs, float *blocks
) {
VAssert(dims.size() == bs.size());
size_t block_size = vproduct(bs);
vector <size_t> bdims;
for (int i=0; i<bs.size(); i++) {
bdims.push_back(((dims[i] - 1) / bs[i]) + 1);
}
size_t nbz = bdims.size() > 2 ? bdims[2] : 1;
size_t nby = bdims.size() > 1 ? bdims[1] : 1;
size_t nbx = bdims.size() > 0 ? bdims[0] : 1;
float *blockptr = blocks;
vector <size_t> bcoord(bdims.size(), 0);
for (size_t zb=0; zb<nbz; zb++) {
for (size_t yb=0; yb<nby; yb++) {
for (size_t xb=0; xb<nbx; xb++) {
extractBlock(data, dims, bcoord, bs, blockptr);
blockptr += block_size;
bcoord = increment(bdims, bcoord);
}
}
}
}
#endif
// make 2D lat and lon arrays from 1D arrays by replication, in place
//
void make2D(
float *lonBuf, float *latBuf, vector <size_t> dims
) {
VAssert(dims.size() == 2);
size_t nx = dims[0];
size_t ny = dims[1];
// longitude
//
for (int j=1; j<ny; j++) {
for (int i=0; i<nx; i++) {
lonBuf[j*nx+i] = lonBuf[i];
}
}
// latitude requires a transpose first
//
for (int i=0; i<ny; i++) {
latBuf[i*nx] = latBuf[i];
}
for (int j=0; j<ny; j++) {
for (int i=1; i<nx; i++) {
latBuf[j*nx+i] = latBuf[j*nx];
}
}
}
// Transpose a 1D, 2D, or 3D array. For 1D 'a' is simply copied
// to 'b'. Otherwise 'b' contains a permuted version of 'a' as follows:
//
// axis 1D 2D 3D
// ---- -- -- --
// 0 (0) (0,1) (0,1,2)
// 1 N/A (1,0) (1,0,2)
// 2 N/A N/A (2,0,1)
//
// where the numbers in parenthesis indicate the permutation of the
// axes.
//
// NOTE: The contents of 'a' are overwritten
//
void transpose(
float *a, float *b, vector <size_t> inDims, int axis
) {
VAssert(inDims.size() < 4);
VAssert(axis >= 0 && axis < inDims.size());
size_t sz = vproduct(inDims);
// No-op if axis is 0
//
if (axis == 0) { // 1D, 2D, and 3D case
for (size_t i=0; i<sz; i++) {
b[i] = a[i];
}
return;
}
if (inDims.size() == 2) {
VAssert(axis == 1);
Wasp::Transpose(a, b, inDims[0], inDims[1]);
}
else if (inDims.size() == 3) {
VAssert(axis == 1 || axis == 2);
size_t stride = inDims[0] * inDims[1];;
const float *aptr = a;
float *bptr = b;
for (size_t i=0; i<inDims[2]; i++) {
Wasp::Transpose(aptr, bptr, inDims[0], inDims[1]);
aptr += stride;
bptr += stride;
}
// For (2,1,0) permutation we do (0,1,2) -> (1,0,2) -> (2,1,0)
//
if (axis == 2) {
// We can treat 3D array as 2D in this case, linearizing X and Y
//
Wasp::Transpose(b, a, inDims[0]*inDims[1], inDims[2]);
// Ugh need to copy data from a back to b
//
for (size_t i=0; i<vproduct(inDims); i++) {
b[i] = a[i];
}
}
}
}
void transpose(
vector <size_t> inDims, int axis, vector <size_t> &outDims
) {
outDims = inDims;
if (axis == 1) {
size_t tmp = outDims[0];
outDims[0] = outDims[1];
outDims[1] = tmp;
}
else if (axis == 2) {
size_t tmp = outDims[0];
outDims[0] = outDims[2];
outDims[2] = tmp;
}
}
void resampleToStaggered(
float *src,
const vector <size_t> &inMin,
const vector <size_t> &inMax,
float *dst,
const vector <size_t> &outMin,
const vector <size_t> &outMax,
int stagDim
) {
VAssert(inMin.size() == inMax.size());
VAssert(inMin.size() == outMax.size());
VAssert(inMin.size() == outMax.size());
vector <size_t> inDims, outDims;
for (size_t i=0; i<outMin.size(); i++) {
inDims.push_back(inMax[i]-inMin[i]+1);
outDims.push_back(outMax[i]-outMin[i]+1);
}
size_t sz = std::max(vproduct(outDims), vproduct(inDims));
float *buf = new float[sz];
// Tranpose the dimensions and array so that we always interpolate
// with unit stride
//
vector <size_t> inDimsT; // transposed input dimensions
vector <size_t> outDimsT; // transposed output dimensions
transpose(inDims, stagDim, inDimsT);
transpose(outDims, stagDim, outDimsT);
transpose(src, buf, inDims, stagDim);
size_t nz = inDimsT.size() >= 3 ? inDimsT[2] : 1;
size_t ny = inDimsT.size() >= 2 ? inDimsT[1] : 1;
size_t nx = inDimsT.size() >= 1 ? inDimsT[0] : 1;
// Interpolate interior
//
size_t nxs = outDimsT[0]; // staggered dimension
size_t i0 = outMin[stagDim] > inMin[stagDim] ? 0 : 1;
for (size_t k=0; k<nz; k++) {
for (size_t j=0; j<ny; j++) {
for (size_t i=0, ii=i0; i<nx-1; i++, ii++) {
src[k*nxs*ny + j*nxs + ii] = 0.5 * (
buf[k*nx*ny + j*nx + i] + buf[k*nx*ny + j*nx + i+1]
);
}
}
}
// Next extrapolate boundary points if needed
//
// left boundary
//
if (outMin[stagDim] <= inMin[stagDim]) {
if (inMin[stagDim] < inMax[stagDim]) {
for (size_t k=0; k<nz; k++) {
for (size_t j=0; j<ny; j++) {
src[k*nxs*ny + j*nxs] = buf[k*nx*ny + j*nx + 0] +
(-0.5*(buf[k*nx*ny + j*nx+1] - buf[k*nx*ny + j*nx + 0]));
}
}
}
else {
for (size_t k=0; k<nz; k++) {
for (size_t j=0; j<ny; j++) {
src[k*nxs*ny + j*nxs] = buf[k*nx*ny + j*nx + 0];
}
}
}
}
// right boundary
//
if (outMax[stagDim] > inMax[stagDim]) {
if (inMin[stagDim] < inMax[stagDim]) {
for (size_t k=0; k<nz; k++) {
for (size_t j=0; j<ny; j++) {
src[k*nxs*ny + j*nxs + nxs-1] = buf[k*nx*ny + j*nx+nx-1] +
(0.5*(buf[k*nx*ny + j*nx + nx-1]-buf[k*nx*ny + j*nx +nx-2]));
}
}
}
else {
for (size_t k=0; k<nz; k++) {
for (size_t j=0; j<ny; j++) {
src[k*nxs*ny + j*nxs + nxs-1] = buf[k*nx*ny + j*nx+nx-1];
}
}
}
}
// Undo tranpose
//
transpose(src, dst, outDimsT, stagDim);
delete [] buf;
}
void resampleToUnStaggered(
float *src,
const vector <size_t> &inMin,
const vector <size_t> &inMax,
float *dst,
const vector <size_t> &outMin,
const vector <size_t> &outMax,
int stagDim
) {
VAssert(inMin.size() == inMax.size());
VAssert(inMin.size() == outMax.size());
VAssert(inMin.size() == outMax.size());
vector <size_t> myOutMax = outMax;
vector <size_t> myOutMin = outMin;
myOutMin[stagDim] += 1;
myOutMax[stagDim] += 1;
resampleToStaggered(
src, inMin, inMax, dst, myOutMin, myOutMax, stagDim
);
}
#ifdef UNIT_TEST
void print_matrix(const float *a, const vector <size_t> &dims) {
size_t nz = dims.size() >= 3 ? dims[2] : 1;
size_t ny = dims.size() >= 2 ? dims[1] : 1;
size_t nx = dims.size() >= 1 ? dims[0] : 1;
for (int k=0; k<nz; k++) {
for (int j=0; j<ny; j++) {
for (int i=0; i<nx; i++) {
cout << a[k*nx*ny + j*nx + i] << " ";
}
cout << endl;
}
cout << endl;
}
}
void test_resample(int stagDim) {
vector <size_t> inMin = {0,0,0};
vector <size_t> inMax = {1,2,3};
vector <size_t> outMin = inMin;
vector <size_t> outMax = inMax;
outMax[stagDim] += 1;
vector <size_t> inDims, outDims;
for (int i=0; i<inMax.size(); i++) {
inDims.push_back(inMax[i]-inMin[i] + 1);
outDims.push_back(outMax[i]-outMin[i] + 1);
}
size_t nz = inDims.size() >= 3 ? inDims[2] : 1;
size_t ny = inDims.size() >= 2 ? inDims[1] : 1;
size_t nx = inDims.size() >= 1 ? inDims[0] : 1;
size_t nzs = outDims.size() >= 3 ? outDims[2] : 1;
size_t nys = outDims.size() >= 2 ? outDims[1] : 1;
size_t nxs = outDims.size() >= 1 ? outDims[0] : 1;
size_t sz = std::max(vproduct(outDims), vproduct(inDims));
float *src = new float[sz];
float *dst = new float[sz];
for (int k=0; k<nz; k++) {
for (int j=0; j<ny; j++) {
for (int i=0; i<nx; i++) {
src[k*nx*ny + j*nx + i] = k*nx*ny + j*nx + i;
}
}
}
for (int k=0; k<nzs; k++) {
for (int j=0; j<nys; j++) {
for (int i=0; i<nxs; i++) {
dst[k*nxs*nys + j*nxs + i] = 99;
}
}
}
cout << "original array" << endl;
print_matrix(src, inDims);
resampleToStaggered(src, inMin, inMax, dst, outMin, outMax, stagDim);
cout << endl << endl;
cout << "staggered array" << endl;
print_matrix(dst, outDims);
resampleToUnStaggered(dst, outMin, outMax, src, inMin, inMax, stagDim);
cout << "reconstructed unstaggered array" << endl;
print_matrix(src, inDims);
}
int main(int argc, char **argv) {
VAssert(argc == 2);
int stagDim = atoi(argv[1]);
test_resample(stagDim);
}
#endif
};
int DerivedVar::_getVar(
DC *dc, size_t ts, string varname, int level, int lod,
const vector <size_t> &min, const vector <size_t> &max, float *region
) const {
int fd = dc->OpenVariableRead(ts, varname, level, lod);
if (fd<0) return(-1);
int rc = dc->ReadRegion(fd, min, max, region);
if (rc<0) {
dc->CloseVariable(fd);
return(-1);
}
return(dc->CloseVariable(fd));
}
int DerivedVar::_getVarDestagger(
DC *dc, size_t ts, string varname, int level, int lod,
const vector <size_t> &min, const vector <size_t> &max, float *region,
int stagDim
) const {
VAssert(stagDim >=0 && stagDim < max.size());
VAssert(min.size() == max.size());
vector <size_t> maxIn = max;
maxIn[stagDim]++;
vector <size_t> dimsIn;
for (int i=0; i<min.size(); i++) {
dimsIn.push_back(max[i]-min[i]+1);
}
vector <float> buf(vproduct(dimsIn));
int rc = _getVar(dc, ts, varname, level, lod, min, maxIn, buf.data());
if (rc<0) return(rc);
resampleToUnStaggered(buf.data(), min, maxIn, region, min, max, stagDim);
return(0);
}
int DerivedVar::_getVarBlock(
DC *dc, size_t ts, string varname, int level, int lod,
const vector <size_t> &min, const vector <size_t> &max, float *region
) const {
int fd = dc->OpenVariableRead(ts, varname, level, lod);
if (fd<0) return(-1);
int rc = dc->ReadRegionBlock(fd, min, max, region);
if (rc<0) {
dc->CloseVariable(fd);
return(-1);
}
return(dc->CloseVariable(fd));
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVar_PCSFromLatLon
//
//////////////////////////////////////////////////////////////////////////////
DerivedCoordVar_PCSFromLatLon::DerivedCoordVar_PCSFromLatLon(
string derivedVarName,
DC *dc, vector <string> inNames, string proj4String, bool uGridFlag,
bool lonFlag
) : DerivedCoordVar(derivedVarName) {
VAssert(inNames.size() == 2);
_dc = dc;
_proj4String = proj4String;
_lonName = inNames[0];
_latName = inNames[1];
_make2DFlag = false;
_uGridFlag = uGridFlag;
_lonFlag = lonFlag;
_dimLens.clear();
}
int DerivedCoordVar_PCSFromLatLon::Initialize() {
int rc = _proj4API.Initialize("", _proj4String);
if (rc<0) {
SetErrMsg("Invalid map projection : %s", _proj4String.c_str());
return(-1);
}
rc = _setupVar();
if (rc<0) return(-1);
return(0);
}
bool DerivedCoordVar_PCSFromLatLon::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVar_PCSFromLatLon::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVar_PCSFromLatLon::GetDimLensAtLevel(
int , std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
dims_at_level = _dimLens;
// No blocking
//
bs_at_level = vector <size_t> (dims_at_level.size(), 1);
return(0);
}
int DerivedCoordVar_PCSFromLatLon::OpenVariableRead(
size_t ts, int , int
) {
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, -1, -1
);
return(_fileTable.AddEntry(f));
}
int DerivedCoordVar_PCSFromLatLon::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
_fileTable.RemoveEntry(fd);
delete f;
return(0);
}
int DerivedCoordVar_PCSFromLatLon::_readRegionHelperCylindrical(
DC::FileTable::FileObject *f,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
VAssert(min.size() == 1);
VAssert(min.size() == max.size());
size_t ts = f->GetTS();
string varname = f->GetVarname();
int lod = f->GetLOD();
size_t nElements = max[0] - min[0] + 1;
float *buf = new float[nElements];
for (int i=0; i<nElements; i++) {
buf[i] = 0.0;
}
string geoCoordVar;
if (_lonFlag) {
geoCoordVar = _lonName;
}
else {
geoCoordVar = _latName;
}
int rc = _getVar(_dc,ts,geoCoordVar,-1,lod, min, max, region);
if (rc<0) {
delete [] buf;
return(rc);
}
if (_lonFlag) {
rc = _proj4API.Transform(region, buf, nElements);
}
else {
rc = _proj4API.Transform(buf, region, nElements);
}
delete [] buf;
return(rc);
}
int DerivedCoordVar_PCSFromLatLon::_readRegionHelper1D(
DC::FileTable::FileObject *f,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
size_t ts = f->GetTS();
string varname = f->GetVarname();
int lod = f->GetLOD();
// Need temporary buffer space for the X or Y coordinate
// NOT being returned (we still need to calculate it)
//
size_t nElements = numElements(min, max);
float *buf = new float[nElements];
vector <size_t> roidims;
for (int i=0; i<min.size(); i++) {
roidims.push_back(max[i] - min[i] + 1);
}
// Assign temporary buffer 'buf' as appropriate
//
float *lonBufPtr;
float *latBufPtr;
if (_lonFlag) {
lonBufPtr = region;
latBufPtr = buf;
}
else {
lonBufPtr = buf;
latBufPtr = region;
}
// Reading 1D data so no blocking
//
vector <size_t> lonMin = {min[0]};
vector <size_t> lonMax = {max[0]};
int rc = _getVar(_dc,ts,_lonName,-1,lod, lonMin, lonMax, lonBufPtr);
if (rc<0) {
delete [] buf;
return(rc);
}
vector <size_t> latMin = {min[1]};
vector <size_t> latMax = {max[1]};
rc = _getVar(_dc, ts, _latName, -1, lod, latMin, latMax, latBufPtr);
if (rc<0) {
delete [] buf;
return(rc);
}
// Combine the 2 1D arrays into a 2D array
//
make2D(lonBufPtr, latBufPtr, roidims);
rc = _proj4API.Transform(lonBufPtr, latBufPtr, vproduct(roidims));
delete [] buf;
return(rc);
}
int DerivedCoordVar_PCSFromLatLon::_readRegionHelper2D(
DC::FileTable::FileObject *f,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
size_t ts = f->GetTS();
string varname = f->GetVarname();
int lod = f->GetLOD();
// Need temporary buffer space for the X or Y coordinate
// NOT being returned (we still need to calculate it)
//
size_t nElements = numElements(min, max);
float *buf = new float[nElements];
// Assign temporary buffer 'buf' as appropriate
//
float *lonBufPtr;
float *latBufPtr;
if (_lonFlag) {
lonBufPtr = region;
latBufPtr = buf;
}
else {
lonBufPtr = buf;
latBufPtr = region;
}
int rc = _getVar(_dc, ts, _lonName, -1, lod, min, max, lonBufPtr);
if (rc<0) {
delete [] buf;
return(rc);
}
rc = _getVar(_dc, ts, _latName, -1, lod, min, max, latBufPtr);
if (rc<0) {
delete [] buf;
return(rc);
}
rc = _proj4API.Transform(lonBufPtr, latBufPtr, nElements);
delete [] buf;
return(rc);
}
int DerivedCoordVar_PCSFromLatLon::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor: %d", fd);
return(-1);
}
if (min.size() == 1) {
// Lat and Lon are 1D variables
//
return(_readRegionHelperCylindrical(f,min,max,region));
}
else {
if (_make2DFlag) {
// Lat and Lon are 1D variables but projections to PCS
// result in X and Y coordinate variables that are 2D
//
return(_readRegionHelper1D(f, min, max, region));
}
else {
return(_readRegionHelper2D(f, min, max, region));
}
}
}
bool DerivedCoordVar_PCSFromLatLon::VariableExists(
size_t ts,
int ,
int
) const {
return(
_dc->VariableExists(ts, _lonName, -1, -1) &&
_dc->VariableExists(ts, _latName, -1, -1)
);
}
int DerivedCoordVar_PCSFromLatLon::_setupVar() {
DC::CoordVar lonVar;
bool ok = _dc->GetCoordVarInfo(_lonName, lonVar);
if (! ok) return(-1);
DC::CoordVar latVar;
ok = _dc->GetCoordVarInfo(_latName, latVar);
if (! ok) return(-1);
vector <size_t> lonDims;
ok = _dc->GetVarDimLens(_lonName, true, lonDims);
if (! ok) {
SetErrMsg("GetVarDimLens(%s) failed", _lonName.c_str());
return(-1);
}
vector <size_t> latDims;
ok = _dc->GetVarDimLens(_latName, true, latDims);
if (! ok) {
SetErrMsg("GetVarDimLens(%s) failed", _lonName.c_str());
return(-1);
}
if (lonDims.size() != latDims.size()) {
SetErrMsg("Incompatible block size");
return(-1);
}
bool cylProj = _proj4API.IsCylindrical();
vector <string> dimNames;
if (lonVar.GetDimNames().size() == 1 && !_uGridFlag) {
if (cylProj) {
if (_lonFlag) {
dimNames.push_back(lonVar.GetDimNames()[0]);
_dimLens.push_back(lonDims[0]);
}
else {
dimNames.push_back(latVar.GetDimNames()[0]);
_dimLens.push_back(latDims[0]);
}
}
else {
dimNames.push_back(lonVar.GetDimNames()[0]);
dimNames.push_back(latVar.GetDimNames()[0]);
_dimLens.push_back(lonDims[0]);
_dimLens.push_back(latDims[0]);
_make2DFlag = true;
}
}
else if (lonVar.GetDimNames().size() == 2 && !_uGridFlag) {
if (lonDims[0] != latDims[0] && lonDims[1] != latDims[1]) {
SetErrMsg("Incompatible dimensions ");
return(-1);
}
dimNames.push_back(lonVar.GetDimNames()[0]);
dimNames.push_back(lonVar.GetDimNames()[1]);
_dimLens.push_back(lonDims[0]);
_dimLens.push_back(lonDims[1]);
_make2DFlag = false;
}
else {
VAssert(lonVar.GetDimNames().size() == 1 && _uGridFlag);
dimNames = lonVar.GetDimNames();
_dimLens = lonDims;
}
if (lonVar.GetTimeDimName() != latVar.GetTimeDimName()) {
SetErrMsg("Incompatible time dimensions");
return(-1);
}
string timeDimName = lonVar.GetTimeDimName();
DC::XType xtype = lonVar.GetXType();
vector <bool> periodic = lonVar.GetPeriodic();
_coordVarInfo.SetName(_derivedVarName);
_coordVarInfo.SetUnits("meters");
_coordVarInfo.SetXType(xtype);
_coordVarInfo.SetWName("");
_coordVarInfo.SetCRatios(vector <size_t> ());
_coordVarInfo.SetPeriodic(periodic);
_coordVarInfo.SetUniform(false);
_coordVarInfo.SetDimNames(dimNames);
_coordVarInfo.SetTimeDimName(timeDimName);
_coordVarInfo.SetAxis(_lonFlag ? 0 : 1);
return(0);
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVar_CF1D
//
//////////////////////////////////////////////////////////////////////////////
DerivedCoordVar_CF1D::DerivedCoordVar_CF1D(
string derivedVarName, DC *dc,
string dimName, int axis, string units
) : DerivedCoordVar(derivedVarName) {
_dc = dc;
_dimName = dimName;
_dimLen = 0;
_coordVarInfo = DC::CoordVar(
_derivedVarName, units, DC::XType::FLOAT,
vector <bool> (1, false), axis, false,
vector <string> (1, dimName), ""
);
}
int DerivedCoordVar_CF1D::Initialize() {
DC::Dimension dimension;
int rc = _dc->GetDimension(_dimName, dimension);
if (rc<0) return(-1);
_dimLen = dimension.GetLength();
return(0);
}
bool DerivedCoordVar_CF1D::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVar_CF1D::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVar_CF1D::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
dims_at_level.push_back(_dimLen);
// No blocking
//
bs_at_level = vector <size_t> (dims_at_level.size(), 1);
return(0);
}
int DerivedCoordVar_CF1D::OpenVariableRead(
size_t ts, int level, int lod
) {
if (level != 0) {
SetErrMsg("Invalid parameter");
return(-1);
}
if (lod != 0) {
SetErrMsg("Invalid parameter");
return(-1);
}
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, level, lod
);
return(_fileTable.AddEntry(f));
return(0);
}
int DerivedCoordVar_CF1D::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
_fileTable.RemoveEntry(fd);
delete f;
return(0);
}
int DerivedCoordVar_CF1D::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
VAssert(min.size() == 1);
VAssert(max.size() == 1);
float *regptr = region;
for (size_t i=min[0]; i<=max[0]; i++) {
*regptr++ = (float) i;
}
return(0);
}
bool DerivedCoordVar_CF1D::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
if (reflevel != 0) return(false);
if (lod != 0) return(false);
return(true);
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVar_CF2D
//
//////////////////////////////////////////////////////////////////////////////
DerivedCoordVar_CF2D::DerivedCoordVar_CF2D(
string derivedVarName, vector <string> dimNames,
vector <size_t> dimLens, int axis, string units,
const vector <float> &data
) : DerivedCoordVar(derivedVarName) {
VAssert(dimNames.size() == 2);
VAssert(dimLens.size() == 2);
VAssert(dimLens[0] * dimLens[1] <= data.size());
_dimNames = dimNames;
_dimLens = dimLens;
_data = data;
_coordVarInfo = DC::CoordVar(
_derivedVarName, units, DC::XType::FLOAT,
vector <bool> (2, false), axis, false, dimNames, ""
);
}
int DerivedCoordVar_CF2D::Initialize() {
return(0);
}
bool DerivedCoordVar_CF2D::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVar_CF2D::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVar_CF2D::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
dims_at_level = _dimLens;
// No blocking
//
bs_at_level = vector <size_t> (dims_at_level.size(), 1);
return(0);
}
int DerivedCoordVar_CF2D::OpenVariableRead(
size_t ts, int level, int lod
) {
return(0);
}
int DerivedCoordVar_CF2D::CloseVariable(int fd) {
return(0);
}
int DerivedCoordVar_CF2D::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
VAssert(min.size() == 2);
VAssert(max.size() == 2);
float *regptr = region;
for (size_t j=min[1]; j<=max[1]; j++) {
for (size_t i=min[0]; i<=max[0]; i++) {
*regptr++ = (float) _data[j*_dimLens[0] + i];
}
}
return(0);
}
bool DerivedCoordVar_CF2D::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
if (reflevel != 0) return(false);
if (lod != 0) return(false);
return(true);
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVar_WRFTime
//
//////////////////////////////////////////////////////////////////////////////
DerivedCoordVar_WRFTime::DerivedCoordVar_WRFTime(
string derivedVarName, NetCDFCollection *ncdfc,
string wrfTimeVar, string dimName, float p2si
) : DerivedCoordVar(derivedVarName) {
_ncdfc = ncdfc;
_times.clear();
_timePerm.clear();
_wrfTimeVar = wrfTimeVar;
_p2si = p2si;
_ovr_ts = 0;
string units = "seconds";
int axis = 3;
_coordVarInfo = DC::CoordVar(
_derivedVarName, units, DC::XType::FLOAT,
vector <bool> (), axis, false,
vector <string> (), dimName
);
}
int DerivedCoordVar_WRFTime::_encodeTime(
UDUnits &udunits,
const vector <string> &timeStrings,
vector <double> ×
) const {
times.clear();
for (int i=0; i<timeStrings.size(); i++) {
const string &s = timeStrings[i];
const char *format6 = "%4d-%2d-%2d_%2d:%2d:%2d";
int year, mon, mday, hour, min, sec;
int rc = sscanf(s.data(), format6, &year, &mon, &mday, &hour,&min,&sec);
if (rc != 6) {
// Alternate date format
//
const char *format5 = "%4d-%5d_%2d:%2d:%2d";
rc = sscanf(s.data(), format5, &year, &mday, &hour, &min, &sec);
if (rc != 5) {
SetErrMsg("Unrecognized time stamp: %s", s.data());
return(-1);
}
mon = 1;
}
times.push_back(
udunits.EncodeTime(year, mon, mday, hour, min, sec) * _p2si
);
}
return(0);
}
int DerivedCoordVar_WRFTime::Initialize() {
_times.clear();
_timePerm.clear();
// Use UDUnits for unit conversion
//
UDUnits udunits;
int rc = udunits.Initialize();
if (rc<0) {
SetErrMsg(
"Failed to initialize udunits2 library : %s",
udunits.GetErrMsg().c_str()
);
return(-1);
}
size_t numTS = _ncdfc->GetNumTimeSteps();
if (numTS < 1) return(0);
vector <size_t> dims = _ncdfc->GetSpatialDims(_wrfTimeVar);
if (dims.size() != 1) {
SetErrMsg("Invalid WRF time variable : %s", _wrfTimeVar.c_str());
return(-1);
}
// Read all of the formatted time strings up front - it's a 1D array
// so we can simply store the results in memory - and convert from
// a formatted time string to seconds since the EPOCH
//
vector <string> timeStrings;
char *buf = new char[dims[0]+1];
buf[dims[0]] = '\0';
for (size_t ts = 0; ts < numTS; ts++) {
int fd = _ncdfc->OpenRead(ts, _wrfTimeVar);
if (fd<0) {
SetErrMsg("Can't read time variable");
return(-1);
}
int rc = _ncdfc->Read(buf, fd);
if (rc<0) {
SetErrMsg("Can't read time variable");
_ncdfc->Close(fd);
delete [] buf;
return(-1);
}
_ncdfc->Close(fd);
timeStrings.push_back(buf);
}
delete [] buf;
// Encode time stamp string as double precision float
//
vector <double> timesD;
rc = _encodeTime(udunits, timeStrings, timesD);
if (rc<0) return(rc);
// Convert to single precision because that's what the API supports
//
for (int i=0; i<timesD.size(); i++) {
_times.push_back((float) timesD[i]);
}
// For high temporal resolution single precision may be insufficient:
// converting from double to single may result in non-unique values.
// Check to see that the number of unique values is the same for the
// double and float vectors. If not, change the year to 2000 to reduce
// the precision needed.
//
if (std::set<double>(timesD.begin(), timesD.end()).size() !=
std::set<double>(_times.begin(), _times.end()).size()
) {
_times.clear();
for (int i=0; i<timeStrings.size(); i++) {
timeStrings[i].replace(0,4,"2000");
}
rc = _encodeTime(udunits, timeStrings, timesD);
if (rc<0) return(rc);
for (int i=0; i<timesD.size(); i++) {
_times.push_back((float) timesD[i]);
}
}
// The NetCDFCollection class doesn't handle the WRF time
// variable. Hence, the time steps aren't sorted. Sort them now and
// create a lookup table to map a time index to the correct time step
// in the WRF data collection. N.B. this is only necessary if multiple
// WRF files are present and they're not passed to Initialize() in
// the correct order.
//
_timePerm.clear();
for (int i = 0 ; i != _times.size() ; i++) {
_timePerm.push_back(i);
}
sort(
_timePerm.begin(), _timePerm.end(), [&](const int& a, const int& b) {
return (_times[a] < _times[b]);
}
);
return(0);
}
bool DerivedCoordVar_WRFTime::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVar_WRFTime::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVar_WRFTime::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
return(0);
}
int DerivedCoordVar_WRFTime::OpenVariableRead(
size_t ts, int level, int lod
) {
ts = ts < _times.size() ? ts : _times.size() - 1;
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, level, lod
);
return(_fileTable.AddEntry(f));
}
int DerivedCoordVar_WRFTime::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
_fileTable.RemoveEntry(fd);
delete f;
return(0);
}
int DerivedCoordVar_WRFTime::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
VAssert(min.size() == 0);
VAssert(max.size() == 0);
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor: %d", fd);
return(-1);
}
size_t ts = f->GetTS();
*region = _times[ts];
return(0);
}
bool DerivedCoordVar_WRFTime::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
return(ts < _times.size());
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVar_TimeInSeconds
//
//////////////////////////////////////////////////////////////////////////////
DerivedCoordVar_TimeInSeconds::DerivedCoordVar_TimeInSeconds(
string derivedVarName, DC *dc,
string nativeTimeVar, string dimName
) : DerivedCoordVar(derivedVarName) {
_dc = dc;
_times.clear();
_nativeTimeVar = nativeTimeVar;
string units = "seconds";
int axis = 3;
_coordVarInfo = DC::CoordVar(
_derivedVarName, units, DC::XType::FLOAT,
vector <bool> (), axis, false,
vector <string> (), dimName
);
}
int DerivedCoordVar_TimeInSeconds::Initialize() {
// Use UDUnits for unit conversion
//
UDUnits udunits;
int rc = udunits.Initialize();
if (rc<0) {
SetErrMsg(
"Failed to initialize udunits2 library : %s",
udunits.GetErrMsg().c_str()
);
return(-1);
}
DC::CoordVar cvar;
bool status = _dc->GetCoordVarInfo(_nativeTimeVar, cvar);
if (! status) {
SetErrMsg("Invalid coordinate variable %s", _nativeTimeVar.c_str());
return(-1);
}
if (! udunits.IsTimeUnit(cvar.GetUnits())) {
SetErrMsg("Invalid coordinate variable %s", _nativeTimeVar.c_str());
return(-1);
}
size_t numTS = _dc->GetNumTimeSteps(_nativeTimeVar);
// Need a single precision and double precision buffer. Single for GetVar,
// double for udunits.Convert :-(
//
float *buf = new float[numTS];
double *dbuf = new double[2*numTS];
double *dbufptr1 = dbuf;
double *dbufptr2 = dbuf + numTS;
rc = _dc->GetVar(_nativeTimeVar, -1, -1, buf);
if (rc<0) {
SetErrMsg("Can't read time variable");
return(-1);
}
for (int i=0; i<numTS; i++) {
dbufptr1[i] = (double) buf[i];
}
status = udunits.Convert(cvar.GetUnits(), "seconds", dbufptr1,dbufptr2,numTS);
if (! status) {
SetErrMsg("Invalid coordinate variable %s", _nativeTimeVar.c_str());
return(-1);
}
_times.clear();
for (int i=0; i<numTS; i++) {
_times.push_back(dbufptr2[i]);
}
delete [] buf;
delete [] dbuf;
return(0);
}
bool DerivedCoordVar_TimeInSeconds::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVar_TimeInSeconds::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVar_TimeInSeconds::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
return(0);
}
int DerivedCoordVar_TimeInSeconds::OpenVariableRead(
size_t ts, int level, int lod
) {
ts = ts < _times.size() ? ts : _times.size() - 1;
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, level, lod
);
return(_fileTable.AddEntry(f));
}
int DerivedCoordVar_TimeInSeconds::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
_fileTable.RemoveEntry(fd);
delete f;
return(0);
}
int DerivedCoordVar_TimeInSeconds::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
VAssert(min.size() == 0);
VAssert(max.size() == 0);
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor: %d", fd);
return(-1);
}
size_t ts = f->GetTS();
*region = _times[ts];
return(0);
}
bool DerivedCoordVar_TimeInSeconds::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
return(ts < _times.size());
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVar_Staggered
//
//////////////////////////////////////////////////////////////////////////////
DerivedCoordVar_Staggered::DerivedCoordVar_Staggered(
string derivedVarName, string stagDimName,
DC *dc, string inName, string dimName
) : DerivedCoordVar(derivedVarName) {
_stagDimName = stagDimName;
_inName = inName;
_dimName = dimName;
_dc = dc;
}
int DerivedCoordVar_Staggered::Initialize() {
bool ok = _dc->GetCoordVarInfo(_inName, _coordVarInfo);
if (! ok) return(-1);
vector <string> dimNames = _coordVarInfo.GetDimNames();
_stagDim = -1;
for (int i=0; i<dimNames.size(); i++) {
if (dimNames[i] == _dimName) {
_stagDim = i;
dimNames[i] = _stagDimName;
break;
}
}
if (_stagDim < 0) {
SetErrMsg("Dimension %s not found", _dimName.c_str());
return(-1);
}
// Change the name of the staggered dimension
//
_coordVarInfo.SetDimNames(dimNames);
return(0);
}
bool DerivedCoordVar_Staggered::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVar_Staggered::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVar_Staggered::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
vector <size_t> dummy;
int rc = _dc->GetDimLensAtLevel(_inName, level, dims_at_level, dummy);
if (rc<0) return(-1);
dims_at_level[_stagDim] += 1;
bs_at_level = vector <size_t> (dims_at_level.size(), 1);
return(0);
}
int DerivedCoordVar_Staggered::OpenVariableRead(
size_t ts, int level, int lod
) {
int fd = _dc->OpenVariableRead(ts, _inName, level, lod);
if (fd<0) return(fd);
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, level, lod, fd
);
return(_fileTable.AddEntry(f));
}
int DerivedCoordVar_Staggered::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
int rc = _dc->CloseVariable(f->GetAux());
_fileTable.RemoveEntry(fd);
delete f;
return(rc);
}
int DerivedCoordVar_Staggered::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
vector <size_t> dims, dummy;
int rc = GetDimLensAtLevel(f->GetLevel(), dims, dummy);
if (rc<0) return(-1);
vector <size_t> inMin = min;
vector <size_t> inMax = max;
// adjust coords for native data so that we have what we
// need for interpolation or extrapolation.
//
// Adjust min max boundaries to handle 4 case (below) where X's
// are samples on the destination grid (staggered) and O's are samples
// on the source grid (unstaggered) and the numbers represent
// the address of the samples in their respective arrays
//
// X O X O X O X
// 0 0 1 1 2 2 3
//
// O X O X O X
// 0 1 1 2 2 3
//
// X O X O X O
// 0 0 1 1 2 2
//
// O X O X O
// 0 1 1 2 2
// Adjust input min so we can interpolate interior.
//
if (min[_stagDim] > 0) {
inMin[_stagDim] -= 1;
}
// input dimensions are one less then output
//
if (max[_stagDim] >= (dims[_stagDim]-1)) {
inMax[_stagDim] -= 1;
}
// Adjust min and max for edge cases
//
if (max[_stagDim] == 0 && (dims[_stagDim]-1) > 1) {
inMax[_stagDim] += 1;
}
if (min[_stagDim] == dims[_stagDim]-1 && min[_stagDim] > 0) {
inMin[_stagDim] -= 1;
}
vector <size_t> inDims, outDims;
for (size_t i=0; i<min.size(); i++) {
inDims.push_back(inMax[i]-inMin[i]+1);
outDims.push_back(max[i]-min[i]+1);
}
size_t sz = std::max(vproduct(outDims), vproduct(inDims));
float *buf = new float[sz];
// Read unstaggered data
//
rc = _dc->ReadRegion(f->GetAux(), inMin, inMax, buf);
if (rc<0) return(-1);
resampleToStaggered(buf, inMin, inMax, region, min, max, _stagDim);
delete [] buf;
return(0);
}
bool DerivedCoordVar_Staggered::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
return(_dc->VariableExists(ts, _inName, reflevel, lod));
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVar_UnStaggered
//
//////////////////////////////////////////////////////////////////////////////
DerivedCoordVar_UnStaggered::DerivedCoordVar_UnStaggered(
string derivedVarName, string unstagDimName,
DC *dc, string inName, string dimName
) : DerivedCoordVar(derivedVarName) {
_unstagDimName = unstagDimName;
_inName = inName;
_dimName = dimName;
_dc = dc;
}
int DerivedCoordVar_UnStaggered::Initialize() {
bool ok = _dc->GetCoordVarInfo(_inName, _coordVarInfo);
if (! ok) return(-1);
vector <string> dimNames = _coordVarInfo.GetDimNames();
_stagDim = -1;
for (int i=0; i<dimNames.size(); i++) {
if (dimNames[i] == _dimName) {
_stagDim = i;
dimNames[i] = _unstagDimName;
break;
}
}
if (_stagDim < 0) {
SetErrMsg("Dimension %s not found", _dimName.c_str());
return(-1);
}
// Change the name of the staggered dimension
//
_coordVarInfo.SetDimNames(dimNames);
return(0);
}
bool DerivedCoordVar_UnStaggered::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVar_UnStaggered::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVar_UnStaggered::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
int rc = _dc->GetDimLensAtLevel(_inName, level, dims_at_level, bs_at_level);
if (rc<0) return(-1);
dims_at_level[_stagDim] -= 1;
bs_at_level = vector <size_t> (dims_at_level.size(), 1);
return(0);
}
int DerivedCoordVar_UnStaggered::OpenVariableRead(
size_t ts, int level, int lod
) {
int fd = _dc->OpenVariableRead(ts, _inName, level, lod);
if (fd<0) return(fd);
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, level, lod, fd
);
return(_fileTable.AddEntry(f));
}
int DerivedCoordVar_UnStaggered::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
int rc = _dc->CloseVariable(f->GetAux());
_fileTable.RemoveEntry(fd);
delete f;
return(rc);
}
int DerivedCoordVar_UnStaggered::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
vector <size_t> dims, dummy;
int rc = GetDimLensAtLevel(f->GetLevel(), dims, dummy);
if (rc<0) return(-1);
vector <size_t> inMin = min;
vector <size_t> inMax = max;
// adjust coords for native data so that we have what we
// need for interpolation .
//
inMax[_stagDim] += 1;
vector <size_t> inDims, outDims;
for (size_t i=0; i<min.size(); i++) {
inDims.push_back(inMax[i]-inMin[i]+1);
outDims.push_back(max[i]-min[i]+1);
}
size_t sz = std::max(vproduct(outDims), vproduct(inDims));
float *buf = new float[sz];
// Read staggered data
//
rc = _dc->ReadRegion(f->GetAux(), inMin, inMax, buf);
if (rc<0) return(-1);
resampleToUnStaggered(buf, inMin, inMax, region, min, max, _stagDim);
delete [] buf;
return(0);
}
bool DerivedCoordVar_UnStaggered::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
return(_dc->VariableExists(ts, _inName, reflevel, lod));
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCFVertCoordVar
//
//////////////////////////////////////////////////////////////////////////////
bool DerivedCFVertCoordVar::ParseFormula(
string formula_terms, map <string, string> &parsed_terms
) {
parsed_terms.clear();
// Remove ":" to ease parsing. It's superflous
//
replace(formula_terms.begin(), formula_terms.end(), ':', ' ');
string buf; // Have a buffer string
stringstream ss(formula_terms); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf) {
tokens.push_back(buf);
}
if (tokens.size() % 2) return(false);
for (int i=0; i<tokens.size(); i+=2) {
parsed_terms[tokens[i]] = tokens[i+1];
if (parsed_terms[tokens[i]].empty()) return(false);
}
return(true);
}
bool DerivedCFVertCoordVar::ValidFormula(
const vector <string> &required_terms, string formula
) {
map <string, string> formulaMap;
if (! ParseFormula(formula, formulaMap)) {
return(false);
}
for (int i=0; i<required_terms.size(); i++) {
map <string, string>::const_iterator itr;
itr = formulaMap.find(required_terms[i]);
if (itr == formulaMap.end()) return(false);
}
return(true);
}
//////////////////////////////////////////////////////////////////////////
//
// DerivedCFVertCoordVarFactory Class
//
/////////////////////////////////////////////////////////////////////////
DerivedCFVertCoordVar *DerivedCFVertCoordVarFactory::CreateInstance(
string standard_name, DC *dc, string mesh, string formula
) {
DerivedCFVertCoordVar * instance = NULL;
// find standard_name in the registry and call factory method.
//
auto it = _factoryFunctionRegistry.find(standard_name);
if(it != _factoryFunctionRegistry.end()) {
instance = it->second(dc, mesh, formula);
}
return instance;
}
vector <string> DerivedCFVertCoordVarFactory::GetFactoryNames() const {
vector <string> names;
map<string, function<DerivedCFVertCoordVar * (DC *, string , string )>>::const_iterator itr;
for (const auto &itr : _factoryFunctionRegistry) {
names.push_back(itr.first);
}
return(names);
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVarStandardWRF_Terrain
//
//////////////////////////////////////////////////////////////////////////////
static DerivedCFVertCoordVarFactoryRegistrar<DerivedCoordVarStandardWRF_Terrain> registrar_wrf_terrain("wrf_terrain");
DerivedCoordVarStandardWRF_Terrain::DerivedCoordVarStandardWRF_Terrain(
DC *dc, string mesh, string formula
) : DerivedCFVertCoordVar(
"", dc, mesh, formula
) {
_PHVar.clear();
_PHBVar.clear();
_grav = 9.80665;
}
int DerivedCoordVarStandardWRF_Terrain::Initialize() {
map <string, string> formulaMap;
if (! ParseFormula(_formula, formulaMap)) {
SetErrMsg("Invalid conversion formula \"%s\"", _formula.c_str());
return(-1);
}
map <string, string>::const_iterator itr;
itr = formulaMap.find("PH");
if (itr != formulaMap.end()) {
_PHVar = itr->second;
}
itr = formulaMap.find("PHB");
if (itr != formulaMap.end()) {
_PHBVar = itr->second;
}
if (_PHVar.empty() || _PHBVar.empty()) {
SetErrMsg("Invalid conversion formula \"%s\"", _formula.c_str());
return(-1);
}
DC::DataVar dvarInfo;
bool status = _dc->GetDataVarInfo(_PHVar, dvarInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", _PHVar.c_str());
return(-1);
}
string timeCoordVar = dvarInfo.GetTimeCoordVar();
string timeDimName;
if (! timeCoordVar.empty()) {
DC::CoordVar cvarInfo;
bool status = _dc->GetCoordVarInfo(timeCoordVar, cvarInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", timeCoordVar.c_str());
return(-1);
}
timeDimName = cvarInfo.GetTimeDimName();
}
DC::Mesh m;
status = _dc->GetMesh(_mesh, m);
if (! status) {
SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str());
return(-1);
}
// Elevation variable
//
vector <string> dimnames = m.GetDimNames();
VAssert(dimnames.size() == 3);
if (
dimnames[0] == "west_east" &&
dimnames[1] == "south_north" &&
dimnames[2] == "bottom_top"
) {
_derivedVarName = "Elevation";
}
else if (
dimnames[0] == "west_east_stag" &&
dimnames[1] == "south_north" &&
dimnames[2] == "bottom_top"
) {
_derivedVarName = "ElevationU";
}
else if (
dimnames[0] == "west_east" &&
dimnames[1] == "south_north_stag" &&
dimnames[2] == "bottom_top"
) {
_derivedVarName = "ElevationV";
}
else if (
dimnames[0] == "west_east" &&
dimnames[1] == "south_north" &&
dimnames[2] == "bottom_top_stag"
) {
_derivedVarName = "ElevationW";
}
else {
SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str());
return(-1);
}
_coordVarInfo = DC::CoordVar(
_derivedVarName, "m", DC::XType::FLOAT, dvarInfo.GetWName(),
dvarInfo.GetCRatios(), vector <bool> (3, false),
dimnames, timeDimName, 2, false
);
return(0);
}
bool DerivedCoordVarStandardWRF_Terrain::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVarStandardWRF_Terrain::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
int DerivedCoordVarStandardWRF_Terrain::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
vector <size_t> dims, bs;
int rc = _dc->GetDimLensAtLevel(_PHVar, -1, dims, bs);
if (rc<0) return(-1);
if (_derivedVarName == "Elevation") {
dims[2]--;
}
else if (_derivedVarName == "ElevationU") {
dims[0]++;
dims[2]--;
}
else if (_derivedVarName == "ElevationV") {
dims[1]++;
dims[2]--;
}
else if (_derivedVarName == "ElevationW") {
}
else {
SetErrMsg("Invalid variable name: %s", _derivedVarName.c_str());
return(-1);
}
int nlevels = _dc->GetNumRefLevels(_PHVar);
if (level < 0) level = nlevels + level;
WASP::InqDimsAtLevel(
_coordVarInfo.GetWName(), level, dims, bs, dims_at_level, bs_at_level
);
// No blocking
//
// bs_at_level = vector <size_t> (dims_at_level.size(), 1);
return(0);
}
int DerivedCoordVarStandardWRF_Terrain::OpenVariableRead(
size_t ts, int level, int lod
) {
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, level, lod
);
return(_fileTable.AddEntry(f));
}
int DerivedCoordVarStandardWRF_Terrain::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
_fileTable.RemoveEntry(fd);
delete f;
return(0);
}
int DerivedCoordVarStandardWRF_Terrain::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
string varname = f->GetVarname();
// Dimensions of "W" grid: PH and PHB variables are sampled on the
// same grid as the W component of velocity
//
vector <size_t> wDims, dummy;
int rc = _dc->GetDimLensAtLevel(_PHVar, f->GetLevel(), wDims, dummy);
if (rc<0) return(-1);
vector <size_t> myDims;
rc = DerivedCoordVarStandardWRF_Terrain::GetDimLensAtLevel(
f->GetLevel(), myDims, dummy
);
if (rc<0) return(-1);
// coordinates of "W" grid.
//
vector <size_t> wMin = min;
vector <size_t> wMax = max;
// coordinates of base (Elevation) grid.
//
if (varname == "Elevation") {
// In general myDims[2] != wDims[2]. However, for multiresolution
// data the two can be equal
//
if (myDims[2] != wDims[2]) {
wMax[2] += 1;
}
}
else if (varname == "ElevationU") {
if (myDims[2] != wDims[2]) {
wMax[2] += 1;
}
if (min[0] > 0) {
wMin[0] -= 1;
}
if (max[0] >= (wDims[0]-1)) {
wMax[0] -= 1;
}
}
else if (varname == "ElevationV") {
if (myDims[2] != wDims[2]) {
wMax[2] += 1;
}
if (min[1] > 0) {
wMin[1] -= 1;
}
if (max[1] >= (wDims[1]-1)) {
wMax[1] -= 1;
}
}
// Base grid dimensions
//
vector <size_t> bMin = wMin;
vector <size_t> bMax = wMax;
if (myDims[2] != wDims[2]) {
bMax[2] -= 1;
}
size_t nElements = std::max(numElements(wMin, wMax), numElements(min, max));
float *buf1 = new float[nElements];
rc = _getVar(
_dc, f->GetTS(), _PHVar, f->GetLevel(), f->GetLOD(),
wMin, wMax, buf1
);
if (rc<0) {
delete [] buf1;
return(rc);
}
float *buf2 = new float[nElements];
rc = _getVar(
_dc, f->GetTS(), _PHBVar, f->GetLevel(), f->GetLOD(),
wMin, wMax, buf2
);
if (rc<0) {
delete [] buf1;
delete [] buf2;
return(rc);
}
float *dst = region;
if (varname != "ElevationW") {
dst = buf1;
}
// Compute elevation on the W grid
//
for (size_t i=0; i<nElements; i++) {
dst[i] = (buf1[i] + buf2[i]) / _grav;
}
// Elevation is correct for W grid. If we want Elevation, ElevationU, or
// Elevation V grid we need to interpolate
//
if (varname == "Elevation") {
// Resample stagged W grid to base grid
//
resampleToUnStaggered(
buf1, wMin, wMax, region, min, max, 2
);
}
else if (varname == "ElevationU") {
// Resample stagged W grid to base grid
//
resampleToUnStaggered(
buf1, wMin, wMax, buf2, bMin, bMax, 2
);
resampleToStaggered(
buf2, bMin, bMax, region, min, max, 0
);
}
else if (varname == "ElevationV") {
// Resample stagged W grid to base grid
//
resampleToUnStaggered(
buf1, wMin, wMax, buf2, bMin, bMax, 2
);
resampleToStaggered(
buf2, bMin, bMax, region, min, max, 1
);
}
delete [] buf1;
delete [] buf2;
return(0);
}
bool DerivedCoordVarStandardWRF_Terrain::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
return(
_dc->VariableExists(ts, _PHVar, reflevel, lod) &&
_dc->VariableExists(ts, _PHBVar, reflevel, lod)
);
}
bool DerivedCoordVarStandardWRF_Terrain::ValidFormula(string formula) {
return(DerivedCFVertCoordVar::ValidFormula(
vector <string> {"PH", "PHB"}, formula
));
}
//////////////////////////////////////////////////////////////////////////////
//
// DerivedCoordVarStandardOceanSCoordinate
//
//////////////////////////////////////////////////////////////////////////////
//
// Register class with object factory!!!
//
static DerivedCFVertCoordVarFactoryRegistrar<DerivedCoordVarStandardOceanSCoordinate> registrar_ocean_s_coordinate_g1("ocean_s_coordinate_g1");
static DerivedCFVertCoordVarFactoryRegistrar<DerivedCoordVarStandardOceanSCoordinate> registrar_ocean_s_coordinate_g2("ocean_s_coordinate_g2");
DerivedCoordVarStandardOceanSCoordinate::DerivedCoordVarStandardOceanSCoordinate(
DC *dc, string mesh, string formula
) : DerivedCFVertCoordVar(
"", dc, mesh, formula
) {
_standard_name = "ocean_s_coordinate_g1";
_sVar.clear();
_CVar.clear();
_etaVar.clear();
_depthVar.clear();
_depth_cVar.clear();
_CVarMV = std::numeric_limits<double>::infinity();
_etaVarMV = std::numeric_limits<double>::infinity();
_depthVarMV = std::numeric_limits<double>::infinity();
_destaggerEtaXDim = false;
_destaggerEtaYDim = false;
_destaggerDepthXDim = false;
_destaggerDepthYDim = false;
}
int DerivedCoordVarStandardOceanSCoordinate::initialize_missing_values() {
DC::DataVar dataInfo;
bool status = _dc->GetDataVarInfo(_CVar, dataInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", _CVar.c_str());
return(-1);
}
if (dataInfo.GetHasMissing()) _CVarMV = dataInfo.GetMissingValue();
status = _dc->GetDataVarInfo(_etaVar, dataInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", _etaVar.c_str());
return(-1);
}
if (dataInfo.GetHasMissing()) _etaVarMV = dataInfo.GetMissingValue();
status = _dc->GetDataVarInfo(_depthVar, dataInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", _depthVar.c_str());
return(-1);
}
if (dataInfo.GetHasMissing()) _depthVarMV = dataInfo.GetMissingValue();
return(0);
}
int DerivedCoordVarStandardOceanSCoordinate::initialize_stagger_flags() {
vector <size_t> derivedDims;
bool status = _dc->GetMeshDimLens(_mesh, derivedDims);
if (! status) {
SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str());
return(-1);
}
vector <size_t> nativeDims;
int rc = _dc->GetDimLens(_etaVar, nativeDims);
if (rc<0) return(-1);
if (nativeDims[0] == derivedDims[0]-1) _destaggerEtaXDim = true;
if (nativeDims[1] == derivedDims[1]-1) _destaggerEtaYDim = true;
rc = _dc->GetDimLens(_depthVar, nativeDims);
if (rc<0) return(-1);
if (nativeDims[0] == derivedDims[0]-1) _destaggerDepthXDim = true;
if (nativeDims[1] == derivedDims[1]-1) _destaggerDepthYDim = true;
return(0);
}
int DerivedCoordVarStandardOceanSCoordinate::Initialize() {
map <string, string> formulaMap;
if (! ParseFormula(_formula, formulaMap)) {
SetErrMsg("Invalid conversion formula \"%s\"", _formula.c_str());
return(-1);
}
map <string, string>::const_iterator itr;
VAssert((itr = formulaMap.find("s")) != formulaMap.end());
_sVar = itr->second;
VAssert((itr = formulaMap.find("C")) != formulaMap.end());
_CVar = itr->second;
VAssert((itr = formulaMap.find("eta")) != formulaMap.end());
_etaVar = itr->second;
VAssert((itr = formulaMap.find("depth")) != formulaMap.end());
_depthVar = itr->second;
VAssert((itr = formulaMap.find("depth_c")) != formulaMap.end());
_depth_cVar = itr->second;
if (initialize_missing_values() < 0) return(-1);
if (initialize_stagger_flags() < 0) return(-1);
// Figure out if this is a Ocean s-coordinate, generic form 1, or
// Ocean s-coordinate, generic form 2
//
DC::CoordVar sInfo;
bool status = _dc->GetCoordVarInfo(_sVar, sInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", _sVar.c_str());
return(-1);
}
DC::Attribute attr_name;
if (! sInfo.GetAttribute("standard_name", attr_name)) {
// Default to generic form 1
//
_standard_name = "ocean_s_coordinate_g1";
}
else {
attr_name.GetValues(_standard_name);
}
// Use the eta variable to set up metadata for the derived variable
//
DC::DataVar etaInfo;
status = _dc->GetDataVarInfo(_etaVar, etaInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", _etaVar.c_str());
return(-1);
}
string timeCoordVar = etaInfo.GetTimeCoordVar();
string timeDimName;
if (! timeCoordVar.empty()) {
DC::CoordVar cvarInfo;
bool status = _dc->GetCoordVarInfo(timeCoordVar, cvarInfo);
if (! status) {
SetErrMsg("Invalid variable \"%s\"", timeCoordVar.c_str());
return(-1);
}
timeDimName = cvarInfo.GetTimeDimName();
}
_derivedVarName = "Z_" + _sVar;
vector <string> dimnames;
status = _dc->GetMeshDimNames(_mesh, dimnames);
if (! status) {
SetErrMsg("Invalid mesh \"%s\"", _mesh.c_str());
return(-1);
}
VAssert(dimnames.size() == 3);
// We're deriving a 3D varible from 1D and 2D varibles. We arbitarily
// use one of the 2D variables to configure metadata such as the
// available compression ratios
//
_coordVarInfo = DC::CoordVar(
_derivedVarName, "m", DC::XType::FLOAT, etaInfo.GetWName(),
etaInfo.GetCRatios(), vector <bool> (3, false),
dimnames, timeDimName, 2, false
);
return(0);
}
bool DerivedCoordVarStandardOceanSCoordinate::GetBaseVarInfo(
DC::BaseVar &var
) const {
var = _coordVarInfo;
return(true);
}
bool DerivedCoordVarStandardOceanSCoordinate::GetCoordVarInfo(
DC::CoordVar &cvar
) const {
cvar = _coordVarInfo;
return(true);
}
vector <string> DerivedCoordVarStandardOceanSCoordinate::GetInputs() const {
map <string, string> formulaMap;
bool ok = ParseFormula(_formula, formulaMap);
VAssert(ok);
vector <string> inputs;
for (auto it = formulaMap.begin(); it != formulaMap.end(); ++it) {
inputs.push_back(it->second);
}
return(inputs);
}
int DerivedCoordVarStandardOceanSCoordinate::GetDimLensAtLevel(
int level, std::vector <size_t> &dims_at_level,
std::vector <size_t> &bs_at_level
) const {
dims_at_level.clear();
bs_at_level.clear();
vector <size_t> dims2d, bs2d;
int rc = _dc->GetDimLensAtLevel(_etaVar, -1, dims2d, bs2d);
if (rc<0) return(-1);
vector <size_t> dims1d, bs1d;
rc = _dc->GetDimLensAtLevel(_sVar, -1, dims1d, bs1d);
if (rc<0) return(-1);
vector <size_t> dims = {dims2d[0], dims2d[1], dims1d[0]};
vector <size_t> bs = {bs2d[0], bs2d[1], bs1d[0]};
int nlevels = _dc->GetNumRefLevels(_etaVar);
if (level < 0) level = nlevels + level;
WASP::InqDimsAtLevel(
_coordVarInfo.GetWName(), level, dims, bs, dims_at_level, bs_at_level
);
return(0);
}
int DerivedCoordVarStandardOceanSCoordinate::OpenVariableRead(
size_t ts, int level, int lod
) {
DC::FileTable::FileObject *f = new DC::FileTable::FileObject(
ts, _derivedVarName, level, lod
);
return(_fileTable.AddEntry(f));
}
int DerivedCoordVarStandardOceanSCoordinate::CloseVariable(int fd) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
if (! f) {
SetErrMsg("Invalid file descriptor : %d", fd);
return(-1);
}
_fileTable.RemoveEntry(fd);
delete f;
return(0);
}
int DerivedCoordVarStandardOceanSCoordinate::ReadRegion(
int fd,
const vector <size_t> &min, const vector <size_t> &max, float *region
) {
DC::FileTable::FileObject *f = _fileTable.GetEntry(fd);
string varname = f->GetVarname();
vector <size_t> dims, dummy;
int rc = GetDimLensAtLevel(f->GetLevel(), dims, dummy);
if (rc<0) return(-1);
vector <float> s(dims[2]);
vector <size_t> myMin = {min[2]};
vector <size_t> myMax = {max[2]};
rc = _getVar(
_dc, f->GetTS(), _sVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, s.data()
);
if (rc<0) return(rc);
vector <float> C(dims[2]);
myMin = {min[2]};
myMax = {max[2]};
rc = _getVar(
_dc, f->GetTS(), _CVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, C.data()
);
if (rc<0) return(rc);
vector <float> eta(dims[0]*dims[1]);
myMin = {min[0], min[1]};
myMax = {max[0], max[1]};
if (_destaggerEtaXDim) {
rc = _getVarDestagger(
_dc, f->GetTS(), _etaVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, eta.data(), 0
);
}
else if (_destaggerEtaYDim) {
rc = _getVarDestagger(
_dc, f->GetTS(), _etaVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, eta.data(), 1
);
}
else {
rc = _getVar(
_dc, f->GetTS(), _etaVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, eta.data()
);
}
if (rc<0) return(rc);
vector <float> depth(dims[0]*dims[1]);
myMin = {min[0], min[1]};
myMax = {max[0], max[1]};
if (_destaggerDepthXDim) {
rc = _getVarDestagger(
_dc, f->GetTS(), _depthVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, depth.data(), 0
);
}
else if (_destaggerDepthYDim) {
rc = _getVarDestagger(
_dc, f->GetTS(), _depthVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, depth.data(), 1
);
}
else {
rc = _getVar(
_dc, f->GetTS(), _depthVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, depth.data()
);
}
float depth_c;
myMin = {};
myMax = {};
rc = _getVar(
_dc, f->GetTS(), _depth_cVar, f->GetLevel(), f->GetLOD(),
myMin, myMax, &depth_c
);
if (_standard_name == "ocean_s_coordinate_g1") {
compute_g1(
min, max, s.data(), C.data(), eta.data(), depth.data(),
depth_c, region
);
}
else {
compute_g2(
min, max, s.data(), C.data(), eta.data(), depth.data(),
depth_c, region
);
}
return(0);
}
bool DerivedCoordVarStandardOceanSCoordinate::VariableExists(
size_t ts,
int reflevel,
int lod
) const {
return(
_dc->VariableExists(ts, _sVar, reflevel, lod) &&
_dc->VariableExists(ts, _CVar, reflevel, lod) &&
_dc->VariableExists(ts, _etaVar, reflevel, lod) &&
_dc->VariableExists(ts, _depthVar, reflevel, lod) &&
_dc->VariableExists(ts, _depth_cVar, reflevel, lod)
);
}
bool DerivedCoordVarStandardOceanSCoordinate::ValidFormula(string formula) {
return(DerivedCFVertCoordVar::ValidFormula(
vector <string> {"s", "C", "eta", "depth", "depth_c"}, formula
));
}
void DerivedCoordVarStandardOceanSCoordinate::compute_g1(
const vector <size_t> &min, const vector <size_t> &max,
const float *s, const float *C, const float *eta, const float *depth,
float depth_c, float *region
) const {
vector <size_t> rDims;
for (int i=0; i<3; i++) {
rDims.push_back(max[i]-min[i]+1);
}
for (size_t k=0; k<max[2]-min[2]+1; k++) {
for (size_t j=0; j<max[1]-min[1]+1; j++) {
for (size_t i=0; i<max[0]-min[0]+1; i++) {
if (depth[j*rDims[0]] == 0.0) {
region[k*rDims[0]*rDims[1] + j*rDims[0] + i] = 0.0;
continue;
}
// We are deriving coordinate values from data values, so missing
// values may be present
//
if (
C[k] == _CVarMV ||
eta[j*rDims[0]+i] == _etaVarMV ||
depth[j*rDims[0]+i] == _depthVarMV
) {
region[k*rDims[0]*rDims[1] + j*rDims[0] + i] = 0.0;
continue;
}
float tmp = depth_c * s[k] + (depth[j*rDims[0]+i] - depth_c) * C[k];
region[k*rDims[0]*rDims[1] + j*rDims[0] + i] =
tmp + eta[j*rDims[0]+i] * (1 + tmp / depth[j*rDims[0]+i]);
}
}
}
}
void DerivedCoordVarStandardOceanSCoordinate::compute_g2(
const vector <size_t> &min, const vector <size_t> &max,
const float *s, const float *C, const float *eta, const float *depth,
float depth_c, float *region
) const {
vector <size_t> rDims;
for (int i=0; i<3; i++) {
rDims.push_back(max[i]-min[i]+1);
}
for (size_t k=0; k<max[2]-min[2]+1; k++) {
for (size_t j=0; j<max[1]-min[1]+1; j++) {
for (size_t i=0; i<max[0]-min[0]+1; i++) {
if ((depth_c + depth[j*rDims[0]]) == 0.0) {
region[k*rDims[0]*rDims[1] + j*rDims[0] + i] = 0.0;
continue;
}
// We are deriving coordinate values from data values, so missing
// values may be present
//
if (
C[k] == _CVarMV ||
eta[j*rDims[0]+i] == _etaVarMV ||
depth[j*rDims[0]+i] == _depthVarMV
) {
region[k*rDims[0]*rDims[1] + j*rDims[0] + i] = 0.0;
continue;
}
float tmp = (depth_c*s[k] + depth[j*rDims[0]+i] * C[k]) /
(depth_c + depth[j*rDims[0]+i]);
region[k*rDims[0]*rDims[1] + j*rDims[0] + i] =
eta[j*rDims[0]+i] +
(eta[j*rDims[0]+i] + depth[j*rDims[0]+i]) * tmp;
}
}
}
}
|
#include "../../common/hex.hpp"
#include "../../common/term.hpp"
#include "../mnemonic.hpp"
#include <boost/algorithm/string.hpp>
using namespace prologcoin::common;
using namespace prologcoin::ec;
static void header( const std::string &str )
{
std::cout << "\n";
std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n";
std::cout << "\n";
}
// Test vectors taken from BIP39
static void test_english()
{
header("test_english");
struct expect_t {
const char *hex_input;
const char *words;
const char *seed;
const char *xprv;
} EXPECTED[] = {
{
"00000000000000000000000000000000",
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
"c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04",
"xprv9s21ZrQH143K3h3fDYiay8mocZ3afhfULfb5GX8kCBdno77K4HiA15Tg23wpbeF1pLfs1c5SPmYHrEpTuuRhxMwvKDwqdKiGJS9XFKzUsAF"
},
{
"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
"legal winner thank year wave sausage worth useful legal winner thank yellow",
"2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607",
"xprv9s21ZrQH143K2gA81bYFHqU68xz1cX2APaSq5tt6MFSLeXnCKV1RVUJt9FWNTbrrryem4ZckN8k4Ls1H6nwdvDTvnV7zEXs2HgPezuVccsq"
},
{
"80808080808080808080808080808080",
"letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
"d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8",
"xprv9s21ZrQH143K2shfP28KM3nr5Ap1SXjz8gc2rAqqMEynmjt6o1qboCDpxckqXavCwdnYds6yBHZGKHv7ef2eTXy461PXUjBFQg6PrwY4Gzq"
},
{
"ffffffffffffffffffffffffffffffff",
"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
"ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069",
"xprv9s21ZrQH143K2V4oox4M8Zmhi2Fjx5XK4Lf7GKRvPSgydU3mjZuKGCTg7UPiBUD7ydVPvSLtg9hjp7MQTYsW67rZHAXeccqYqrsx8LcXnyd"
},
{
"000000000000000000000000000000000000000000000000",
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent",
"035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa",
"xprv9s21ZrQH143K3mEDrypcZ2usWqFgzKB6jBBx9B6GfC7fu26X6hPRzVjzkqkPvDqp6g5eypdk6cyhGnBngbjeHTe4LsuLG1cCmKJka5SMkmU"
},
{
"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
"legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will",
"f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd",
"xprv9s21ZrQH143K3Lv9MZLj16np5GzLe7tDKQfVusBni7toqJGcnKRtHSxUwbKUyUWiwpK55g1DUSsw76TF1T93VT4gz4wt5RM23pkaQLnvBh7"
},
{
"808080808080808080808080808080808080808080808080",
"letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always",
"107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65",
"xprv9s21ZrQH143K3VPCbxbUtpkh9pRG371UCLDz3BjceqP1jz7XZsQ5EnNkYAEkfeZp62cDNj13ZTEVG1TEro9sZ9grfRmcYWLBhCocViKEJae"
},
{
"ffffffffffffffffffffffffffffffffffffffffffffffff",
"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when",
"0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528",
"xprv9s21ZrQH143K36Ao5jHRVhFGDbLP6FCx8BEEmpru77ef3bmA928BxsqvVM27WnvvyfWywiFN8K6yToqMaGYfzS6Db1EHAXT5TuyCLBXUfdm"
},
{
"0000000000000000000000000000000000000000000000000000000000000000",
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
"bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8",
"xprv9s21ZrQH143K32qBagUJAMU2LsHg3ka7jqMcV98Y7gVeVyNStwYS3U7yVVoDZ4btbRNf4h6ibWpY22iRmXq35qgLs79f312g2kj5539ebPM"
},
{
"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
"legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title",
"bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87",
"xprv9s21ZrQH143K3Y1sd2XVu9wtqxJRvybCfAetjUrMMco6r3v9qZTBeXiBZkS8JxWbcGJZyio8TrZtm6pkbzG8SYt1sxwNLh3Wx7to5pgiVFU"
},
{
"8080808080808080808080808080808080808080808080808080808080808080",
"letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless",
"c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f",
"xprv9s21ZrQH143K3CSnQNYC3MqAAqHwxeTLhDbhF43A4ss4ciWNmCY9zQGvAKUSqVUf2vPHBTSE1rB2pg4avopqSiLVzXEU8KziNnVPauTqLRo"
},
{
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote",
"dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad",
"xprv9s21ZrQH143K2WFF16X85T2QCpndrGwx6GueB72Zf3AHwHJaknRXNF37ZmDrtHrrLSHvbuRejXcnYxoZKvRquTPyp2JiNG3XcjQyzSEgqCB"
},
{
"9e885d952ad362caeb4efe34a8e91bd2",
"ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic",
"274ddc525802f7c828d8ef7ddbcdc5304e87ac3535913611fbbfa986d0c9e5476c91689f9c8a54fd55bd38606aa6a8595ad213d4c9c9f9aca3fb217069a41028",
"xprv9s21ZrQH143K2oZ9stBYpoaZ2ktHj7jLz7iMqpgg1En8kKFTXJHsjxry1JbKH19YrDTicVwKPehFKTbmaxgVEc5TpHdS1aYhB2s9aFJBeJH"
},
{
"6610b25967cdcca9d59875f5cb50b0ea75433311869e930b",
"gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog",
"628c3827a8823298ee685db84f55caa34b5cc195a778e52d45f59bcf75aba68e4d7590e101dc414bc1bbd5737666fbbef35d1f1903953b66624f910feef245ac",
"xprv9s21ZrQH143K3uT8eQowUjsxrmsA9YUuQQK1RLqFufzybxD6DH6gPY7NjJ5G3EPHjsWDrs9iivSbmvjc9DQJbJGatfa9pv4MZ3wjr8qWPAK"
},
{
"68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c",
"hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length",
"64c87cde7e12ecf6704ab95bb1408bef047c22db4cc7491c4271d170a1b213d20b385bc1588d9c7b38f1b39d415665b8a9030c9ec653d75e65f847d8fc1fc440",
"xprv9s21ZrQH143K2XTAhys3pMNcGn261Fi5Ta2Pw8PwaVPhg3D8DWkzWQwjTJfskj8ofb81i9NP2cUNKxwjueJHHMQAnxtivTA75uUFqPFeWzk"
},
{
"c0ba5a8e914111210f2bd131f3d5e08d",
"scheme spot photo card baby mountain device kick cradle pact join borrow",
"ea725895aaae8d4c1cf682c1bfd2d358d52ed9f0f0591131b559e2724bb234fca05aa9c02c57407e04ee9dc3b454aa63fbff483a8b11de949624b9f1831a9612",
"xprv9s21ZrQH143K3FperxDp8vFsFycKCRcJGAFmcV7umQmcnMZaLtZRt13QJDsoS5F6oYT6BB4sS6zmTmyQAEkJKxJ7yByDNtRe5asP2jFGhT6"
},
{
"6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3",
"horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave",
"fd579828af3da1d32544ce4db5c73d53fc8acc4ddb1e3b251a31179cdb71e853c56d2fcb11aed39898ce6c34b10b5382772db8796e52837b54468aeb312cfc3d",
"xprv9s21ZrQH143K3R1SfVZZLtVbXEB9ryVxmVtVMsMwmEyEvgXN6Q84LKkLRmf4ST6QrLeBm3jQsb9gx1uo23TS7vo3vAkZGZz71uuLCcywUkt"
},
{
"9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863",
"panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside",
"72be8e052fc4919d2adf28d5306b5474b0069df35b02303de8c1729c9538dbb6fc2d731d5f832193cd9fb6aeecbc469594a70e3dd50811b5067f3b88b28c3e8d",
"xprv9s21ZrQH143K2WNnKmssvZYM96VAr47iHUQUTUyUXH3sAGNjhJANddnhw3i3y3pBbRAVk5M5qUGFr4rHbEWwXgX4qrvrceifCYQJbbFDems"
},
{
"23db8160a31d3e0dca3688ed941adbf3",
"cat swing flag economy stadium alone churn speed unique patch report train",
"deb5f45449e615feff5640f2e49f933ff51895de3b4381832b3139941c57b59205a42480c52175b6efcffaa58a2503887c1e8b363a707256bdd2b587b46541f5",
"xprv9s21ZrQH143K4G28omGMogEoYgDQuigBo8AFHAGDaJdqQ99QKMQ5J6fYTMfANTJy6xBmhvsNZ1CJzRZ64PWbnTFUn6CDV2FxoMDLXdk95DQ"
},
{
"8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0",
"light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access",
"4cbdff1ca2db800fd61cae72a57475fdc6bab03e441fd63f96dabd1f183ef5b782925f00105f318309a7e9c3ea6967c7801e46c8a58082674c860a37b93eda02",
"xprv9s21ZrQH143K3wtsvY8L2aZyxkiWULZH4vyQE5XkHTXkmx8gHo6RUEfH3Jyr6NwkJhvano7Xb2o6UqFKWHVo5scE31SGDCAUsgVhiUuUDyh"
},
{
"066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad",
"all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform",
"26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513ca2a2d67722b77e954b4b3fc11f7590449191d",
"xprv9s21ZrQH143K3rEfqSM4QZRVmiMuSWY9wugscmaCjYja3SbUD3KPEB1a7QXJoajyR2T1SiXU7rFVRXMV9XdYVSZe7JoUXdP4SRHTxsT1nzm"
},
{
"f30f8c1da665478f49b001d94c5fc452",
"vessel ladder alter error federal sibling chat ability sun glass valve picture",
"2aaa9242daafcee6aa9d7269f17d4efe271e1b9a529178d7dc139cd18747090bf9d60295d0ce74309a78852a9caadf0af48aae1c6253839624076224374bc63f",
"xprv9s21ZrQH143K2QWV9Wn8Vvs6jbqfF1YbTCdURQW9dLFKDovpKaKrqS3SEWsXCu6ZNky9PSAENg6c9AQYHcg4PjopRGGKmdD313ZHszymnps"
},
{
"c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05",
"scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump",
"7b4a10be9d98e6cba265566db7f136718e1398c71cb581e1b2f464cac1ceedf4f3e274dc270003c670ad8d02c4558b2f8e39edea2775c9e232c7cb798b069e88",
"xprv9s21ZrQH143K4aERa2bq7559eMCCEs2QmmqVjUuzfy5eAeDX4mqZffkYwpzGQRE2YEEeLVRoH4CSHxianrFaVnMN2RYaPUZJhJx8S5j6puX"
},
{
"f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f",
"void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold",
"01f5bced59dec48e362f2c45b5de68b9fd6c92c6634f44d6d40aab69056506f0e35524a518034ddc1192e1dacd32c1ed3eaa3c3b131c88ed8e7e54c49a5d0998",
"xprv9s21ZrQH143K39rnQJknpH1WEPFJrzmAqqasiDcVrNuk926oizzJDDQkdiTvNPr2FYDYzWgiMiC63YmfPAa2oPyNB23r2g7d1yiK6WpqaQS"
},
{ nullptr, nullptr, nullptr, nullptr }
};
term_env env;
mnemonic mem(env);
secp256k1_ctx ctx;
for (size_t i = 0; EXPECTED[i].hex_input != nullptr; i++) {
std::cout << "INPUT: " << EXPECTED[i].hex_input << std::endl;
uint8_t bytes[32];
assert(strlen(EXPECTED[i].hex_input) % 2 == 0);
size_t bytes_len = strlen(EXPECTED[i].hex_input) / 2;
hex::from_string(EXPECTED[i].hex_input, bytes, bytes_len);
mem.set(bytes, bytes_len);
term sentence = mem.to_sentence();
mnemonic mem2(env);
mem2.from_sentence(sentence);
term sentence2 = mem2.to_sentence();
uint64_t cost = 0;
assert(env.equal(sentence, sentence2, cost));
std::string str = env.to_string(sentence);
std::replace(str.begin(), str.end(), ',', ' ');
boost::replace_all(str, "\n", "");
boost::replace_all(str, "\r", "");
boost::replace_all(str, " ", " ");
boost::replace_all(str, "[", "");
boost::replace_all(str, "]", "");
boost::trim(str);
std::cout << "ACTUAL: " << str << std::endl;
std::cout << "EXPECT: " << EXPECTED[i].words << std::endl;
assert(str == EXPECTED[i].words);
extended_private_key key;
hd_keys hd(ctx);
mem.compute_key(hd, "TREZOR");
uint8_t seed[64];
mem.compute_seed(seed, "TREZOR");
std::string xprv = hd.master_private().to_string();
std::string seedstr = hex::to_string(seed, 64);
std::cout << "SEED: " << seedstr << std::endl;
std::cout << "KEY : " << xprv << std::endl;
assert(seedstr == EXPECTED[i].seed);
assert(xprv == EXPECTED[i].xprv);
}
}
int main(int argc, char *argv[])
{
test_english();
return 0;
}
|
#include "upstream.h"
int upstream() { return systemlib(); }
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/lite/kernels/test_util.h"
#include "tensorflow/contrib/lite/version.h"
#include "tensorflow/core/platform/logging.h"
namespace tflite {
using ::testing::FloatNear;
using ::testing::Matcher;
namespace {
template <typename T>
std::pair<float, int32_t> QuantizationParams(float f_min, float f_max) {
// These are required by many quantized operations.
CHECK_LE(f_min, 0);
CHECK_GE(f_max, 0);
T q_min = std::numeric_limits<T>::min();
T q_max = std::numeric_limits<T>::max();
float range = q_max - q_min;
float scale = (f_max - f_min) / range;
int32_t zero_point = std::min(
q_max,
std::max(q_min, static_cast<T>(std::round(q_min - f_min / scale))));
return {scale, zero_point};
}
} // namespace
std::vector<Matcher<float>> ArrayFloatNear(const std::vector<float>& values,
float max_abs_error) {
std::vector<Matcher<float>> matchers;
matchers.reserve(values.size());
for (const float& v : values) {
matchers.emplace_back(FloatNear(v, max_abs_error));
}
return matchers;
}
int SingleOpModel::AddTensor(TensorData t) {
int id = tensors_.size();
// This is slightly different depending on whether we are adding a
// quantized or a regular tensor.
bool is_quantized = (t.min != 0 || t.max != 0 || t.scale != 0);
flatbuffers::Offset<QuantizationParameters> q_params = 0;
if (is_quantized) {
if (t.min != 0 || t.max != 0) {
if (t.type == TensorType_UINT8) {
std::tie(t.scale, t.zero_point) =
QuantizationParams<uint8_t>(t.min, t.max);
} else if (t.type == TensorType_INT32) {
std::tie(t.scale, t.zero_point) =
QuantizationParams<int32_t>(t.min, t.max);
} else {
LOG(FATAL) << "No support for the requested quantized type";
}
t.min = 0;
t.max = 0;
}
q_params = CreateQuantizationParameters(
builder_, /*min=*/0, /*max=*/0, builder_.CreateVector<float>({t.scale}),
builder_.CreateVector<int64_t>({t.zero_point}));
}
tensors_.push_back(CreateTensor(builder_, builder_.CreateVector<int>({}),
t.type, /*buffer=*/0,
/*name=*/0, q_params));
tensor_data_[id] = t;
return id;
}
int SingleOpModel::AddInput(const TensorData& t) {
int id = AddTensor(t);
inputs_.push_back(id);
return id;
}
int SingleOpModel::AddNullInput() {
int id = kOptionalTensor;
inputs_.push_back(id);
return id;
}
int SingleOpModel::AddOutput(const TensorData& t) {
int id = AddTensor(t);
outputs_.push_back(id);
return id;
}
void SingleOpModel::SetBuiltinOp(BuiltinOperator type,
BuiltinOptions builtin_options_type,
flatbuffers::Offset<void> builtin_options) {
opcodes_.push_back(CreateOperatorCode(builder_, type, 0));
operators_.push_back(CreateOperator(
builder_, /*opcode_index=*/0, builder_.CreateVector<int32_t>(inputs_),
builder_.CreateVector<int32_t>(outputs_), builtin_options_type,
builtin_options,
/*custom_options=*/0, CustomOptionsFormat_FLEXBUFFERS));
}
void SingleOpModel::SetCustomOp(
const string& name, const std::vector<uint8_t>& custom_option,
const std::function<TfLiteRegistration*()>& registeration) {
custom_registrations_[name] = registeration;
opcodes_.push_back(
CreateOperatorCodeDirect(builder_, BuiltinOperator_CUSTOM, name.data()));
operators_.push_back(CreateOperator(
builder_, /*opcode_index=*/0, builder_.CreateVector<int32_t>(inputs_),
builder_.CreateVector<int32_t>(outputs_), BuiltinOptions_NONE, 0,
builder_.CreateVector<uint8_t>(custom_option),
CustomOptionsFormat_FLEXBUFFERS));
}
void SingleOpModel::BuildInterpreter(
std::vector<std::vector<int>> input_shapes) {
auto opcodes = builder_.CreateVector(opcodes_);
auto operators = builder_.CreateVector(operators_);
auto tensors = builder_.CreateVector(tensors_);
auto inputs = builder_.CreateVector<int32_t>(inputs_);
auto outputs = builder_.CreateVector<int32_t>(outputs_);
// Create a single subgraph
std::vector<flatbuffers::Offset<SubGraph>> subgraphs;
auto subgraph = CreateSubGraph(builder_, tensors, inputs, outputs, operators);
subgraphs.push_back(subgraph);
auto subgraphs_flatbuffer = builder_.CreateVector(subgraphs);
std::vector<flatbuffers::Offset<Buffer>> buffers_vec;
auto buffers = builder_.CreateVector(buffers_vec);
auto description = builder_.CreateString("programmatic model");
builder_.Finish(CreateModel(builder_, TFLITE_SCHEMA_VERSION, opcodes,
subgraphs_flatbuffer, description, buffers));
auto* model = GetModel(builder_.GetBufferPointer());
ops::builtin::BuiltinOpResolver builtins;
for (const auto& reg : custom_registrations_) {
builtins.AddCustom(reg.first.data(), reg.second());
}
InterpreterBuilder(model, builtins)(&interpreter_);
CHECK(interpreter_ != nullptr);
int i = 0;
for (const auto& shape : input_shapes) {
int input_idx = interpreter_->inputs()[i++];
if (input_idx == kOptionalTensor) continue;
CHECK(interpreter_->ResizeInputTensor(input_idx, shape) == kTfLiteOk);
}
CHECK(interpreter_->AllocateTensors() == kTfLiteOk)
<< "Cannot allocate tensors";
}
void SingleOpModel::Invoke() { CHECK(interpreter_->Invoke() == kTfLiteOk); }
int32_t SingleOpModel::GetTensorSize(int index) const {
TfLiteTensor* t = interpreter_->tensor(index);
CHECK(t);
int total_size = 1;
for (int i = 0; i < t->dims->size; ++i) {
total_size *= t->dims->data[i];
}
return total_size;
}
} // namespace tflite
|
#include "include/logger.h"
logger::logger(std::string path) {
log_path = path;
log_file.open(log_path, std::ofstream::out | std::ofstream::app);
}
logger::~logger() {
log_file.close();
}
std::string logger::get_time() {
time_t tim = time(NULL);
std::string now = std::string(asctime(localtime(&tim)));
now.erase(now.end()-1, now.end());
return now;
}
void logger::add(const char * text, ...) {
char mess[8192];
va_list args;
va_start (args, text);
vsprintf(mess, text, args);
va_end(args);
log_file << get_time() << ": " << mess << std::endl;
}
void logger::error(const char *text, ...) {
char mess[8192];
va_list args;
va_start (args, text);
vsprintf(mess, text, args);
va_end(args);
std::cerr << "!ERROR - " << get_time() << ": " << mess << std::endl;
log_file << "!ERROR - " << get_time() << ": " << mess << std::endl;
}
|
#ifndef ENGINECL_SCHEDULER_PROP_HPP
#define ENGINECL_SCHEDULER_PROP_HPP 1
#include <atomic>
#include <chrono>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
#include "inspector.hpp"
#include "scheduler.hpp"
#include "semaphore.hpp"
#include "work.hpp"
using std::atomic;
using std::lock_guard;
using std::make_tuple;
using std::mutex;
using std::queue;
using std::thread;
using std::tie;
namespace ecl {
enum class ActionType;
class Device;
class Scheduler;
class ProportionalScheduler;
void
scheduler_thread_func(ProportionalScheduler& sched);
class ProportionalScheduler : public Scheduler
{
public:
enum WorkSplit
{
Raw = 0,
// work / ndevices
By_Devices = 1,
// Decr2 = 2, // first 50%, second 50% * 50%, etc
// Incr2 = 3, // last 50%, before last 50% * 50%, etc
};
ProportionalScheduler(WorkSplit wsplit = WorkSplit::By_Devices);
~ProportionalScheduler();
ProportionalScheduler(ProportionalScheduler const&) = delete;
ProportionalScheduler& operator=(ProportionalScheduler const&) = delete;
ProportionalScheduler(ProportionalScheduler&&) = default;
ProportionalScheduler& operator=(ProportionalScheduler&&) = default;
// Public API
void start() override;
// NOTE(dyn) new func
void setWorkSize(size_t size);
// NOTE(dyn) new func
bool hasWork();
// NOTE(dyn)
Device* getNextRequest();
void notifyDevices();
void waitRequests();
void notifyRequests();
void waitCallbacks();
void notifyCallbacks();
void setTotalSize(size_t size);
tuple<size_t, size_t> splitWork(size_t size, float prop, size_t bound);
void calcProportions();
void setDevices(vector<Device*>&& devices);
int getWorkIndex(Device* device) override;
Work getWork(uint queue_index) override;
// Thread API
void init();
void endScheduler() override;
void printStats() override;
void saveDuration(ActionType action);
void saveDurationOffset(ActionType action);
void callback(int queue_index) override;
void req_work(Device* device) override;
void enq_work(Device* device) override;
void preenq_work() override;
void setGWS(NDRange gws) override;
void setLWS(size_t lws) override;
void setWSBound(float ws_bound) override;
private:
thread m_thread;
size_t m_size;
vector<Device*> m_devices;
uint m_ndevices;
mutex m_mutex_work;
vector<Work> m_queue_work;
vector<vector<uint>> m_queue_id_work;
uint m_queue_work_size;
vector<uint> m_chunk_todo;
vector<uint> m_chunk_given;
vector<uint> m_chunk_done;
vector<uint>m_device_enable;
int m_devices_working;
vector<tuple<size_t, size_t>> m_proportions;
vector<float> m_raw_proportions;
// new
WorkSplit m_wsplit;
bool m_has_work;
semaphore m_sema_requests;
semaphore m_sema_callbacks;
queue<int> m_requests;
atomic<size_t> m_chunks_done;
int m_requests_max;
atomic<uint> m_requests_idx;
atomic<uint> m_requests_idx_done;
vector<uint> m_requests_list;
int m_size_rem_given;
int m_size_rem;
// size_t m_size_rem_completed;
atomic<int> m_size_rem_completed;
size_t m_size_given;
size_t m_worksize;
size_t m_work_last;
NDRange m_gws;
size_t m_lws;
size_t m_ws_bound;
mutex* m_mutex_duration;
std::chrono::duration<double,std::micro> m_time_init;
std::chrono::duration<double,std::micro> m_time;
vector<tuple<size_t, ActionType>> m_duration_actions;
vector<tuple<size_t, ActionType>> m_duration_offset_actions;
};
} // namespace ecl
#endif /* ENGINECL_SCHEDULER_PROP_HPP */
|
/*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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.
*/
// om-;TEST=SPathTest om-t
#include <cassert>
#include <vector>
#include <string>
#include <iomanip>
#include <iostream>
#include "SPath.hh"
#include "OPTICKS_LOG.hh"
void test_Stem()
{
LOG(info);
const char* name = "hello.cu" ;
const char* stem = SPath::Stem(name);
const char* x_stem = "hello" ;
assert( strcmp( stem, x_stem ) == 0 );
}
void test_GetHomePath()
{
LOG(info);
const char* bashrc = SPath::GetHomePath(".bashrc") ;
std::cout << bashrc << std::endl ;
}
void test_IsReadable()
{
LOG(info);
const char* self = SPath::GetHomePath("opticks/sysrap/tests/SPathTest.cc") ;
const char* non = SPath::GetHomePath("opticks/sysrap/tests/SPathTest.cc.non") ;
std::cout << self << std::endl ;
bool readable = SPath::IsReadable(self);
if(!readable)
{
LOG(fatal) << "looks like opticks source not in HOME" ;
}
//assert( readable == true );
bool readable_non = SPath::IsReadable(non);
assert( readable_non == false );
}
void test_Dirname()
{
LOG(info);
const char* lines = R"LIT(
$HOME/hello
$TMP/somewhere/over/the/rainbow.txt
$NON_EXISTING_EVAR/elsewhere/sub.txt
/just/some/path.txt
stem.ext
/
$
)LIT";
std::stringstream ss(lines);
std::string line ;
while (std::getline(ss, line, '\n'))
{
if(line.empty()) continue ;
const char* path = SPath::Dirname(line.c_str());
std::cout
<< std::setw(60) << line
<< " : "
<< std::setw(60) << path
<< std::endl
;
}
}
void test_Basename()
{
LOG(info);
std::vector<std::string> paths = { "/dd/materials/Water", "Water", "" } ;
for(unsigned i=0 ; i < paths.size() ; i++)
{
const char* path = paths[i].c_str() ;
const char* base = SPath::Basename(path) ;
std::cout
<< " path [" << path << "]"
<< " base [" << base << "]"
<< std::endl
;
}
}
void test_UserTmpDir()
{
LOG(info);
const char* tmp = SPath::UserTmpDir();
std::cout << tmp << std::endl ;
}
void test_Resolve()
{
LOG(info);
const char* lines = R"LIT(
$TMP
$OPTICKS_TMP
$OPTICKS_EVENT_BASE
$HOME/hello
$TMP/somewhere/over/the/rainbow.txt
$NON_EXISTING_EVAR/elsewhere/sub.txt
/just/some/path.txt
stem.ext
/
$
)LIT";
std::stringstream ss(lines);
std::string line ;
while (std::getline(ss, line, '\n'))
{
if(line.empty()) continue ;
const char* path = SPath::Resolve(line.c_str());
std::cout
<< std::setw(60) << line
<< " : "
<< std::setw(60) << path
<< std::endl
;
}
}
void test_ChangeName()
{
const char* srcpath = "/some/long/path/ending/with/pixels.jpg" ;
const char* path = SPath::ChangeName(srcpath, "posi.npy" );
const char* xpath = "/some/long/path/ending/with/posi.npy" ;
LOG(info) << path ;
assert( 0 == strcmp( path, xpath ) ) ;
}
void test_MakeDirs()
{
const char* path = "/tmp/SPathTest/red/green/blue" ;
int rc = SPath::MakeDirs(path);
LOG(info) << " path " << path << " rc " << rc ;
}
void test_MakePath()
{
const char* path = SPath::MakePath<double>("/tmp/SPathTest", "test_MakePath", 1.123, "demo.npy" );
LOG(info) << " path " << path ;
}
int main(int argc , char** argv )
{
OPTICKS_LOG(argc, argv);
/*
test_Stem();
test_GetHomePath();
test_IsReadable();
test_Dirname();
test_Basename();
test_UserTmpDir();
test_Resolve();
test_ChangeName();
test_MakeDirs();
*/
test_MakePath();
return 0 ;
}
// om-;TEST=SPathTest om-t
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017 The ATEC developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ecwrapper.h"
#include "serialize.h"
#include "uint256.h"
#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
namespace
{
/**
* Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
* recid selects which key is recovered
* if check is non-zero, additional checks are performed
*/
int ECDSA_SIG_recover_key_GFp(EC_KEY* eckey, ECDSA_SIG* ecsig, const unsigned char* msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX* ctx = NULL;
BIGNUM* x = NULL;
BIGNUM* e = NULL;
BIGNUM* order = NULL;
BIGNUM* sor = NULL;
BIGNUM* eor = NULL;
BIGNUM* field = NULL;
EC_POINT* R = NULL;
EC_POINT* O = NULL;
EC_POINT* Q = NULL;
BIGNUM* rr = NULL;
BIGNUM* zero = NULL;
int n = 0;
int i = recid / 2;
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
const BIGNUM *sig_r, *sig_s;
ECDSA_SIG_get0(ecsig, &sig_r, &sig_s);
#endif
const EC_GROUP* group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) {
ret = -1;
goto err;
}
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) {
ret = -2;
goto err;
}
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) {
ret = -1;
goto err;
}
if (!BN_mul_word(x, i)) {
ret = -1;
goto err;
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (!BN_add(x, x, sig_r)) {
#else
if (!BN_add(x, x, ecsig->r)) {
#endif
ret = -1;
goto err;
}
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) {
ret = -2;
goto err;
}
if (BN_cmp(x, field) >= 0) {
ret = 0;
goto err;
}
if ((R = EC_POINT_new(group)) == NULL) {
ret = -2;
goto err;
}
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) {
ret = 0;
goto err;
}
if (check) {
if ((O = EC_POINT_new(group)) == NULL) {
ret = -2;
goto err;
}
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) {
ret = -2;
goto err;
}
if (!EC_POINT_is_at_infinity(group, O)) {
ret = 0;
goto err;
}
}
if ((Q = EC_POINT_new(group)) == NULL) {
ret = -2;
goto err;
}
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) {
ret = -1;
goto err;
}
if (8 * msglen > n) BN_rshift(e, e, 8 - (n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) {
ret = -1;
goto err;
}
if (!BN_mod_sub(e, zero, e, order, ctx)) {
ret = -1;
goto err;
}
rr = BN_CTX_get(ctx);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (!BN_mod_inverse(rr, sig_r, order, ctx)) {
#else
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) {
#endif
ret = -1;
goto err;
}
sor = BN_CTX_get(ctx);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (!BN_mod_mul(sor, sig_s, rr, order, ctx)) {
#else
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) {
#endif
ret = -1;
goto err;
}
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) {
ret = -1;
goto err;
}
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) {
ret = -2;
goto err;
}
if (!EC_KEY_set_public_key(eckey, Q)) {
ret = -2;
goto err;
}
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
} // anon namespace
CECKey::CECKey()
{
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
assert(pkey != NULL);
}
CECKey::~CECKey()
{
EC_KEY_free(pkey);
}
void CECKey::GetPubKey(std::vector<unsigned char>& pubkey, bool fCompressed)
{
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2o_ECPublicKey(pkey, NULL);
assert(nSize);
assert(nSize <= 65);
pubkey.clear();
pubkey.resize(nSize);
unsigned char* pbegin(begin_ptr(pubkey));
int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
assert(nSize == nSize2);
}
bool CECKey::SetPubKey(const unsigned char* pubkey, size_t size)
{
return o2i_ECPublicKey(&pkey, &pubkey, size) != NULL;
}
bool CECKey::Verify(const uint256& hash, const std::vector<unsigned char>& vchSig)
{
if (vchSig.empty())
return false;
// New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
unsigned char* norm_der = NULL;
ECDSA_SIG* norm_sig = ECDSA_SIG_new();
const unsigned char* sigptr = &vchSig[0];
assert(norm_sig);
if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL) {
/* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
* error. But OpenSSL's own use of this function redundantly frees the
* result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
* clear contract for the function behaving the same way is more
* conservative.
*/
ECDSA_SIG_free(norm_sig);
return false;
}
int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
ECDSA_SIG_free(norm_sig);
if (derlen <= 0)
return false;
// -1 = error, 0 = bad sig, 1 = good
bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
OPENSSL_free(norm_der);
return ret;
}
bool CECKey::Recover(const uint256& hash, const unsigned char* p64, int rec)
{
if (rec < 0 || rec >= 3)
return false;
ECDSA_SIG* sig = ECDSA_SIG_new();
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
BIGNUM *sig_r = NULL;
BIGNUM *sig_s = NULL;
if (!(sig_r = BN_bin2bn(&p64[0], 32, nullptr)) ||
!(sig_s = BN_bin2bn(&p64[32], 32, nullptr)) ||
!ECDSA_SIG_set0(sig, sig_r, sig_s)) {
BN_free(sig_r);
BN_free(sig_s);
return false;
}
#else
BN_bin2bn(&p64[0], 32, sig->r);
BN_bin2bn(&p64[32], 32, sig->s);
#endif
bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
ECDSA_SIG_free(sig);
return ret;
}
bool CECKey::TweakPublic(const unsigned char vchTweak[32])
{
bool ret = true;
BN_CTX* ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM* bnTweak = BN_CTX_get(ctx);
BIGNUM* bnOrder = BN_CTX_get(ctx);
BIGNUM* bnOne = BN_CTX_get(ctx);
const EC_GROUP* group = EC_KEY_get0_group(pkey);
EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
BN_bin2bn(vchTweak, 32, bnTweak);
if (BN_cmp(bnTweak, bnOrder) >= 0)
ret = false; // extremely unlikely
EC_POINT* point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
BN_one(bnOne);
EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
if (EC_POINT_is_at_infinity(group, point))
ret = false; // ridiculously unlikely
EC_KEY_set_public_key(pkey, point);
EC_POINT_free(point);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ret;
}
bool CECKey::SanityCheck()
{
EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
return false;
EC_KEY_free(pkey);
// TODO Is there more EC functionality that could be missing?
return true;
}
|
/**
* OpenAL cross platform audio library
* Copyright (C) 1999-2007 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include "version.h"
#include <exception>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <chrono>
#include <cinttypes>
#include <climits>
#include <cmath>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <mutex>
#include <new>
#include <numeric>
#include <string>
#include <thread>
#include <utility>
#include "AL/al.h"
#include "AL/alc.h"
#include "AL/alext.h"
#include "AL/efx.h"
#include "al/auxeffectslot.h"
#include "al/effect.h"
#include "al/event.h"
#include "al/filter.h"
#include "al/listener.h"
#include "al/source.h"
#include "alcmain.h"
#include "albyte.h"
#include "alconfig.h"
#include "alcontext.h"
#include "alexcpt.h"
#include "almalloc.h"
#include "alnumeric.h"
#include "aloptional.h"
#include "alspan.h"
#include "alstring.h"
#include "alu.h"
#include "ambidefs.h"
#include "atomic.h"
#include "bformatdec.h"
#include "bs2b.h"
#include "compat.h"
#include "cpu_caps.h"
#include "devformat.h"
#include "effects/base.h"
#include "filters/nfc.h"
#include "filters/splitter.h"
#include "fpu_modes.h"
#include "hrtf.h"
#include "inprogext.h"
#include "intrusive_ptr.h"
#include "logging.h"
#include "mastering.h"
#include "opthelpers.h"
#include "pragmadefs.h"
#include "ringbuffer.h"
#include "strutils.h"
#include "threads.h"
#include "uhjfilter.h"
#include "vecmat.h"
#include "vector.h"
#include "backends/base.h"
#include "backends/null.h"
#include "backends/loopback.h"
#ifdef HAVE_JACK
#include "backends/jack.h"
#endif
#ifdef HAVE_PULSEAUDIO
#include "backends/pulseaudio.h"
#endif
#ifdef HAVE_ALSA
#include "backends/alsa.h"
#endif
#ifdef HAVE_WASAPI
#include "backends/wasapi.h"
#endif
#ifdef HAVE_COREAUDIO
#include "backends/coreaudio.h"
#endif
#ifdef HAVE_OPENSL
#include "backends/opensl.h"
#endif
#ifdef HAVE_SOLARIS
#include "backends/solaris.h"
#endif
#ifdef HAVE_SNDIO
#include "backends/sndio.h"
#endif
#ifdef HAVE_OSS
#include "backends/oss.h"
#endif
#ifdef HAVE_QSA
#include "backends/qsa.h"
#endif
#ifdef HAVE_DSOUND
#include "backends/dsound.h"
#endif
#ifdef HAVE_WINMM
#include "backends/winmm.h"
#endif
#ifdef HAVE_PORTAUDIO
#include "backends/portaudio.h"
#endif
#ifdef HAVE_SDL2
#include "backends/sdl2.h"
#endif
#ifdef HAVE_WAVE
#include "backends/wave.h"
#endif
namespace {
using namespace std::placeholders;
using std::chrono::seconds;
using std::chrono::nanoseconds;
/************************************************
* Backends
************************************************/
struct BackendInfo {
const char *name;
BackendFactory& (*getFactory)(void);
};
BackendInfo BackendList[] = {
#ifdef HAVE_JACK
{ "jack", JackBackendFactory::getFactory },
#endif
#ifdef HAVE_PULSEAUDIO
{ "pulse", PulseBackendFactory::getFactory },
#endif
#ifdef HAVE_ALSA
{ "alsa", AlsaBackendFactory::getFactory },
#endif
#ifdef HAVE_WASAPI
{ "wasapi", WasapiBackendFactory::getFactory },
#endif
#ifdef HAVE_COREAUDIO
{ "core", CoreAudioBackendFactory::getFactory },
#endif
#ifdef HAVE_OPENSL
{ "opensl", OSLBackendFactory::getFactory },
#endif
#ifdef HAVE_SOLARIS
{ "solaris", SolarisBackendFactory::getFactory },
#endif
#ifdef HAVE_SNDIO
{ "sndio", SndIOBackendFactory::getFactory },
#endif
#ifdef HAVE_OSS
{ "oss", OSSBackendFactory::getFactory },
#endif
#ifdef HAVE_QSA
{ "qsa", QSABackendFactory::getFactory },
#endif
#ifdef HAVE_DSOUND
{ "dsound", DSoundBackendFactory::getFactory },
#endif
#ifdef HAVE_WINMM
{ "winmm", WinMMBackendFactory::getFactory },
#endif
#ifdef HAVE_PORTAUDIO
{ "port", PortBackendFactory::getFactory },
#endif
#ifdef HAVE_SDL2
{ "sdl2", SDL2BackendFactory::getFactory },
#endif
{ "null", NullBackendFactory::getFactory },
#ifdef HAVE_WAVE
{ "wave", WaveBackendFactory::getFactory },
#endif
};
auto BackendListEnd = std::end(BackendList);
BackendFactory *PlaybackFactory{};
BackendFactory *CaptureFactory{};
/************************************************
* Functions, enums, and errors
************************************************/
#define DECL(x) { #x, reinterpret_cast<void*>(x) }
const struct {
const ALCchar *funcName;
ALCvoid *address;
} alcFunctions[] = {
DECL(alcCreateContext),
DECL(alcMakeContextCurrent),
DECL(alcProcessContext),
DECL(alcSuspendContext),
DECL(alcDestroyContext),
DECL(alcGetCurrentContext),
DECL(alcGetContextsDevice),
DECL(alcOpenDevice),
DECL(alcCloseDevice),
DECL(alcGetError),
DECL(alcIsExtensionPresent),
DECL(alcGetProcAddress),
DECL(alcGetEnumValue),
DECL(alcGetString),
DECL(alcGetIntegerv),
DECL(alcCaptureOpenDevice),
DECL(alcCaptureCloseDevice),
DECL(alcCaptureStart),
DECL(alcCaptureStop),
DECL(alcCaptureSamples),
DECL(alcSetThreadContext),
DECL(alcGetThreadContext),
DECL(alcLoopbackOpenDeviceSOFT),
DECL(alcIsRenderFormatSupportedSOFT),
DECL(alcRenderSamplesSOFT),
DECL(alcDevicePauseSOFT),
DECL(alcDeviceResumeSOFT),
DECL(alcGetStringiSOFT),
DECL(alcResetDeviceSOFT),
DECL(alcGetInteger64vSOFT),
DECL(alEnable),
DECL(alDisable),
DECL(alIsEnabled),
DECL(alGetString),
DECL(alGetBooleanv),
DECL(alGetIntegerv),
DECL(alGetFloatv),
DECL(alGetDoublev),
DECL(alGetBoolean),
DECL(alGetInteger),
DECL(alGetFloat),
DECL(alGetDouble),
DECL(alGetError),
DECL(alIsExtensionPresent),
DECL(alGetProcAddress),
DECL(alGetEnumValue),
DECL(alListenerf),
DECL(alListener3f),
DECL(alListenerfv),
DECL(alListeneri),
DECL(alListener3i),
DECL(alListeneriv),
DECL(alGetListenerf),
DECL(alGetListener3f),
DECL(alGetListenerfv),
DECL(alGetListeneri),
DECL(alGetListener3i),
DECL(alGetListeneriv),
DECL(alGenSources),
DECL(alDeleteSources),
DECL(alIsSource),
DECL(alSourcef),
DECL(alSource3f),
DECL(alSourcefv),
DECL(alSourcei),
DECL(alSource3i),
DECL(alSourceiv),
DECL(alGetSourcef),
DECL(alGetSource3f),
DECL(alGetSourcefv),
DECL(alGetSourcei),
DECL(alGetSource3i),
DECL(alGetSourceiv),
DECL(alSourcePlayv),
DECL(alSourceStopv),
DECL(alSourceRewindv),
DECL(alSourcePausev),
DECL(alSourcePlay),
DECL(alSourceStop),
DECL(alSourceRewind),
DECL(alSourcePause),
DECL(alSourceQueueBuffers),
DECL(alSourceUnqueueBuffers),
DECL(alGenBuffers),
DECL(alDeleteBuffers),
DECL(alIsBuffer),
DECL(alBufferData),
DECL(alBufferf),
DECL(alBuffer3f),
DECL(alBufferfv),
DECL(alBufferi),
DECL(alBuffer3i),
DECL(alBufferiv),
DECL(alGetBufferf),
DECL(alGetBuffer3f),
DECL(alGetBufferfv),
DECL(alGetBufferi),
DECL(alGetBuffer3i),
DECL(alGetBufferiv),
DECL(alDopplerFactor),
DECL(alDopplerVelocity),
DECL(alSpeedOfSound),
DECL(alDistanceModel),
DECL(alGenFilters),
DECL(alDeleteFilters),
DECL(alIsFilter),
DECL(alFilteri),
DECL(alFilteriv),
DECL(alFilterf),
DECL(alFilterfv),
DECL(alGetFilteri),
DECL(alGetFilteriv),
DECL(alGetFilterf),
DECL(alGetFilterfv),
DECL(alGenEffects),
DECL(alDeleteEffects),
DECL(alIsEffect),
DECL(alEffecti),
DECL(alEffectiv),
DECL(alEffectf),
DECL(alEffectfv),
DECL(alGetEffecti),
DECL(alGetEffectiv),
DECL(alGetEffectf),
DECL(alGetEffectfv),
DECL(alGenAuxiliaryEffectSlots),
DECL(alDeleteAuxiliaryEffectSlots),
DECL(alIsAuxiliaryEffectSlot),
DECL(alAuxiliaryEffectSloti),
DECL(alAuxiliaryEffectSlotiv),
DECL(alAuxiliaryEffectSlotf),
DECL(alAuxiliaryEffectSlotfv),
DECL(alGetAuxiliaryEffectSloti),
DECL(alGetAuxiliaryEffectSlotiv),
DECL(alGetAuxiliaryEffectSlotf),
DECL(alGetAuxiliaryEffectSlotfv),
DECL(alDeferUpdatesSOFT),
DECL(alProcessUpdatesSOFT),
DECL(alSourcedSOFT),
DECL(alSource3dSOFT),
DECL(alSourcedvSOFT),
DECL(alGetSourcedSOFT),
DECL(alGetSource3dSOFT),
DECL(alGetSourcedvSOFT),
DECL(alSourcei64SOFT),
DECL(alSource3i64SOFT),
DECL(alSourcei64vSOFT),
DECL(alGetSourcei64SOFT),
DECL(alGetSource3i64SOFT),
DECL(alGetSourcei64vSOFT),
DECL(alGetStringiSOFT),
DECL(alBufferStorageSOFT),
DECL(alMapBufferSOFT),
DECL(alUnmapBufferSOFT),
DECL(alFlushMappedBufferSOFT),
DECL(alEventControlSOFT),
DECL(alEventCallbackSOFT),
DECL(alGetPointerSOFT),
DECL(alGetPointervSOFT),
};
#undef DECL
#define DECL(x) { #x, (x) }
constexpr struct {
const ALCchar *enumName;
ALCenum value;
} alcEnumerations[] = {
DECL(ALC_INVALID),
DECL(ALC_FALSE),
DECL(ALC_TRUE),
DECL(ALC_MAJOR_VERSION),
DECL(ALC_MINOR_VERSION),
DECL(ALC_ATTRIBUTES_SIZE),
DECL(ALC_ALL_ATTRIBUTES),
DECL(ALC_DEFAULT_DEVICE_SPECIFIER),
DECL(ALC_DEVICE_SPECIFIER),
DECL(ALC_ALL_DEVICES_SPECIFIER),
DECL(ALC_DEFAULT_ALL_DEVICES_SPECIFIER),
DECL(ALC_EXTENSIONS),
DECL(ALC_FREQUENCY),
DECL(ALC_REFRESH),
DECL(ALC_SYNC),
DECL(ALC_MONO_SOURCES),
DECL(ALC_STEREO_SOURCES),
DECL(ALC_CAPTURE_DEVICE_SPECIFIER),
DECL(ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER),
DECL(ALC_CAPTURE_SAMPLES),
DECL(ALC_CONNECTED),
DECL(ALC_EFX_MAJOR_VERSION),
DECL(ALC_EFX_MINOR_VERSION),
DECL(ALC_MAX_AUXILIARY_SENDS),
DECL(ALC_FORMAT_CHANNELS_SOFT),
DECL(ALC_FORMAT_TYPE_SOFT),
DECL(ALC_MONO_SOFT),
DECL(ALC_STEREO_SOFT),
DECL(ALC_QUAD_SOFT),
DECL(ALC_5POINT1_SOFT),
DECL(ALC_6POINT1_SOFT),
DECL(ALC_7POINT1_SOFT),
DECL(ALC_BFORMAT3D_SOFT),
DECL(ALC_BYTE_SOFT),
DECL(ALC_UNSIGNED_BYTE_SOFT),
DECL(ALC_SHORT_SOFT),
DECL(ALC_UNSIGNED_SHORT_SOFT),
DECL(ALC_INT_SOFT),
DECL(ALC_UNSIGNED_INT_SOFT),
DECL(ALC_FLOAT_SOFT),
DECL(ALC_HRTF_SOFT),
DECL(ALC_DONT_CARE_SOFT),
DECL(ALC_HRTF_STATUS_SOFT),
DECL(ALC_HRTF_DISABLED_SOFT),
DECL(ALC_HRTF_ENABLED_SOFT),
DECL(ALC_HRTF_DENIED_SOFT),
DECL(ALC_HRTF_REQUIRED_SOFT),
DECL(ALC_HRTF_HEADPHONES_DETECTED_SOFT),
DECL(ALC_HRTF_UNSUPPORTED_FORMAT_SOFT),
DECL(ALC_NUM_HRTF_SPECIFIERS_SOFT),
DECL(ALC_HRTF_SPECIFIER_SOFT),
DECL(ALC_HRTF_ID_SOFT),
DECL(ALC_AMBISONIC_LAYOUT_SOFT),
DECL(ALC_AMBISONIC_SCALING_SOFT),
DECL(ALC_AMBISONIC_ORDER_SOFT),
DECL(ALC_ACN_SOFT),
DECL(ALC_FUMA_SOFT),
DECL(ALC_N3D_SOFT),
DECL(ALC_SN3D_SOFT),
DECL(ALC_OUTPUT_LIMITER_SOFT),
DECL(ALC_NO_ERROR),
DECL(ALC_INVALID_DEVICE),
DECL(ALC_INVALID_CONTEXT),
DECL(ALC_INVALID_ENUM),
DECL(ALC_INVALID_VALUE),
DECL(ALC_OUT_OF_MEMORY),
DECL(AL_INVALID),
DECL(AL_NONE),
DECL(AL_FALSE),
DECL(AL_TRUE),
DECL(AL_SOURCE_RELATIVE),
DECL(AL_CONE_INNER_ANGLE),
DECL(AL_CONE_OUTER_ANGLE),
DECL(AL_PITCH),
DECL(AL_POSITION),
DECL(AL_DIRECTION),
DECL(AL_VELOCITY),
DECL(AL_LOOPING),
DECL(AL_BUFFER),
DECL(AL_GAIN),
DECL(AL_MIN_GAIN),
DECL(AL_MAX_GAIN),
DECL(AL_ORIENTATION),
DECL(AL_REFERENCE_DISTANCE),
DECL(AL_ROLLOFF_FACTOR),
DECL(AL_CONE_OUTER_GAIN),
DECL(AL_MAX_DISTANCE),
DECL(AL_SEC_OFFSET),
DECL(AL_SAMPLE_OFFSET),
DECL(AL_BYTE_OFFSET),
DECL(AL_SOURCE_TYPE),
DECL(AL_STATIC),
DECL(AL_STREAMING),
DECL(AL_UNDETERMINED),
DECL(AL_METERS_PER_UNIT),
DECL(AL_LOOP_POINTS_SOFT),
DECL(AL_DIRECT_CHANNELS_SOFT),
DECL(AL_DIRECT_FILTER),
DECL(AL_AUXILIARY_SEND_FILTER),
DECL(AL_AIR_ABSORPTION_FACTOR),
DECL(AL_ROOM_ROLLOFF_FACTOR),
DECL(AL_CONE_OUTER_GAINHF),
DECL(AL_DIRECT_FILTER_GAINHF_AUTO),
DECL(AL_AUXILIARY_SEND_FILTER_GAIN_AUTO),
DECL(AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO),
DECL(AL_SOURCE_STATE),
DECL(AL_INITIAL),
DECL(AL_PLAYING),
DECL(AL_PAUSED),
DECL(AL_STOPPED),
DECL(AL_BUFFERS_QUEUED),
DECL(AL_BUFFERS_PROCESSED),
DECL(AL_FORMAT_MONO8),
DECL(AL_FORMAT_MONO16),
DECL(AL_FORMAT_MONO_FLOAT32),
DECL(AL_FORMAT_MONO_DOUBLE_EXT),
DECL(AL_FORMAT_STEREO8),
DECL(AL_FORMAT_STEREO16),
DECL(AL_FORMAT_STEREO_FLOAT32),
DECL(AL_FORMAT_STEREO_DOUBLE_EXT),
DECL(AL_FORMAT_MONO_IMA4),
DECL(AL_FORMAT_STEREO_IMA4),
DECL(AL_FORMAT_MONO_MSADPCM_SOFT),
DECL(AL_FORMAT_STEREO_MSADPCM_SOFT),
DECL(AL_FORMAT_QUAD8_LOKI),
DECL(AL_FORMAT_QUAD16_LOKI),
DECL(AL_FORMAT_QUAD8),
DECL(AL_FORMAT_QUAD16),
DECL(AL_FORMAT_QUAD32),
DECL(AL_FORMAT_51CHN8),
DECL(AL_FORMAT_51CHN16),
DECL(AL_FORMAT_51CHN32),
DECL(AL_FORMAT_61CHN8),
DECL(AL_FORMAT_61CHN16),
DECL(AL_FORMAT_61CHN32),
DECL(AL_FORMAT_71CHN8),
DECL(AL_FORMAT_71CHN16),
DECL(AL_FORMAT_71CHN32),
DECL(AL_FORMAT_REAR8),
DECL(AL_FORMAT_REAR16),
DECL(AL_FORMAT_REAR32),
DECL(AL_FORMAT_MONO_MULAW),
DECL(AL_FORMAT_MONO_MULAW_EXT),
DECL(AL_FORMAT_STEREO_MULAW),
DECL(AL_FORMAT_STEREO_MULAW_EXT),
DECL(AL_FORMAT_QUAD_MULAW),
DECL(AL_FORMAT_51CHN_MULAW),
DECL(AL_FORMAT_61CHN_MULAW),
DECL(AL_FORMAT_71CHN_MULAW),
DECL(AL_FORMAT_REAR_MULAW),
DECL(AL_FORMAT_MONO_ALAW_EXT),
DECL(AL_FORMAT_STEREO_ALAW_EXT),
DECL(AL_FORMAT_BFORMAT2D_8),
DECL(AL_FORMAT_BFORMAT2D_16),
DECL(AL_FORMAT_BFORMAT2D_FLOAT32),
DECL(AL_FORMAT_BFORMAT2D_MULAW),
DECL(AL_FORMAT_BFORMAT3D_8),
DECL(AL_FORMAT_BFORMAT3D_16),
DECL(AL_FORMAT_BFORMAT3D_FLOAT32),
DECL(AL_FORMAT_BFORMAT3D_MULAW),
DECL(AL_FREQUENCY),
DECL(AL_BITS),
DECL(AL_CHANNELS),
DECL(AL_SIZE),
DECL(AL_UNPACK_BLOCK_ALIGNMENT_SOFT),
DECL(AL_PACK_BLOCK_ALIGNMENT_SOFT),
DECL(AL_SOURCE_RADIUS),
DECL(AL_STEREO_ANGLES),
DECL(AL_UNUSED),
DECL(AL_PENDING),
DECL(AL_PROCESSED),
DECL(AL_NO_ERROR),
DECL(AL_INVALID_NAME),
DECL(AL_INVALID_ENUM),
DECL(AL_INVALID_VALUE),
DECL(AL_INVALID_OPERATION),
DECL(AL_OUT_OF_MEMORY),
DECL(AL_VENDOR),
DECL(AL_VERSION),
DECL(AL_RENDERER),
DECL(AL_EXTENSIONS),
DECL(AL_DOPPLER_FACTOR),
DECL(AL_DOPPLER_VELOCITY),
DECL(AL_DISTANCE_MODEL),
DECL(AL_SPEED_OF_SOUND),
DECL(AL_SOURCE_DISTANCE_MODEL),
DECL(AL_DEFERRED_UPDATES_SOFT),
DECL(AL_GAIN_LIMIT_SOFT),
DECL(AL_INVERSE_DISTANCE),
DECL(AL_INVERSE_DISTANCE_CLAMPED),
DECL(AL_LINEAR_DISTANCE),
DECL(AL_LINEAR_DISTANCE_CLAMPED),
DECL(AL_EXPONENT_DISTANCE),
DECL(AL_EXPONENT_DISTANCE_CLAMPED),
DECL(AL_FILTER_TYPE),
DECL(AL_FILTER_NULL),
DECL(AL_FILTER_LOWPASS),
DECL(AL_FILTER_HIGHPASS),
DECL(AL_FILTER_BANDPASS),
DECL(AL_LOWPASS_GAIN),
DECL(AL_LOWPASS_GAINHF),
DECL(AL_HIGHPASS_GAIN),
DECL(AL_HIGHPASS_GAINLF),
DECL(AL_BANDPASS_GAIN),
DECL(AL_BANDPASS_GAINHF),
DECL(AL_BANDPASS_GAINLF),
DECL(AL_EFFECT_TYPE),
DECL(AL_EFFECT_NULL),
DECL(AL_EFFECT_REVERB),
DECL(AL_EFFECT_EAXREVERB),
DECL(AL_EFFECT_CHORUS),
DECL(AL_EFFECT_DISTORTION),
DECL(AL_EFFECT_ECHO),
DECL(AL_EFFECT_FLANGER),
DECL(AL_EFFECT_PITCH_SHIFTER),
DECL(AL_EFFECT_FREQUENCY_SHIFTER),
DECL(AL_EFFECT_VOCAL_MORPHER),
DECL(AL_EFFECT_RING_MODULATOR),
DECL(AL_EFFECT_AUTOWAH),
DECL(AL_EFFECT_COMPRESSOR),
DECL(AL_EFFECT_EQUALIZER),
DECL(AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT),
DECL(AL_EFFECT_DEDICATED_DIALOGUE),
DECL(AL_EFFECTSLOT_EFFECT),
DECL(AL_EFFECTSLOT_GAIN),
DECL(AL_EFFECTSLOT_AUXILIARY_SEND_AUTO),
DECL(AL_EFFECTSLOT_NULL),
DECL(AL_EAXREVERB_DENSITY),
DECL(AL_EAXREVERB_DIFFUSION),
DECL(AL_EAXREVERB_GAIN),
DECL(AL_EAXREVERB_GAINHF),
DECL(AL_EAXREVERB_GAINLF),
DECL(AL_EAXREVERB_DECAY_TIME),
DECL(AL_EAXREVERB_DECAY_HFRATIO),
DECL(AL_EAXREVERB_DECAY_LFRATIO),
DECL(AL_EAXREVERB_REFLECTIONS_GAIN),
DECL(AL_EAXREVERB_REFLECTIONS_DELAY),
DECL(AL_EAXREVERB_REFLECTIONS_PAN),
DECL(AL_EAXREVERB_LATE_REVERB_GAIN),
DECL(AL_EAXREVERB_LATE_REVERB_DELAY),
DECL(AL_EAXREVERB_LATE_REVERB_PAN),
DECL(AL_EAXREVERB_ECHO_TIME),
DECL(AL_EAXREVERB_ECHO_DEPTH),
DECL(AL_EAXREVERB_MODULATION_TIME),
DECL(AL_EAXREVERB_MODULATION_DEPTH),
DECL(AL_EAXREVERB_AIR_ABSORPTION_GAINHF),
DECL(AL_EAXREVERB_HFREFERENCE),
DECL(AL_EAXREVERB_LFREFERENCE),
DECL(AL_EAXREVERB_ROOM_ROLLOFF_FACTOR),
DECL(AL_EAXREVERB_DECAY_HFLIMIT),
DECL(AL_REVERB_DENSITY),
DECL(AL_REVERB_DIFFUSION),
DECL(AL_REVERB_GAIN),
DECL(AL_REVERB_GAINHF),
DECL(AL_REVERB_DECAY_TIME),
DECL(AL_REVERB_DECAY_HFRATIO),
DECL(AL_REVERB_REFLECTIONS_GAIN),
DECL(AL_REVERB_REFLECTIONS_DELAY),
DECL(AL_REVERB_LATE_REVERB_GAIN),
DECL(AL_REVERB_LATE_REVERB_DELAY),
DECL(AL_REVERB_AIR_ABSORPTION_GAINHF),
DECL(AL_REVERB_ROOM_ROLLOFF_FACTOR),
DECL(AL_REVERB_DECAY_HFLIMIT),
DECL(AL_CHORUS_WAVEFORM),
DECL(AL_CHORUS_PHASE),
DECL(AL_CHORUS_RATE),
DECL(AL_CHORUS_DEPTH),
DECL(AL_CHORUS_FEEDBACK),
DECL(AL_CHORUS_DELAY),
DECL(AL_DISTORTION_EDGE),
DECL(AL_DISTORTION_GAIN),
DECL(AL_DISTORTION_LOWPASS_CUTOFF),
DECL(AL_DISTORTION_EQCENTER),
DECL(AL_DISTORTION_EQBANDWIDTH),
DECL(AL_ECHO_DELAY),
DECL(AL_ECHO_LRDELAY),
DECL(AL_ECHO_DAMPING),
DECL(AL_ECHO_FEEDBACK),
DECL(AL_ECHO_SPREAD),
DECL(AL_FLANGER_WAVEFORM),
DECL(AL_FLANGER_PHASE),
DECL(AL_FLANGER_RATE),
DECL(AL_FLANGER_DEPTH),
DECL(AL_FLANGER_FEEDBACK),
DECL(AL_FLANGER_DELAY),
DECL(AL_FREQUENCY_SHIFTER_FREQUENCY),
DECL(AL_FREQUENCY_SHIFTER_LEFT_DIRECTION),
DECL(AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION),
DECL(AL_RING_MODULATOR_FREQUENCY),
DECL(AL_RING_MODULATOR_HIGHPASS_CUTOFF),
DECL(AL_RING_MODULATOR_WAVEFORM),
DECL(AL_PITCH_SHIFTER_COARSE_TUNE),
DECL(AL_PITCH_SHIFTER_FINE_TUNE),
DECL(AL_COMPRESSOR_ONOFF),
DECL(AL_EQUALIZER_LOW_GAIN),
DECL(AL_EQUALIZER_LOW_CUTOFF),
DECL(AL_EQUALIZER_MID1_GAIN),
DECL(AL_EQUALIZER_MID1_CENTER),
DECL(AL_EQUALIZER_MID1_WIDTH),
DECL(AL_EQUALIZER_MID2_GAIN),
DECL(AL_EQUALIZER_MID2_CENTER),
DECL(AL_EQUALIZER_MID2_WIDTH),
DECL(AL_EQUALIZER_HIGH_GAIN),
DECL(AL_EQUALIZER_HIGH_CUTOFF),
DECL(AL_DEDICATED_GAIN),
DECL(AL_AUTOWAH_ATTACK_TIME),
DECL(AL_AUTOWAH_RELEASE_TIME),
DECL(AL_AUTOWAH_RESONANCE),
DECL(AL_AUTOWAH_PEAK_GAIN),
DECL(AL_VOCAL_MORPHER_PHONEMEA),
DECL(AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING),
DECL(AL_VOCAL_MORPHER_PHONEMEB),
DECL(AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING),
DECL(AL_VOCAL_MORPHER_WAVEFORM),
DECL(AL_VOCAL_MORPHER_RATE),
DECL(AL_NUM_RESAMPLERS_SOFT),
DECL(AL_DEFAULT_RESAMPLER_SOFT),
DECL(AL_SOURCE_RESAMPLER_SOFT),
DECL(AL_RESAMPLER_NAME_SOFT),
DECL(AL_SOURCE_SPATIALIZE_SOFT),
DECL(AL_AUTO_SOFT),
DECL(AL_MAP_READ_BIT_SOFT),
DECL(AL_MAP_WRITE_BIT_SOFT),
DECL(AL_MAP_PERSISTENT_BIT_SOFT),
DECL(AL_PRESERVE_DATA_BIT_SOFT),
DECL(AL_EVENT_CALLBACK_FUNCTION_SOFT),
DECL(AL_EVENT_CALLBACK_USER_PARAM_SOFT),
DECL(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT),
DECL(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT),
DECL(AL_EVENT_TYPE_ERROR_SOFT),
DECL(AL_EVENT_TYPE_PERFORMANCE_SOFT),
DECL(AL_EVENT_TYPE_DEPRECATED_SOFT),
DECL(AL_DROP_UNMATCHED_SOFT),
DECL(AL_REMIX_UNMATCHED_SOFT),
DECL(AL_AMBISONIC_LAYOUT_SOFT),
DECL(AL_AMBISONIC_SCALING_SOFT),
DECL(AL_FUMA_SOFT),
DECL(AL_ACN_SOFT),
DECL(AL_SN3D_SOFT),
DECL(AL_N3D_SOFT),
};
#undef DECL
constexpr ALCchar alcNoError[] = "No Error";
constexpr ALCchar alcErrInvalidDevice[] = "Invalid Device";
constexpr ALCchar alcErrInvalidContext[] = "Invalid Context";
constexpr ALCchar alcErrInvalidEnum[] = "Invalid Enum";
constexpr ALCchar alcErrInvalidValue[] = "Invalid Value";
constexpr ALCchar alcErrOutOfMemory[] = "Out of Memory";
/************************************************
* Global variables
************************************************/
/* Enumerated device names */
constexpr ALCchar alcDefaultName[] = "OpenAL Soft\0";
std::string alcAllDevicesList;
std::string alcCaptureDeviceList;
/* Default is always the first in the list */
al::string alcDefaultAllDevicesSpecifier;
al::string alcCaptureDefaultDeviceSpecifier;
/* Default context extensions */
constexpr ALchar alExtList[] =
"AL_EXT_ALAW "
"AL_EXT_BFORMAT "
"AL_EXT_DOUBLE "
"AL_EXT_EXPONENT_DISTANCE "
"AL_EXT_FLOAT32 "
"AL_EXT_IMA4 "
"AL_EXT_LINEAR_DISTANCE "
"AL_EXT_MCFORMATS "
"AL_EXT_MULAW "
"AL_EXT_MULAW_BFORMAT "
"AL_EXT_MULAW_MCFORMATS "
"AL_EXT_OFFSET "
"AL_EXT_source_distance_model "
"AL_EXT_SOURCE_RADIUS "
"AL_EXT_STEREO_ANGLES "
"AL_LOKI_quadriphonic "
"AL_SOFT_bformat_ex "
"AL_SOFT_block_alignment "
"AL_SOFT_deferred_updates "
"AL_SOFT_direct_channels "
"AL_SOFT_direct_channels_remix "
"AL_SOFTX_effect_chain "
"AL_SOFTX_events "
"AL_SOFTX_filter_gain_ex "
"AL_SOFT_gain_clamp_ex "
"AL_SOFT_loop_points "
"AL_SOFTX_map_buffer "
"AL_SOFT_MSADPCM "
"AL_SOFT_source_latency "
"AL_SOFT_source_length "
"AL_SOFT_source_resampler "
"AL_SOFT_source_spatialize";
std::atomic<ALCenum> LastNullDeviceError{ALC_NO_ERROR};
/* Thread-local current context */
class ThreadCtx {
ALCcontext *ctx{nullptr};
public:
~ThreadCtx()
{
if(ctx)
{
const bool result{ctx->releaseIfNoDelete()};
ERR("Context %p current for thread being destroyed%s!\n",
decltype(std::declval<void*>()){ctx}, result ? "" : ", leak detected");
}
}
ALCcontext *get() const noexcept { return ctx; }
void set(ALCcontext *ctx_) noexcept { ctx = ctx_; }
};
thread_local ThreadCtx LocalContext;
/* Process-wide current context */
std::atomic<ALCcontext*> GlobalContext{nullptr};
/* Flag to trap ALC device errors */
bool TrapALCError{false};
/* One-time configuration init control */
std::once_flag alc_config_once{};
/* Default effect that applies to sources that don't have an effect on send 0 */
ALeffect DefaultEffect;
/* Flag to specify if alcSuspendContext/alcProcessContext should defer/process
* updates.
*/
bool SuspendDefers{true};
/* Initial seed for dithering. */
constexpr ALuint DitherRNGSeed{22222u};
/************************************************
* ALC information
************************************************/
constexpr ALCchar alcNoDeviceExtList[] =
"ALC_ENUMERATE_ALL_EXT "
"ALC_ENUMERATION_EXT "
"ALC_EXT_CAPTURE "
"ALC_EXT_thread_local_context "
"ALC_SOFT_loopback";
constexpr ALCchar alcExtensionList[] =
"ALC_ENUMERATE_ALL_EXT "
"ALC_ENUMERATION_EXT "
"ALC_EXT_CAPTURE "
"ALC_EXT_DEDICATED "
"ALC_EXT_disconnect "
"ALC_EXT_EFX "
"ALC_EXT_thread_local_context "
"ALC_SOFT_device_clock "
"ALC_SOFT_HRTF "
"ALC_SOFT_loopback "
"ALC_SOFT_output_limiter "
"ALC_SOFT_pause_device";
constexpr ALCint alcMajorVersion = 1;
constexpr ALCint alcMinorVersion = 1;
constexpr ALCint alcEFXMajorVersion = 1;
constexpr ALCint alcEFXMinorVersion = 0;
/* To avoid extraneous allocations, a 0-sized FlexArray<ALCcontext*> is defined
* globally as a sharable object. MSVC warns that a zero-sized array will have
* zero objects here, so silence that.
*/
DIAGNOSTIC_PUSH
msc_pragma(warning(disable : 4815))
al::FlexArray<ALCcontext*> EmptyContextArray{0u};
DIAGNOSTIC_POP
using DeviceRef = al::intrusive_ptr<ALCdevice>;
/************************************************
* Device lists
************************************************/
al::vector<ALCdevice*> DeviceList;
al::vector<ALCcontext*> ContextList;
std::recursive_mutex ListLock;
void alc_initconfig(void)
{
if(auto loglevel = al::getenv("ALSOFT_LOGLEVEL"))
{
long lvl = strtol(loglevel->c_str(), nullptr, 0);
if(lvl >= NoLog && lvl <= LogRef)
gLogLevel = static_cast<LogLevel>(lvl);
}
if(auto logfile = al::getenv("ALSOFT_LOGFILE"))
{
#ifdef _WIN32
std::wstring wname{utf8_to_wstr(logfile->c_str())};
FILE *logf{_wfopen(wname.c_str(), L"wt")};
#else
FILE *logf{fopen(logfile->c_str(), "wt")};
#endif
if(logf) gLogFile = logf;
else ERR("Failed to open log file '%s'\n", logfile->c_str());
}
TRACE("Initializing library v%s-%s %s\n", ALSOFT_VERSION, ALSOFT_GIT_COMMIT_HASH,
ALSOFT_GIT_BRANCH);
{
al::string names;
if(std::begin(BackendList) == BackendListEnd)
names += "(none)";
else
{
const al::span<const BackendInfo> infos{std::begin(BackendList), BackendListEnd};
names += infos[0].name;
for(const auto &backend : infos.subspan(1))
{
names += ", ";
names += backend.name;
}
}
TRACE("Supported backends: %s\n", names.c_str());
}
ReadALConfig();
if(auto suspendmode = al::getenv("__ALSOFT_SUSPEND_CONTEXT"))
{
if(al::strcasecmp(suspendmode->c_str(), "ignore") == 0)
{
SuspendDefers = false;
TRACE("Selected context suspend behavior, \"ignore\"\n");
}
else
ERR("Unhandled context suspend behavior setting: \"%s\"\n", suspendmode->c_str());
}
int capfilter{0};
#if defined(HAVE_SSE4_1)
capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
#elif defined(HAVE_SSE3)
capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
#elif defined(HAVE_SSE2)
capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2;
#elif defined(HAVE_SSE)
capfilter |= CPU_CAP_SSE;
#endif
#ifdef HAVE_NEON
capfilter |= CPU_CAP_NEON;
#endif
if(auto cpuopt = ConfigValueStr(nullptr, nullptr, "disable-cpu-exts"))
{
const char *str{cpuopt->c_str()};
if(al::strcasecmp(str, "all") == 0)
capfilter = 0;
else
{
const char *next = str;
do {
str = next;
while(isspace(str[0]))
str++;
next = strchr(str, ',');
if(!str[0] || str[0] == ',')
continue;
size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
while(len > 0 && isspace(str[len-1]))
len--;
if(len == 3 && al::strncasecmp(str, "sse", len) == 0)
capfilter &= ~CPU_CAP_SSE;
else if(len == 4 && al::strncasecmp(str, "sse2", len) == 0)
capfilter &= ~CPU_CAP_SSE2;
else if(len == 4 && al::strncasecmp(str, "sse3", len) == 0)
capfilter &= ~CPU_CAP_SSE3;
else if(len == 6 && al::strncasecmp(str, "sse4.1", len) == 0)
capfilter &= ~CPU_CAP_SSE4_1;
else if(len == 4 && al::strncasecmp(str, "neon", len) == 0)
capfilter &= ~CPU_CAP_NEON;
else
WARN("Invalid CPU extension \"%s\"\n", str);
} while(next++);
}
}
FillCPUCaps(capfilter);
#ifdef _WIN32
#define DEF_MIXER_PRIO 1
#else
#define DEF_MIXER_PRIO 0
#endif
RTPrioLevel = ConfigValueInt(nullptr, nullptr, "rt-prio").value_or(DEF_MIXER_PRIO);
#undef DEF_MIXER_PRIO
aluInit();
aluInitMixer();
auto traperr = al::getenv("ALSOFT_TRAP_ERROR");
if(traperr && (al::strcasecmp(traperr->c_str(), "true") == 0
|| std::strtol(traperr->c_str(), nullptr, 0) == 1))
{
TrapALError = true;
TrapALCError = true;
}
else
{
traperr = al::getenv("ALSOFT_TRAP_AL_ERROR");
if(traperr)
TrapALError = al::strcasecmp(traperr->c_str(), "true") == 0
|| strtol(traperr->c_str(), nullptr, 0) == 1;
else
TrapALError = !!GetConfigValueBool(nullptr, nullptr, "trap-al-error", false);
traperr = al::getenv("ALSOFT_TRAP_ALC_ERROR");
if(traperr)
TrapALCError = al::strcasecmp(traperr->c_str(), "true") == 0
|| strtol(traperr->c_str(), nullptr, 0) == 1;
else
TrapALCError = !!GetConfigValueBool(nullptr, nullptr, "trap-alc-error", false);
}
if(auto boostopt = ConfigValueFloat(nullptr, "reverb", "boost"))
{
const float valf{std::isfinite(*boostopt) ? clampf(*boostopt, -24.0f, 24.0f) : 0.0f};
ReverbBoost *= std::pow(10.0f, valf / 20.0f);
}
auto devopt = al::getenv("ALSOFT_DRIVERS");
if(devopt || (devopt=ConfigValueStr(nullptr, nullptr, "drivers")))
{
auto backendlist_cur = std::begin(BackendList);
bool endlist{true};
const char *next{devopt->c_str()};
do {
const char *devs{next};
while(isspace(devs[0]))
devs++;
next = strchr(devs, ',');
const bool delitem{devs[0] == '-'};
if(devs[0] == '-') devs++;
if(!devs[0] || devs[0] == ',')
{
endlist = false;
continue;
}
endlist = true;
size_t len{next ? (static_cast<size_t>(next-devs)) : strlen(devs)};
while(len > 0 && isspace(devs[len-1])) --len;
#ifdef HAVE_WASAPI
/* HACK: For backwards compatibility, convert backend references of
* mmdevapi to wasapi. This should eventually be removed.
*/
if(len == 8 && strncmp(devs, "mmdevapi", len) == 0)
{
devs = "wasapi";
len = 6;
}
#endif
auto find_backend = [devs,len](const BackendInfo &backend) -> bool
{ return len == strlen(backend.name) && strncmp(backend.name, devs, len) == 0; };
auto this_backend = std::find_if(std::begin(BackendList), BackendListEnd,
find_backend);
if(this_backend == BackendListEnd)
continue;
if(delitem)
BackendListEnd = std::move(this_backend+1, BackendListEnd, this_backend);
else
backendlist_cur = std::rotate(backendlist_cur, this_backend, this_backend+1);
} while(next++);
if(endlist)
BackendListEnd = backendlist_cur;
}
auto init_backend = [](BackendInfo &backend) -> bool
{
if(PlaybackFactory && CaptureFactory)
return true;
BackendFactory &factory = backend.getFactory();
if(!factory.init())
{
WARN("Failed to initialize backend \"%s\"\n", backend.name);
return true;
}
TRACE("Initialized backend \"%s\"\n", backend.name);
if(!PlaybackFactory && factory.querySupport(BackendType::Playback))
{
PlaybackFactory = &factory;
TRACE("Added \"%s\" for playback\n", backend.name);
}
if(!CaptureFactory && factory.querySupport(BackendType::Capture))
{
CaptureFactory = &factory;
TRACE("Added \"%s\" for capture\n", backend.name);
}
return false;
};
BackendListEnd = std::remove_if(std::begin(BackendList), BackendListEnd, init_backend);
LoopbackBackendFactory::getFactory().init();
if(!PlaybackFactory)
WARN("No playback backend available!\n");
if(!CaptureFactory)
WARN("No capture backend available!\n");
if(auto exclopt = ConfigValueStr(nullptr, nullptr, "excludefx"))
{
const char *next{exclopt->c_str()};
do {
const char *str{next};
next = strchr(str, ',');
if(!str[0] || next == str)
continue;
size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
for(const EffectList &effectitem : gEffectList)
{
if(len == strlen(effectitem.name) &&
strncmp(effectitem.name, str, len) == 0)
DisabledEffects[effectitem.type] = AL_TRUE;
}
} while(next++);
}
InitEffect(&DefaultEffect);
auto defrevopt = al::getenv("ALSOFT_DEFAULT_REVERB");
if(defrevopt || (defrevopt=ConfigValueStr(nullptr, nullptr, "default-reverb")))
LoadReverbPreset(defrevopt->c_str(), &DefaultEffect);
}
#define DO_INITCONFIG() std::call_once(alc_config_once, [](){alc_initconfig();})
/************************************************
* Device enumeration
************************************************/
void ProbeAllDevicesList()
{
DO_INITCONFIG();
std::lock_guard<std::recursive_mutex> _{ListLock};
alcAllDevicesList.clear();
if(PlaybackFactory)
PlaybackFactory->probe(DevProbe::Playback, &alcAllDevicesList);
}
void ProbeCaptureDeviceList()
{
DO_INITCONFIG();
std::lock_guard<std::recursive_mutex> _{ListLock};
alcCaptureDeviceList.clear();
if(CaptureFactory)
CaptureFactory->probe(DevProbe::Capture, &alcCaptureDeviceList);
}
} // namespace
/* Mixing thread piority level */
ALint RTPrioLevel;
FILE *gLogFile{stderr};
#ifdef _DEBUG
LogLevel gLogLevel{LogWarning};
#else
LogLevel gLogLevel{LogError};
#endif
/************************************************
* Library initialization
************************************************/
#if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC)
BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/)
{
switch(reason)
{
case DLL_PROCESS_ATTACH:
/* Pin the DLL so we won't get unloaded until the process terminates */
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
reinterpret_cast<WCHAR*>(module), &module);
break;
}
return TRUE;
}
#endif
/************************************************
* Device format information
************************************************/
const ALCchar *DevFmtTypeString(DevFmtType type) noexcept
{
switch(type)
{
case DevFmtByte: return "Signed Byte";
case DevFmtUByte: return "Unsigned Byte";
case DevFmtShort: return "Signed Short";
case DevFmtUShort: return "Unsigned Short";
case DevFmtInt: return "Signed Int";
case DevFmtUInt: return "Unsigned Int";
case DevFmtFloat: return "Float";
}
return "(unknown type)";
}
const ALCchar *DevFmtChannelsString(DevFmtChannels chans) noexcept
{
switch(chans)
{
case DevFmtMono: return "Mono";
case DevFmtStereo: return "Stereo";
case DevFmtQuad: return "Quadraphonic";
case DevFmtX51: return "5.1 Surround";
case DevFmtX51Rear: return "5.1 Surround (Rear)";
case DevFmtX61: return "6.1 Surround";
case DevFmtX71: return "7.1 Surround";
case DevFmtAmbi3D: return "Ambisonic 3D";
}
return "(unknown channels)";
}
ALuint BytesFromDevFmt(DevFmtType type) noexcept
{
switch(type)
{
case DevFmtByte: return sizeof(ALbyte);
case DevFmtUByte: return sizeof(ALubyte);
case DevFmtShort: return sizeof(ALshort);
case DevFmtUShort: return sizeof(ALushort);
case DevFmtInt: return sizeof(ALint);
case DevFmtUInt: return sizeof(ALuint);
case DevFmtFloat: return sizeof(ALfloat);
}
return 0;
}
ALuint ChannelsFromDevFmt(DevFmtChannels chans, ALuint ambiorder) noexcept
{
switch(chans)
{
case DevFmtMono: return 1;
case DevFmtStereo: return 2;
case DevFmtQuad: return 4;
case DevFmtX51: return 6;
case DevFmtX51Rear: return 6;
case DevFmtX61: return 7;
case DevFmtX71: return 8;
case DevFmtAmbi3D: return (ambiorder+1) * (ambiorder+1);
}
return 0;
}
namespace {
struct DevFmtPair { DevFmtChannels chans; DevFmtType type; };
al::optional<DevFmtPair> DecomposeDevFormat(ALenum format)
{
static const struct {
ALenum format;
DevFmtChannels channels;
DevFmtType type;
} list[] = {
{ AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
{ AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
{ AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
{ AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
{ AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
{ AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
{ AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
{ AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
{ AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
{ AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
{ AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
{ AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
{ AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
{ AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
{ AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
{ AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
{ AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
{ AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
};
for(const auto &item : list)
{
if(item.format == format)
return al::make_optional(DevFmtPair{item.channels, item.type});
}
return al::nullopt;
}
bool IsValidALCType(ALCenum type)
{
switch(type)
{
case ALC_BYTE_SOFT:
case ALC_UNSIGNED_BYTE_SOFT:
case ALC_SHORT_SOFT:
case ALC_UNSIGNED_SHORT_SOFT:
case ALC_INT_SOFT:
case ALC_UNSIGNED_INT_SOFT:
case ALC_FLOAT_SOFT:
return true;
}
return false;
}
bool IsValidALCChannels(ALCenum channels)
{
switch(channels)
{
case ALC_MONO_SOFT:
case ALC_STEREO_SOFT:
case ALC_QUAD_SOFT:
case ALC_5POINT1_SOFT:
case ALC_6POINT1_SOFT:
case ALC_7POINT1_SOFT:
case ALC_BFORMAT3D_SOFT:
return true;
}
return false;
}
bool IsValidAmbiLayout(ALCenum layout)
{
switch(layout)
{
case ALC_ACN_SOFT:
case ALC_FUMA_SOFT:
return true;
}
return false;
}
bool IsValidAmbiScaling(ALCenum scaling)
{
switch(scaling)
{
case ALC_N3D_SOFT:
case ALC_SN3D_SOFT:
case ALC_FUMA_SOFT:
return true;
}
return false;
}
/* Downmixing channel arrays, to map the given format's missing channels to
* existing ones. Based on Wine's DSound downmix values, which are based on
* PulseAudio's.
*/
const std::array<InputRemixMap,7> MonoDownmix{{
{ FrontLeft, {{{FrontCenter, 0.5f}, {LFE, 0.0f}}} },
{ FrontRight, {{{FrontCenter, 0.5f}, {LFE, 0.0f}}} },
{ SideLeft, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} },
{ SideRight, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} },
{ BackLeft, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} },
{ BackRight, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} },
{ BackCenter, {{{FrontCenter, 1.0f/9.0f}, {LFE, 0.0f}}} },
}};
const std::array<InputRemixMap,6> StereoDownmix{{
{ FrontCenter, {{{FrontLeft, 0.5f}, {FrontRight, 0.5f}}} },
{ SideLeft, {{{FrontLeft, 1.0f/9.0f}, {FrontRight, 0.0f}}} },
{ SideRight, {{{FrontLeft, 0.0f}, {FrontRight, 1.0f/9.0f}}} },
{ BackLeft, {{{FrontLeft, 1.0f/9.0f}, {FrontRight, 0.0f}}} },
{ BackRight, {{{FrontLeft, 0.0f}, {FrontRight, 1.0f/9.0f}}} },
{ BackCenter, {{{FrontLeft, 0.5f/9.0f}, {FrontRight, 0.5f/9.0f}}} },
}};
const std::array<InputRemixMap,4> QuadDownmix{{
{ FrontCenter, {{{FrontLeft, 0.5f}, {FrontRight, 0.5f}}} },
{ SideLeft, {{{FrontLeft, 0.5f}, {BackLeft, 0.5f}}} },
{ SideRight, {{{FrontRight, 0.5f}, {BackRight, 0.5f}}} },
{ BackCenter, {{{BackLeft, 0.5f}, {BackRight, 0.5f}}} },
}};
const std::array<InputRemixMap,3> X51Downmix{{
{ BackLeft, {{{SideLeft, 1.0f}, {SideRight, 0.0f}}} },
{ BackRight, {{{SideLeft, 0.0f}, {SideRight, 1.0f}}} },
{ BackCenter, {{{SideLeft, 0.5f}, {SideRight, 0.5f}}} },
}};
const std::array<InputRemixMap,3> X51RearDownmix{{
{ SideLeft, {{{BackLeft, 1.0f}, {BackRight, 0.0f}}} },
{ SideRight, {{{BackLeft, 0.0f}, {BackRight, 1.0f}}} },
{ BackCenter, {{{BackLeft, 0.5f}, {BackRight, 0.5f}}} },
}};
const std::array<InputRemixMap,2> X61Downmix{{
{ BackLeft, {{{BackCenter, 0.5f}, {SideLeft, 0.5f}}} },
{ BackRight, {{{BackCenter, 0.5f}, {SideRight, 0.5f}}} },
}};
const std::array<InputRemixMap,1> X71Downmix{{
{ BackCenter, {{{BackLeft, 0.5f}, {BackRight, 0.5f}}} },
}};
} // namespace
/************************************************
* Miscellaneous ALC helpers
************************************************/
/* SetDefaultWFXChannelOrder
*
* Sets the default channel order used by WaveFormatEx.
*/
void SetDefaultWFXChannelOrder(ALCdevice *device)
{
device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX);
switch(device->FmtChans)
{
case DevFmtMono:
device->RealOut.ChannelIndex[FrontCenter] = 0;
break;
case DevFmtStereo:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
break;
case DevFmtQuad:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
device->RealOut.ChannelIndex[BackLeft] = 2;
device->RealOut.ChannelIndex[BackRight] = 3;
break;
case DevFmtX51:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
device->RealOut.ChannelIndex[FrontCenter] = 2;
device->RealOut.ChannelIndex[LFE] = 3;
device->RealOut.ChannelIndex[SideLeft] = 4;
device->RealOut.ChannelIndex[SideRight] = 5;
break;
case DevFmtX51Rear:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
device->RealOut.ChannelIndex[FrontCenter] = 2;
device->RealOut.ChannelIndex[LFE] = 3;
device->RealOut.ChannelIndex[BackLeft] = 4;
device->RealOut.ChannelIndex[BackRight] = 5;
break;
case DevFmtX61:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
device->RealOut.ChannelIndex[FrontCenter] = 2;
device->RealOut.ChannelIndex[LFE] = 3;
device->RealOut.ChannelIndex[BackCenter] = 4;
device->RealOut.ChannelIndex[SideLeft] = 5;
device->RealOut.ChannelIndex[SideRight] = 6;
break;
case DevFmtX71:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
device->RealOut.ChannelIndex[FrontCenter] = 2;
device->RealOut.ChannelIndex[LFE] = 3;
device->RealOut.ChannelIndex[BackLeft] = 4;
device->RealOut.ChannelIndex[BackRight] = 5;
device->RealOut.ChannelIndex[SideLeft] = 6;
device->RealOut.ChannelIndex[SideRight] = 7;
break;
case DevFmtAmbi3D:
device->RealOut.ChannelIndex[Aux0] = 0;
if(device->mAmbiOrder > 0)
{
device->RealOut.ChannelIndex[Aux1] = 1;
device->RealOut.ChannelIndex[Aux2] = 2;
device->RealOut.ChannelIndex[Aux3] = 3;
}
if(device->mAmbiOrder > 1)
{
device->RealOut.ChannelIndex[Aux4] = 4;
device->RealOut.ChannelIndex[Aux5] = 5;
device->RealOut.ChannelIndex[Aux6] = 6;
device->RealOut.ChannelIndex[Aux7] = 7;
device->RealOut.ChannelIndex[Aux8] = 8;
}
if(device->mAmbiOrder > 2)
{
device->RealOut.ChannelIndex[Aux9] = 9;
device->RealOut.ChannelIndex[Aux10] = 10;
device->RealOut.ChannelIndex[Aux11] = 11;
device->RealOut.ChannelIndex[Aux12] = 12;
device->RealOut.ChannelIndex[Aux13] = 13;
device->RealOut.ChannelIndex[Aux14] = 14;
device->RealOut.ChannelIndex[Aux15] = 15;
}
break;
}
}
/* SetDefaultChannelOrder
*
* Sets the default channel order used by most non-WaveFormatEx-based APIs.
*/
void SetDefaultChannelOrder(ALCdevice *device)
{
device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX);
switch(device->FmtChans)
{
case DevFmtX51Rear:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
device->RealOut.ChannelIndex[BackLeft] = 2;
device->RealOut.ChannelIndex[BackRight] = 3;
device->RealOut.ChannelIndex[FrontCenter] = 4;
device->RealOut.ChannelIndex[LFE] = 5;
return;
case DevFmtX71:
device->RealOut.ChannelIndex[FrontLeft] = 0;
device->RealOut.ChannelIndex[FrontRight] = 1;
device->RealOut.ChannelIndex[BackLeft] = 2;
device->RealOut.ChannelIndex[BackRight] = 3;
device->RealOut.ChannelIndex[FrontCenter] = 4;
device->RealOut.ChannelIndex[LFE] = 5;
device->RealOut.ChannelIndex[SideLeft] = 6;
device->RealOut.ChannelIndex[SideRight] = 7;
return;
/* Same as WFX order */
case DevFmtMono:
case DevFmtStereo:
case DevFmtQuad:
case DevFmtX51:
case DevFmtX61:
case DevFmtAmbi3D:
SetDefaultWFXChannelOrder(device);
break;
}
}
void ALCcontext::processUpdates()
{
std::lock_guard<std::mutex> _{mPropLock};
if(mDeferUpdates.exchange(false))
{
/* Tell the mixer to stop applying updates, then wait for any active
* updating to finish, before providing updates.
*/
mHoldUpdates.store(true, std::memory_order_release);
while((mUpdateCount.load(std::memory_order_acquire)&1) != 0)
std::this_thread::yield();
if(!mPropsClean.test_and_set(std::memory_order_acq_rel))
UpdateContextProps(this);
if(!mListener.PropsClean.test_and_set(std::memory_order_acq_rel))
UpdateListenerProps(this);
UpdateAllEffectSlotProps(this);
UpdateAllSourceProps(this);
/* Now with all updates declared, let the mixer continue applying them
* so they all happen at once.
*/
mHoldUpdates.store(false, std::memory_order_release);
}
}
/* alcSetError
*
* Stores the latest ALC device error
*/
static void alcSetError(ALCdevice *device, ALCenum errorCode)
{
WARN("Error generated on device %p, code 0x%04x\n", decltype(std::declval<void*>()){device},
errorCode);
if(TrapALCError)
{
#ifdef _WIN32
/* DebugBreak() will cause an exception if there is no debugger */
if(IsDebuggerPresent())
DebugBreak();
#elif defined(SIGTRAP)
raise(SIGTRAP);
#endif
}
if(device)
device->LastError.store(errorCode);
else
LastNullDeviceError.store(errorCode);
}
static std::unique_ptr<Compressor> CreateDeviceLimiter(const ALCdevice *device, const float threshold)
{
return Compressor::Create(device->RealOut.Buffer.size(), static_cast<float>(device->Frequency),
AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f, 0.002f, 0.0f, 0.0f, threshold,
std::numeric_limits<float>::infinity(), 0.0f, 0.020f, 0.200f);
}
/* UpdateClockBase
*
* Updates the device's base clock time with however many samples have been
* done. This is used so frequency changes on the device don't cause the time
* to jump forward or back. Must not be called while the device is running/
* mixing.
*/
static inline void UpdateClockBase(ALCdevice *device)
{
IncrementRef(device->MixCount);
device->ClockBase += nanoseconds{seconds{device->SamplesDone}} / device->Frequency;
device->SamplesDone = 0;
IncrementRef(device->MixCount);
}
/* UpdateDeviceParams
*
* Updates device parameters according to the attribute list (caller is
* responsible for holding the list lock).
*/
static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
{
HrtfRequestMode hrtf_userreq{Hrtf_Default};
HrtfRequestMode hrtf_appreq{Hrtf_Default};
ALCenum gainLimiter{device->LimiterState};
const ALCuint old_sends{device->NumAuxSends};
ALCuint new_sends{device->NumAuxSends};
DevFmtChannels oldChans;
DevFmtType oldType;
ALboolean update_failed;
ALCsizei hrtf_id{-1};
ALCuint oldFreq;
if((!attrList || !attrList[0]) && device->Type == Loopback)
{
WARN("Missing attributes for loopback device\n");
return ALC_INVALID_VALUE;
}
// Check for attributes
if(attrList && attrList[0])
{
ALCenum alayout{AL_NONE};
ALCenum ascale{AL_NONE};
ALCenum schans{AL_NONE};
ALCenum stype{AL_NONE};
ALCsizei attrIdx{0};
ALCuint aorder{0};
ALCuint freq{0u};
ALuint numMono{device->NumMonoSources};
ALuint numStereo{device->NumStereoSources};
ALuint numSends{old_sends};
#define TRACE_ATTR(a, v) TRACE("%s = %d\n", #a, v)
while(attrList[attrIdx])
{
switch(attrList[attrIdx])
{
case ALC_FORMAT_CHANNELS_SOFT:
schans = attrList[attrIdx + 1];
TRACE_ATTR(ALC_FORMAT_CHANNELS_SOFT, schans);
break;
case ALC_FORMAT_TYPE_SOFT:
stype = attrList[attrIdx + 1];
TRACE_ATTR(ALC_FORMAT_TYPE_SOFT, stype);
break;
case ALC_FREQUENCY:
freq = static_cast<ALuint>(attrList[attrIdx + 1]);
TRACE_ATTR(ALC_FREQUENCY, freq);
break;
case ALC_AMBISONIC_LAYOUT_SOFT:
alayout = attrList[attrIdx + 1];
TRACE_ATTR(ALC_AMBISONIC_LAYOUT_SOFT, alayout);
break;
case ALC_AMBISONIC_SCALING_SOFT:
ascale = attrList[attrIdx + 1];
TRACE_ATTR(ALC_AMBISONIC_SCALING_SOFT, ascale);
break;
case ALC_AMBISONIC_ORDER_SOFT:
aorder = static_cast<ALuint>(attrList[attrIdx + 1]);
TRACE_ATTR(ALC_AMBISONIC_ORDER_SOFT, aorder);
break;
case ALC_MONO_SOURCES:
numMono = static_cast<ALuint>(attrList[attrIdx + 1]);
TRACE_ATTR(ALC_MONO_SOURCES, numMono);
if(numMono > INT_MAX) numMono = 0;
break;
case ALC_STEREO_SOURCES:
numStereo = static_cast<ALuint>(attrList[attrIdx + 1]);
TRACE_ATTR(ALC_STEREO_SOURCES, numStereo);
if(numStereo > INT_MAX) numStereo = 0;
break;
case ALC_MAX_AUXILIARY_SENDS:
numSends = static_cast<ALuint>(attrList[attrIdx + 1]);
TRACE_ATTR(ALC_MAX_AUXILIARY_SENDS, numSends);
if(numSends > INT_MAX) numSends = 0;
else numSends = minu(numSends, MAX_SENDS);
break;
case ALC_HRTF_SOFT:
TRACE_ATTR(ALC_HRTF_SOFT, attrList[attrIdx + 1]);
if(attrList[attrIdx + 1] == ALC_FALSE)
hrtf_appreq = Hrtf_Disable;
else if(attrList[attrIdx + 1] == ALC_TRUE)
hrtf_appreq = Hrtf_Enable;
else
hrtf_appreq = Hrtf_Default;
break;
case ALC_HRTF_ID_SOFT:
hrtf_id = attrList[attrIdx + 1];
TRACE_ATTR(ALC_HRTF_ID_SOFT, hrtf_id);
break;
case ALC_OUTPUT_LIMITER_SOFT:
gainLimiter = attrList[attrIdx + 1];
TRACE_ATTR(ALC_OUTPUT_LIMITER_SOFT, gainLimiter);
break;
default:
TRACE("0x%04X = %d (0x%x)\n", attrList[attrIdx],
attrList[attrIdx + 1], attrList[attrIdx + 1]);
break;
}
attrIdx += 2;
}
#undef TRACE_ATTR
const bool loopback{device->Type == Loopback};
if(loopback)
{
if(!schans || !stype || !freq)
{
WARN("Missing format for loopback device\n");
return ALC_INVALID_VALUE;
}
if(!IsValidALCChannels(schans) || !IsValidALCType(stype) || freq < MIN_OUTPUT_RATE)
return ALC_INVALID_VALUE;
if(schans == ALC_BFORMAT3D_SOFT)
{
if(!alayout || !ascale || !aorder)
{
WARN("Missing ambisonic info for loopback device\n");
return ALC_INVALID_VALUE;
}
if(!IsValidAmbiLayout(alayout) || !IsValidAmbiScaling(ascale))
return ALC_INVALID_VALUE;
if(aorder < 1 || aorder > MAX_AMBI_ORDER)
return ALC_INVALID_VALUE;
if((alayout == ALC_FUMA_SOFT || ascale == ALC_FUMA_SOFT) && aorder > 3)
return ALC_INVALID_VALUE;
}
}
/* If a context is already running on the device, stop playback so the
* device attributes can be updated.
*/
if(device->Flags.get<DeviceRunning>())
device->Backend->stop();
device->Flags.unset<DeviceRunning>();
UpdateClockBase(device);
const char *devname{nullptr};
if(!loopback)
{
devname = device->DeviceName.c_str();
device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES;
device->UpdateSize = DEFAULT_UPDATE_SIZE;
device->Frequency = DEFAULT_OUTPUT_RATE;
freq = ConfigValueUInt(devname, nullptr, "frequency").value_or(freq);
if(freq < 1)
device->Flags.unset<FrequencyRequest>();
else
{
freq = maxu(freq, MIN_OUTPUT_RATE);
device->UpdateSize = (device->UpdateSize*freq + device->Frequency/2) /
device->Frequency;
device->BufferSize = (device->BufferSize*freq + device->Frequency/2) /
device->Frequency;
device->Frequency = freq;
device->Flags.set<FrequencyRequest>();
}
if(auto persizeopt = ConfigValueUInt(devname, nullptr, "period_size"))
device->UpdateSize = clampu(*persizeopt, 64, 8192);
if(auto peropt = ConfigValueUInt(devname, nullptr, "periods"))
device->BufferSize = device->UpdateSize * clampu(*peropt, 2, 16);
else
device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2);
}
else
{
device->Frequency = freq;
device->FmtChans = static_cast<DevFmtChannels>(schans);
device->FmtType = static_cast<DevFmtType>(stype);
if(schans == ALC_BFORMAT3D_SOFT)
{
device->mAmbiOrder = aorder;
device->mAmbiLayout = static_cast<AmbiLayout>(alayout);
device->mAmbiScale = static_cast<AmbiNorm>(ascale);
}
}
if(numMono > INT_MAX-numStereo)
numMono = INT_MAX-numStereo;
numMono += numStereo;
if(auto srcsopt = ConfigValueUInt(devname, nullptr, "sources"))
{
if(*srcsopt <= 0) numMono = 256;
else numMono = *srcsopt;
}
else
numMono = maxu(numMono, 256);
numStereo = minu(numStereo, numMono);
numMono -= numStereo;
device->SourcesMax = numMono + numStereo;
device->NumMonoSources = numMono;
device->NumStereoSources = numStereo;
if(auto sendsopt = ConfigValueInt(devname, nullptr, "sends"))
new_sends = minu(numSends, static_cast<ALuint>(clampi(*sendsopt, 0, MAX_SENDS)));
else
new_sends = numSends;
}
if(device->Flags.get<DeviceRunning>())
return ALC_NO_ERROR;
device->AvgSpeakerDist = 0.0f;
device->Uhj_Encoder = nullptr;
device->AmbiDecoder = nullptr;
device->Bs2b = nullptr;
device->PostProcess = nullptr;
device->Stablizer = nullptr;
device->Limiter = nullptr;
device->ChannelDelay.clear();
std::fill(std::begin(device->HrtfAccumData), std::end(device->HrtfAccumData), float2{});
device->Dry.AmbiMap.fill(BFChannelConfig{});
device->Dry.Buffer = {};
std::fill(std::begin(device->NumChannelsPerOrder), std::end(device->NumChannelsPerOrder), 0u);
device->RealOut.RemixMap = {};
device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX);
device->RealOut.Buffer = {};
device->MixBuffer.clear();
device->MixBuffer.shrink_to_fit();
UpdateClockBase(device);
device->FixedLatency = nanoseconds::zero();
device->DitherDepth = 0.0f;
device->DitherSeed = DitherRNGSeed;
/*************************************************************************
* Update device format request if HRTF is requested
*/
device->HrtfStatus = ALC_HRTF_DISABLED_SOFT;
if(device->Type != Loopback)
{
if(auto hrtfopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "hrtf"))
{
const char *hrtf{hrtfopt->c_str()};
if(al::strcasecmp(hrtf, "true") == 0)
hrtf_userreq = Hrtf_Enable;
else if(al::strcasecmp(hrtf, "false") == 0)
hrtf_userreq = Hrtf_Disable;
else if(al::strcasecmp(hrtf, "auto") != 0)
ERR("Unexpected hrtf value: %s\n", hrtf);
}
if(hrtf_userreq == Hrtf_Enable || (hrtf_userreq != Hrtf_Disable && hrtf_appreq == Hrtf_Enable))
{
device->FmtChans = DevFmtStereo;
device->Flags.set<ChannelsRequest>();
}
}
oldFreq = device->Frequency;
oldChans = device->FmtChans;
oldType = device->FmtType;
TRACE("Pre-reset: %s%s, %s%s, %s%uhz, %u / %u buffer\n",
device->Flags.get<ChannelsRequest>()?"*":"", DevFmtChannelsString(device->FmtChans),
device->Flags.get<SampleTypeRequest>()?"*":"", DevFmtTypeString(device->FmtType),
device->Flags.get<FrequencyRequest>()?"*":"", device->Frequency,
device->UpdateSize, device->BufferSize);
try {
if(device->Backend->reset() == false)
return ALC_INVALID_DEVICE;
}
catch(std::exception &e) {
ERR("Device reset failed: %s\n", e.what());
return ALC_INVALID_DEVICE;
}
if(device->FmtChans != oldChans && device->Flags.get<ChannelsRequest>())
{
ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans),
DevFmtChannelsString(device->FmtChans));
device->Flags.unset<ChannelsRequest>();
}
if(device->FmtType != oldType && device->Flags.get<SampleTypeRequest>())
{
ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType),
DevFmtTypeString(device->FmtType));
device->Flags.unset<SampleTypeRequest>();
}
if(device->Frequency != oldFreq && device->Flags.get<FrequencyRequest>())
{
WARN("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency);
device->Flags.unset<FrequencyRequest>();
}
TRACE("Post-reset: %s, %s, %uhz, %u / %u buffer\n",
DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
device->Frequency, device->UpdateSize, device->BufferSize);
switch(device->FmtChans)
{
case DevFmtMono: device->RealOut.RemixMap = MonoDownmix; break;
case DevFmtStereo: device->RealOut.RemixMap = StereoDownmix; break;
case DevFmtQuad: device->RealOut.RemixMap = QuadDownmix; break;
case DevFmtX51: device->RealOut.RemixMap = X51Downmix; break;
case DevFmtX51Rear: device->RealOut.RemixMap = X51RearDownmix; break;
case DevFmtX61: device->RealOut.RemixMap = X61Downmix; break;
case DevFmtX71: device->RealOut.RemixMap = X71Downmix; break;
case DevFmtAmbi3D: break;
}
aluInitRenderer(device, hrtf_id, hrtf_appreq, hrtf_userreq);
device->NumAuxSends = new_sends;
TRACE("Max sources: %d (%d + %d), effect slots: %d, sends: %d\n",
device->SourcesMax, device->NumMonoSources, device->NumStereoSources,
device->AuxiliaryEffectSlotMax, device->NumAuxSends);
/* Enable the stablizer only for formats that have front-left, front-right,
* and front-center outputs.
*/
switch(device->FmtChans)
{
case DevFmtX51:
case DevFmtX51Rear:
case DevFmtX61:
case DevFmtX71:
if(GetConfigValueBool(device->DeviceName.c_str(), nullptr, "front-stablizer", 0))
{
auto stablizer = al::make_unique<FrontStablizer>();
/* Initialize band-splitting filters for the front-left and front-
* right channels, with a crossover at 5khz (could be higher).
*/
const ALfloat scale{5000.0f / static_cast<ALfloat>(device->Frequency)};
stablizer->LFilter.init(scale);
stablizer->RFilter = stablizer->LFilter;
device->Stablizer = std::move(stablizer);
/* NOTE: Don't know why this has to be "copied" into a local static
* constexpr variable to avoid a reference on
* FrontStablizer::DelayLength...
*/
constexpr size_t StablizerDelay{FrontStablizer::DelayLength};
device->FixedLatency += nanoseconds{seconds{StablizerDelay}} / device->Frequency;
}
break;
case DevFmtMono:
case DevFmtStereo:
case DevFmtQuad:
case DevFmtAmbi3D:
break;
}
TRACE("Front stablizer %s\n", device->Stablizer ? "enabled" : "disabled");
if(GetConfigValueBool(device->DeviceName.c_str(), nullptr, "dither", 1))
{
ALint depth{
ConfigValueInt(device->DeviceName.c_str(), nullptr, "dither-depth").value_or(0)};
if(depth <= 0)
{
switch(device->FmtType)
{
case DevFmtByte:
case DevFmtUByte:
depth = 8;
break;
case DevFmtShort:
case DevFmtUShort:
depth = 16;
break;
case DevFmtInt:
case DevFmtUInt:
case DevFmtFloat:
break;
}
}
if(depth > 0)
{
depth = clampi(depth, 2, 24);
device->DitherDepth = std::pow(2.0f, static_cast<ALfloat>(depth-1));
}
}
if(!(device->DitherDepth > 0.0f))
TRACE("Dithering disabled\n");
else
TRACE("Dithering enabled (%d-bit, %g)\n", float2int(std::log2(device->DitherDepth)+0.5f)+1,
device->DitherDepth);
device->LimiterState = gainLimiter;
if(auto limopt = ConfigValueBool(device->DeviceName.c_str(), nullptr, "output-limiter"))
gainLimiter = *limopt ? ALC_TRUE : ALC_FALSE;
/* Valid values for gainLimiter are ALC_DONT_CARE_SOFT, ALC_TRUE, and
* ALC_FALSE. For ALC_DONT_CARE_SOFT, use the limiter for integer-based
* output (where samples must be clamped), and don't for floating-point
* (which can take unclamped samples).
*/
if(gainLimiter == ALC_DONT_CARE_SOFT)
{
switch(device->FmtType)
{
case DevFmtByte:
case DevFmtUByte:
case DevFmtShort:
case DevFmtUShort:
case DevFmtInt:
case DevFmtUInt:
gainLimiter = ALC_TRUE;
break;
case DevFmtFloat:
gainLimiter = ALC_FALSE;
break;
}
}
if(gainLimiter == ALC_FALSE)
TRACE("Output limiter disabled\n");
else
{
ALfloat thrshld = 1.0f;
switch(device->FmtType)
{
case DevFmtByte:
case DevFmtUByte:
thrshld = 127.0f / 128.0f;
break;
case DevFmtShort:
case DevFmtUShort:
thrshld = 32767.0f / 32768.0f;
break;
case DevFmtInt:
case DevFmtUInt:
case DevFmtFloat:
break;
}
if(device->DitherDepth > 0.0f)
thrshld -= 1.0f / device->DitherDepth;
const float thrshld_dB{std::log10(thrshld) * 20.0f};
auto limiter = CreateDeviceLimiter(device, thrshld_dB);
/* Convert the lookahead from samples to nanosamples to nanoseconds. */
device->FixedLatency += nanoseconds{seconds{limiter->getLookAhead()}} / device->Frequency;
device->Limiter = std::move(limiter);
TRACE("Output limiter enabled, %.4fdB limit\n", thrshld_dB);
}
TRACE("Fixed device latency: %" PRId64 "ns\n", int64_t{device->FixedLatency.count()});
/* Need to delay returning failure until replacement Send arrays have been
* allocated with the appropriate size.
*/
update_failed = AL_FALSE;
FPUCtl mixer_mode{};
for(ALCcontext *context : *device->mContexts.load())
{
if(context->mDefaultSlot)
{
ALeffectslot *slot = context->mDefaultSlot.get();
aluInitEffectPanning(slot, device);
EffectState *state{slot->Effect.State};
state->mOutTarget = device->Dry.Buffer;
if(state->deviceUpdate(device) == AL_FALSE)
update_failed = AL_TRUE;
else
UpdateEffectSlotProps(slot, context);
}
std::unique_lock<std::mutex> proplock{context->mPropLock};
std::unique_lock<std::mutex> slotlock{context->mEffectSlotLock};
if(ALeffectslotArray *curarray{context->mActiveAuxSlots.load(std::memory_order_relaxed)})
std::fill_n(curarray->end(), curarray->size(), nullptr);
for(auto &sublist : context->mEffectSlotList)
{
uint64_t usemask = ~sublist.FreeMask;
while(usemask)
{
ALsizei idx = CTZ64(usemask);
ALeffectslot *slot = sublist.EffectSlots + idx;
usemask &= ~(1_u64 << idx);
aluInitEffectPanning(slot, device);
EffectState *state{slot->Effect.State};
state->mOutTarget = device->Dry.Buffer;
if(state->deviceUpdate(device) == AL_FALSE)
update_failed = AL_TRUE;
else
UpdateEffectSlotProps(slot, context);
}
}
slotlock.unlock();
std::unique_lock<std::mutex> srclock{context->mSourceLock};
for(auto &sublist : context->mSourceList)
{
uint64_t usemask = ~sublist.FreeMask;
while(usemask)
{
ALsizei idx = CTZ64(usemask);
ALsource *source = sublist.Sources + idx;
usemask &= ~(1_u64 << idx);
if(old_sends != device->NumAuxSends)
{
if(source->Send.size() > device->NumAuxSends)
{
auto clear_send = [](ALsource::SendData &send) -> void
{
if(send.Slot)
DecrementRef(send.Slot->ref);
send.Slot = nullptr;
};
auto send_begin = source->Send.begin() +
static_cast<ptrdiff_t>(device->NumAuxSends);
std::for_each(send_begin, source->Send.end(), clear_send);
}
source->Send.resize(device->NumAuxSends,
{nullptr, 1.0f, 1.0f, LOWPASSFREQREF, 1.0f, HIGHPASSFREQREF});
source->Send.shrink_to_fit();
}
source->PropsClean.clear(std::memory_order_release);
}
}
/* Clear any pre-existing voice property structs, in case the number of
* auxiliary sends is changing. Active sources will have updates
* respecified in UpdateAllSourceProps.
*/
ALvoiceProps *vprops{context->mFreeVoiceProps.exchange(nullptr, std::memory_order_acq_rel)};
while(vprops)
{
ALvoiceProps *next = vprops->next.load(std::memory_order_relaxed);
delete vprops;
vprops = next;
}
if(device->NumAuxSends < old_sends)
{
const ALuint num_sends{device->NumAuxSends};
/* Clear extraneous property set sends. */
auto clear_sends = [num_sends](ALvoice &voice) -> void
{
std::fill(std::begin(voice.mProps.Send)+num_sends, std::end(voice.mProps.Send),
ALvoiceProps::SendData{});
std::fill(voice.mSend.begin()+num_sends, voice.mSend.end(), ALvoice::TargetData{});
auto clear_chan_sends = [num_sends](ALvoice::ChannelData &chandata) -> void
{
std::fill(chandata.mWetParams.begin()+num_sends, chandata.mWetParams.end(),
SendParams{});
};
std::for_each(voice.mChans.begin(), voice.mChans.end(), clear_chan_sends);
};
std::for_each(context->mVoices.begin(), context->mVoices.end(), clear_sends);
}
auto reset_voice = [device](ALvoice &voice) -> void
{
delete voice.mUpdate.exchange(nullptr, std::memory_order_acq_rel);
/* Force the voice to stopped if it was stopping. */
ALvoice::State vstate{ALvoice::Stopping};
voice.mPlayState.compare_exchange_strong(vstate, ALvoice::Stopped,
std::memory_order_acquire, std::memory_order_acquire);
if(voice.mSourceID.load(std::memory_order_relaxed) == 0u)
return;
voice.mStep = 0;
voice.mFlags |= VOICE_IS_FADING;
if((voice.mFmtChannels == FmtBFormat2D || voice.mFmtChannels == FmtBFormat3D)
&& device->mAmbiOrder > voice.mAmbiOrder)
{
const uint8_t *OrderFromChan{(voice.mFmtChannels == FmtBFormat2D) ?
AmbiIndex::OrderFrom2DChannel.data() :
AmbiIndex::OrderFromChannel.data()};
const BandSplitter splitter{400.0f / static_cast<float>(device->Frequency)};
const auto scales = BFormatDec::GetHFOrderScales(voice.mAmbiOrder,
device->mAmbiOrder);
auto init_ambi = [device,&scales,&OrderFromChan,splitter](ALvoice::ChannelData &chandata) -> void
{
chandata.mPrevSamples.fill(0.0f);
chandata.mAmbiScale = scales[*(OrderFromChan++)];
chandata.mAmbiSplitter = splitter;
chandata.mDryParams = DirectParams{};
std::fill_n(chandata.mWetParams.begin(), device->NumAuxSends, SendParams{});
};
std::for_each(voice.mChans.begin(), voice.mChans.begin()+voice.mNumChannels,
init_ambi);
voice.mFlags |= VOICE_IS_AMBISONIC;
}
else
{
/* Clear previous samples. */
auto clear_prevs = [device](ALvoice::ChannelData &chandata) -> void
{
chandata.mPrevSamples.fill(0.0f);
chandata.mDryParams = DirectParams{};
std::fill_n(chandata.mWetParams.begin(), device->NumAuxSends, SendParams{});
};
std::for_each(voice.mChans.begin(), voice.mChans.begin()+voice.mNumChannels,
clear_prevs);
voice.mFlags &= ~VOICE_IS_AMBISONIC;
}
if(device->AvgSpeakerDist > 0.0f)
{
/* Reinitialize the NFC filters for new parameters. */
const ALfloat w1{SPEEDOFSOUNDMETRESPERSEC /
(device->AvgSpeakerDist * static_cast<float>(device->Frequency))};
auto init_nfc = [w1](ALvoice::ChannelData &chandata) -> void
{ chandata.mDryParams.NFCtrlFilter.init(w1); };
std::for_each(voice.mChans.begin(), voice.mChans.begin()+voice.mNumChannels,
init_nfc);
}
};
std::for_each(context->mVoices.begin(), context->mVoices.end(), reset_voice);
srclock.unlock();
context->mPropsClean.test_and_set(std::memory_order_release);
UpdateContextProps(context);
context->mListener.PropsClean.test_and_set(std::memory_order_release);
UpdateListenerProps(context);
UpdateAllSourceProps(context);
}
mixer_mode.leave();
if(update_failed)
return ALC_INVALID_DEVICE;
if(!device->Flags.get<DevicePaused>())
{
try {
auto backend = device->Backend.get();
if(!backend->start())
throw al::backend_exception{ALC_INVALID_DEVICE, "Backend error"};
device->Flags.set<DeviceRunning>();
}
catch(al::backend_exception& e) {
WARN("Failed to start playback: %s\n", e.what());
return ALC_INVALID_DEVICE;
}
}
return ALC_NO_ERROR;
}
ALCdevice::ALCdevice(DeviceType type) : Type{type}, mContexts{&EmptyContextArray}
{
}
/* ALCdevice::~ALCdevice
*
* Frees the device structure, and destroys any objects the app failed to
* delete. Called once there's no more references on the device.
*/
ALCdevice::~ALCdevice()
{
TRACE("Freeing device %p\n", decltype(std::declval<void*>()){this});
Backend = nullptr;
size_t count{std::accumulate(BufferList.cbegin(), BufferList.cend(), size_t{0u},
[](size_t cur, const BufferSubList &sublist) noexcept -> size_t
{ return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
)};
if(count > 0)
WARN("%zu Buffer%s not deleted\n", count, (count==1)?"":"s");
count = std::accumulate(EffectList.cbegin(), EffectList.cend(), size_t{0u},
[](size_t cur, const EffectSubList &sublist) noexcept -> size_t
{ return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
);
if(count > 0)
WARN("%zu Effect%s not deleted\n", count, (count==1)?"":"s");
count = std::accumulate(FilterList.cbegin(), FilterList.cend(), size_t{0u},
[](size_t cur, const FilterSubList &sublist) noexcept -> size_t
{ return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
);
if(count > 0)
WARN("%zu Filter%s not deleted\n", count, (count==1)?"":"s");
if(mHrtf)
mHrtf->DecRef();
mHrtf = nullptr;
auto *oldarray = mContexts.exchange(nullptr, std::memory_order_relaxed);
if(oldarray != &EmptyContextArray) delete oldarray;
}
/* VerifyDevice
*
* Checks if the device handle is valid, and returns a new reference if so.
*/
static DeviceRef VerifyDevice(ALCdevice *device)
{
std::lock_guard<std::recursive_mutex> _{ListLock};
auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
if(iter != DeviceList.end() && *iter == device)
{
(*iter)->add_ref();
return DeviceRef{*iter};
}
return nullptr;
}
ALCcontext::ALCcontext(al::intrusive_ptr<ALCdevice> device) : mDevice{std::move(device)}
{
mPropsClean.test_and_set(std::memory_order_relaxed);
}
ALCcontext::~ALCcontext()
{
TRACE("Freeing context %p\n", decltype(std::declval<void*>()){this});
size_t count{0};
ALcontextProps *cprops{mUpdate.exchange(nullptr, std::memory_order_relaxed)};
if(cprops)
{
++count;
delete cprops;
}
cprops = mFreeContextProps.exchange(nullptr, std::memory_order_acquire);
while(cprops)
{
ALcontextProps *next{cprops->next.load(std::memory_order_relaxed)};
delete cprops;
cprops = next;
++count;
}
TRACE("Freed %zu context property object%s\n", count, (count==1)?"":"s");
count = std::accumulate(mSourceList.cbegin(), mSourceList.cend(), size_t{0u},
[](size_t cur, const SourceSubList &sublist) noexcept -> size_t
{ return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
);
if(count > 0)
WARN("%zu Source%s not deleted\n", count, (count==1)?"":"s");
mSourceList.clear();
mNumSources = 0;
count = 0;
ALeffectslotProps *eprops{mFreeEffectslotProps.exchange(nullptr, std::memory_order_acquire)};
while(eprops)
{
ALeffectslotProps *next{eprops->next.load(std::memory_order_relaxed)};
if(eprops->State) eprops->State->release();
delete eprops;
eprops = next;
++count;
}
TRACE("Freed %zu AuxiliaryEffectSlot property object%s\n", count, (count==1)?"":"s");
if(ALeffectslotArray *curarray{mActiveAuxSlots.exchange(nullptr, std::memory_order_relaxed)})
{
al::destroy_n(curarray->end(), curarray->size());
delete curarray;
}
mDefaultSlot = nullptr;
count = std::accumulate(mEffectSlotList.cbegin(), mEffectSlotList.cend(), size_t{0u},
[](size_t cur, const EffectSlotSubList &sublist) noexcept -> size_t
{ return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
);
if(count > 0)
WARN("%zu AuxiliaryEffectSlot%s not deleted\n", count, (count==1)?"":"s");
mEffectSlotList.clear();
mNumEffectSlots = 0;
count = 0;
ALvoiceProps *vprops{mFreeVoiceProps.exchange(nullptr, std::memory_order_acquire)};
while(vprops)
{
ALvoiceProps *next{vprops->next.load(std::memory_order_relaxed)};
delete vprops;
vprops = next;
++count;
}
TRACE("Freed %zu voice property object%s\n", count, (count==1)?"":"s");
mVoices.clear();
count = 0;
ALlistenerProps *lprops{mListener.Params.Update.exchange(nullptr, std::memory_order_relaxed)};
if(lprops)
{
++count;
delete lprops;
}
lprops = mFreeListenerProps.exchange(nullptr, std::memory_order_acquire);
while(lprops)
{
ALlistenerProps *next{lprops->next.load(std::memory_order_relaxed)};
delete lprops;
lprops = next;
++count;
}
TRACE("Freed %zu listener property object%s\n", count, (count==1)?"":"s");
if(mAsyncEvents)
{
count = 0;
auto evt_vec = mAsyncEvents->getReadVector();
if(evt_vec.first.len > 0)
{
al::destroy_n(reinterpret_cast<AsyncEvent*>(evt_vec.first.buf), evt_vec.first.len);
count += evt_vec.first.len;
}
if(evt_vec.second.len > 0)
{
al::destroy_n(reinterpret_cast<AsyncEvent*>(evt_vec.second.buf), evt_vec.second.len);
count += evt_vec.second.len;
}
if(count > 0)
TRACE("Destructed %zu orphaned event%s\n", count, (count==1)?"":"s");
mAsyncEvents->readAdvance(count);
}
}
void ALCcontext::init()
{
if(DefaultEffect.type != AL_EFFECT_NULL && mDevice->Type == Playback)
{
mDefaultSlot = std::unique_ptr<ALeffectslot>{new ALeffectslot{}};
if(InitEffectSlot(mDefaultSlot.get()) == AL_NO_ERROR)
aluInitEffectPanning(mDefaultSlot.get(), mDevice.get());
else
{
mDefaultSlot = nullptr;
ERR("Failed to initialize the default effect slot\n");
}
}
ALeffectslotArray *auxslots;
if(!mDefaultSlot)
auxslots = ALeffectslot::CreatePtrArray(0);
else
{
auxslots = ALeffectslot::CreatePtrArray(1);
(*auxslots)[0] = mDefaultSlot.get();
}
mActiveAuxSlots.store(auxslots, std::memory_order_relaxed);
mExtensionList = alExtList;
mListener.Params.Matrix = alu::Matrix::Identity();
mListener.Params.Velocity = alu::Vector{};
mListener.Params.Gain = mListener.Gain;
mListener.Params.MetersPerUnit = mListener.mMetersPerUnit;
mListener.Params.DopplerFactor = mDopplerFactor;
mListener.Params.SpeedOfSound = mSpeedOfSound * mDopplerVelocity;
mListener.Params.SourceDistanceModel = mSourceDistanceModel;
mListener.Params.mDistanceModel = mDistanceModel;
mAsyncEvents = RingBuffer::Create(511, sizeof(AsyncEvent), false);
StartEventThrd(this);
mVoices.reserve(256);
mVoices.resize(64);
}
bool ALCcontext::deinit()
{
if(LocalContext.get() == this)
{
WARN("%p released while current on thread\n", decltype(std::declval<void*>()){this});
LocalContext.set(nullptr);
release();
}
ALCcontext *origctx{this};
if(GlobalContext.compare_exchange_strong(origctx, nullptr))
release();
bool ret{};
/* First make sure this context exists in the device's list. */
auto *oldarray = mDevice->mContexts.load(std::memory_order_acquire);
if(auto toremove = static_cast<size_t>(std::count(oldarray->begin(), oldarray->end(), this)))
{
using ContextArray = al::FlexArray<ALCcontext*>;
auto alloc_ctx_array = [](const size_t count) -> ContextArray*
{
if(count == 0) return &EmptyContextArray;
return ContextArray::Create(count).release();
};
auto *newarray = alloc_ctx_array(oldarray->size() - toremove);
/* Copy the current/old context handles to the new array, excluding the
* given context.
*/
std::copy_if(oldarray->begin(), oldarray->end(), newarray->begin(),
std::bind(std::not_equal_to<ALCcontext*>{}, _1, this));
/* Store the new context array in the device. Wait for any current mix
* to finish before deleting the old array.
*/
mDevice->mContexts.store(newarray);
if(oldarray != &EmptyContextArray)
{
while((mDevice->MixCount.load(std::memory_order_acquire)&1))
std::this_thread::yield();
delete oldarray;
}
ret = !newarray->empty();
}
else
ret = !oldarray->empty();
StopEventThrd(this);
return ret;
}
/* VerifyContext
*
* Checks if the given context is valid, returning a new reference to it if so.
*/
static ContextRef VerifyContext(ALCcontext *context)
{
std::lock_guard<std::recursive_mutex> _{ListLock};
auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context);
if(iter != ContextList.end() && *iter == context)
{
(*iter)->add_ref();
return ContextRef{*iter};
}
return nullptr;
}
/* GetContextRef
*
* Returns a new reference to the currently active context for this thread.
*/
ContextRef GetContextRef(void)
{
ALCcontext *context{LocalContext.get()};
if(context)
context->add_ref();
else
{
std::lock_guard<std::recursive_mutex> _{ListLock};
context = GlobalContext.load(std::memory_order_acquire);
if(context) context->add_ref();
}
return ContextRef{context};
}
/************************************************
* Standard ALC functions
************************************************/
/* alcGetError
*
* Return last ALC generated error code for the given device
*/
ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(dev) return dev->LastError.exchange(ALC_NO_ERROR);
return LastNullDeviceError.exchange(ALC_NO_ERROR);
}
END_API_FUNC
/* alcSuspendContext
*
* Suspends updates for the given context
*/
ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *context)
START_API_FUNC
{
if(!SuspendDefers)
return;
ContextRef ctx{VerifyContext(context)};
if(!ctx)
alcSetError(nullptr, ALC_INVALID_CONTEXT);
else
ctx->deferUpdates();
}
END_API_FUNC
/* alcProcessContext
*
* Resumes processing updates for the given context
*/
ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *context)
START_API_FUNC
{
if(!SuspendDefers)
return;
ContextRef ctx{VerifyContext(context)};
if(!ctx)
alcSetError(nullptr, ALC_INVALID_CONTEXT);
else
ctx->processUpdates();
}
END_API_FUNC
/* alcGetString
*
* Returns information about the device, and error strings
*/
ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param)
START_API_FUNC
{
const ALCchar *value = nullptr;
switch(param)
{
case ALC_NO_ERROR:
value = alcNoError;
break;
case ALC_INVALID_ENUM:
value = alcErrInvalidEnum;
break;
case ALC_INVALID_VALUE:
value = alcErrInvalidValue;
break;
case ALC_INVALID_DEVICE:
value = alcErrInvalidDevice;
break;
case ALC_INVALID_CONTEXT:
value = alcErrInvalidContext;
break;
case ALC_OUT_OF_MEMORY:
value = alcErrOutOfMemory;
break;
case ALC_DEVICE_SPECIFIER:
value = alcDefaultName;
break;
case ALC_ALL_DEVICES_SPECIFIER:
if(DeviceRef dev{VerifyDevice(Device)})
value = dev->DeviceName.c_str();
else
{
ProbeAllDevicesList();
value = alcAllDevicesList.c_str();
}
break;
case ALC_CAPTURE_DEVICE_SPECIFIER:
if(DeviceRef dev{VerifyDevice(Device)})
value = dev->DeviceName.c_str();
else
{
ProbeCaptureDeviceList();
value = alcCaptureDeviceList.c_str();
}
break;
/* Default devices are always first in the list */
case ALC_DEFAULT_DEVICE_SPECIFIER:
value = alcDefaultName;
break;
case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
if(alcAllDevicesList.empty())
ProbeAllDevicesList();
/* Copy first entry as default. */
alcDefaultAllDevicesSpecifier = alcAllDevicesList.c_str();
value = alcDefaultAllDevicesSpecifier.c_str();
break;
case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
if(alcCaptureDeviceList.empty())
ProbeCaptureDeviceList();
/* Copy first entry as default. */
alcCaptureDefaultDeviceSpecifier = alcCaptureDeviceList.c_str();
value = alcCaptureDefaultDeviceSpecifier.c_str();
break;
case ALC_EXTENSIONS:
if(VerifyDevice(Device))
value = alcExtensionList;
else
value = alcNoDeviceExtList;
break;
case ALC_HRTF_SPECIFIER_SOFT:
if(DeviceRef dev{VerifyDevice(Device)})
{
std::lock_guard<std::mutex> _{dev->StateLock};
value = (dev->mHrtf ? dev->HrtfName.c_str() : "");
}
else
alcSetError(nullptr, ALC_INVALID_DEVICE);
break;
default:
alcSetError(VerifyDevice(Device).get(), ALC_INVALID_ENUM);
break;
}
return value;
}
END_API_FUNC
static inline ALCsizei NumAttrsForDevice(ALCdevice *device)
{
if(device->Type == Capture) return 9;
if(device->Type != Loopback) return 29;
if(device->FmtChans == DevFmtAmbi3D)
return 35;
return 29;
}
static size_t GetIntegerv(ALCdevice *device, ALCenum param, const al::span<ALCint> values)
{
size_t i;
if(values.empty())
{
alcSetError(device, ALC_INVALID_VALUE);
return 0;
}
if(!device)
{
switch(param)
{
case ALC_MAJOR_VERSION:
values[0] = alcMajorVersion;
return 1;
case ALC_MINOR_VERSION:
values[0] = alcMinorVersion;
return 1;
case ALC_ATTRIBUTES_SIZE:
case ALC_ALL_ATTRIBUTES:
case ALC_FREQUENCY:
case ALC_REFRESH:
case ALC_SYNC:
case ALC_MONO_SOURCES:
case ALC_STEREO_SOURCES:
case ALC_CAPTURE_SAMPLES:
case ALC_FORMAT_CHANNELS_SOFT:
case ALC_FORMAT_TYPE_SOFT:
case ALC_AMBISONIC_LAYOUT_SOFT:
case ALC_AMBISONIC_SCALING_SOFT:
case ALC_AMBISONIC_ORDER_SOFT:
case ALC_MAX_AMBISONIC_ORDER_SOFT:
alcSetError(nullptr, ALC_INVALID_DEVICE);
return 0;
default:
alcSetError(nullptr, ALC_INVALID_ENUM);
return 0;
}
return 0;
}
if(device->Type == Capture)
{
switch(param)
{
case ALC_ATTRIBUTES_SIZE:
values[0] = NumAttrsForDevice(device);
return 1;
case ALC_ALL_ATTRIBUTES:
i = 0;
if(values.size() < static_cast<size_t>(NumAttrsForDevice(device)))
alcSetError(device, ALC_INVALID_VALUE);
else
{
std::lock_guard<std::mutex> _{device->StateLock};
values[i++] = ALC_MAJOR_VERSION;
values[i++] = alcMajorVersion;
values[i++] = ALC_MINOR_VERSION;
values[i++] = alcMinorVersion;
values[i++] = ALC_CAPTURE_SAMPLES;
values[i++] = static_cast<int>(device->Backend->availableSamples());
values[i++] = ALC_CONNECTED;
values[i++] = device->Connected.load(std::memory_order_relaxed);
values[i++] = 0;
}
return i;
case ALC_MAJOR_VERSION:
values[0] = alcMajorVersion;
return 1;
case ALC_MINOR_VERSION:
values[0] = alcMinorVersion;
return 1;
case ALC_CAPTURE_SAMPLES:
{
std::lock_guard<std::mutex> _{device->StateLock};
values[0] = static_cast<int>(device->Backend->availableSamples());
}
return 1;
case ALC_CONNECTED:
{
std::lock_guard<std::mutex> _{device->StateLock};
values[0] = device->Connected.load(std::memory_order_acquire);
}
return 1;
default:
alcSetError(device, ALC_INVALID_ENUM);
}
return 0;
}
/* render device */
switch(param)
{
case ALC_ATTRIBUTES_SIZE:
values[0] = NumAttrsForDevice(device);
return 1;
case ALC_ALL_ATTRIBUTES:
i = 0;
if(values.size() < static_cast<size_t>(NumAttrsForDevice(device)))
alcSetError(device, ALC_INVALID_VALUE);
else
{
std::lock_guard<std::mutex> _{device->StateLock};
values[i++] = ALC_MAJOR_VERSION;
values[i++] = alcMajorVersion;
values[i++] = ALC_MINOR_VERSION;
values[i++] = alcMinorVersion;
values[i++] = ALC_EFX_MAJOR_VERSION;
values[i++] = alcEFXMajorVersion;
values[i++] = ALC_EFX_MINOR_VERSION;
values[i++] = alcEFXMinorVersion;
values[i++] = ALC_FREQUENCY;
values[i++] = static_cast<int>(device->Frequency);
if(device->Type != Loopback)
{
values[i++] = ALC_REFRESH;
values[i++] = static_cast<int>(device->Frequency / device->UpdateSize);
values[i++] = ALC_SYNC;
values[i++] = ALC_FALSE;
}
else
{
if(device->FmtChans == DevFmtAmbi3D)
{
values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
values[i++] = static_cast<ALCint>(device->mAmbiLayout);
values[i++] = ALC_AMBISONIC_SCALING_SOFT;
values[i++] = static_cast<ALCint>(device->mAmbiScale);
values[i++] = ALC_AMBISONIC_ORDER_SOFT;
values[i++] = static_cast<ALCint>(device->mAmbiOrder);
}
values[i++] = ALC_FORMAT_CHANNELS_SOFT;
values[i++] = device->FmtChans;
values[i++] = ALC_FORMAT_TYPE_SOFT;
values[i++] = device->FmtType;
}
values[i++] = ALC_MONO_SOURCES;
values[i++] = static_cast<int>(device->NumMonoSources);
values[i++] = ALC_STEREO_SOURCES;
values[i++] = static_cast<int>(device->NumStereoSources);
values[i++] = ALC_MAX_AUXILIARY_SENDS;
values[i++] = static_cast<ALCint>(device->NumAuxSends);
values[i++] = ALC_HRTF_SOFT;
values[i++] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
values[i++] = ALC_HRTF_STATUS_SOFT;
values[i++] = device->HrtfStatus;
values[i++] = ALC_OUTPUT_LIMITER_SOFT;
values[i++] = device->Limiter ? ALC_TRUE : ALC_FALSE;
values[i++] = ALC_MAX_AMBISONIC_ORDER_SOFT;
values[i++] = MAX_AMBI_ORDER;
values[i++] = 0;
}
return i;
case ALC_MAJOR_VERSION:
values[0] = alcMajorVersion;
return 1;
case ALC_MINOR_VERSION:
values[0] = alcMinorVersion;
return 1;
case ALC_EFX_MAJOR_VERSION:
values[0] = alcEFXMajorVersion;
return 1;
case ALC_EFX_MINOR_VERSION:
values[0] = alcEFXMinorVersion;
return 1;
case ALC_FREQUENCY:
values[0] = static_cast<int>(device->Frequency);
return 1;
case ALC_REFRESH:
if(device->Type == Loopback)
{
alcSetError(device, ALC_INVALID_DEVICE);
return 0;
}
{
std::lock_guard<std::mutex> _{device->StateLock};
values[0] = static_cast<int>(device->Frequency / device->UpdateSize);
}
return 1;
case ALC_SYNC:
if(device->Type == Loopback)
{
alcSetError(device, ALC_INVALID_DEVICE);
return 0;
}
values[0] = ALC_FALSE;
return 1;
case ALC_FORMAT_CHANNELS_SOFT:
if(device->Type != Loopback)
{
alcSetError(device, ALC_INVALID_DEVICE);
return 0;
}
values[0] = device->FmtChans;
return 1;
case ALC_FORMAT_TYPE_SOFT:
if(device->Type != Loopback)
{
alcSetError(device, ALC_INVALID_DEVICE);
return 0;
}
values[0] = device->FmtType;
return 1;
case ALC_AMBISONIC_LAYOUT_SOFT:
if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
{
alcSetError(device, ALC_INVALID_DEVICE);
return 0;
}
values[0] = static_cast<ALCint>(device->mAmbiLayout);
return 1;
case ALC_AMBISONIC_SCALING_SOFT:
if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
{
alcSetError(device, ALC_INVALID_DEVICE);
return 0;
}
values[0] = static_cast<ALCint>(device->mAmbiScale);
return 1;
case ALC_AMBISONIC_ORDER_SOFT:
if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
{
alcSetError(device, ALC_INVALID_DEVICE);
return 0;
}
values[0] = static_cast<int>(device->mAmbiOrder);
return 1;
case ALC_MONO_SOURCES:
values[0] = static_cast<int>(device->NumMonoSources);
return 1;
case ALC_STEREO_SOURCES:
values[0] = static_cast<int>(device->NumStereoSources);
return 1;
case ALC_MAX_AUXILIARY_SENDS:
values[0] = static_cast<ALCint>(device->NumAuxSends);
return 1;
case ALC_CONNECTED:
{
std::lock_guard<std::mutex> _{device->StateLock};
values[0] = device->Connected.load(std::memory_order_acquire);
}
return 1;
case ALC_HRTF_SOFT:
values[0] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
return 1;
case ALC_HRTF_STATUS_SOFT:
values[0] = device->HrtfStatus;
return 1;
case ALC_NUM_HRTF_SPECIFIERS_SOFT:
{
std::lock_guard<std::mutex> _{device->StateLock};
device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
values[0] = static_cast<ALCint>(minz(device->HrtfList.size(),
std::numeric_limits<ALCint>::max()));
}
return 1;
case ALC_OUTPUT_LIMITER_SOFT:
values[0] = device->Limiter ? ALC_TRUE : ALC_FALSE;
return 1;
case ALC_MAX_AMBISONIC_ORDER_SOFT:
values[0] = MAX_AMBI_ORDER;
return 1;
default:
alcSetError(device, ALC_INVALID_ENUM);
}
return 0;
}
/* alcGetIntegerv
*
* Returns information about the device and the version of OpenAL
*/
ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(size <= 0 || values == nullptr)
alcSetError(dev.get(), ALC_INVALID_VALUE);
else
GetIntegerv(dev.get(), param, {values, values+size});
}
END_API_FUNC
ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALCsizei size, ALCint64SOFT *values)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(size <= 0 || values == nullptr)
alcSetError(dev.get(), ALC_INVALID_VALUE);
else if(!dev || dev->Type == Capture)
{
auto ivals = al::vector<ALCint>(static_cast<ALuint>(size));
size_t got{GetIntegerv(dev.get(), pname, {ivals.data(), ivals.size()})};
std::copy_n(ivals.begin(), got, values);
return;
}
/* render device */
switch(pname)
{
case ALC_ATTRIBUTES_SIZE:
*values = NumAttrsForDevice(dev.get())+4;
break;
case ALC_ALL_ATTRIBUTES:
if(size < NumAttrsForDevice(dev.get())+4)
alcSetError(dev.get(), ALC_INVALID_VALUE);
else
{
size_t i{0};
std::lock_guard<std::mutex> _{dev->StateLock};
values[i++] = ALC_FREQUENCY;
values[i++] = dev->Frequency;
if(dev->Type != Loopback)
{
values[i++] = ALC_REFRESH;
values[i++] = dev->Frequency / dev->UpdateSize;
values[i++] = ALC_SYNC;
values[i++] = ALC_FALSE;
}
else
{
if(dev->FmtChans == DevFmtAmbi3D)
{
values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiLayout);
values[i++] = ALC_AMBISONIC_SCALING_SOFT;
values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiScale);
values[i++] = ALC_AMBISONIC_ORDER_SOFT;
values[i++] = dev->mAmbiOrder;
}
values[i++] = ALC_FORMAT_CHANNELS_SOFT;
values[i++] = dev->FmtChans;
values[i++] = ALC_FORMAT_TYPE_SOFT;
values[i++] = dev->FmtType;
}
values[i++] = ALC_MONO_SOURCES;
values[i++] = dev->NumMonoSources;
values[i++] = ALC_STEREO_SOURCES;
values[i++] = dev->NumStereoSources;
values[i++] = ALC_MAX_AUXILIARY_SENDS;
values[i++] = dev->NumAuxSends;
values[i++] = ALC_HRTF_SOFT;
values[i++] = (dev->mHrtf ? ALC_TRUE : ALC_FALSE);
values[i++] = ALC_HRTF_STATUS_SOFT;
values[i++] = dev->HrtfStatus;
values[i++] = ALC_OUTPUT_LIMITER_SOFT;
values[i++] = dev->Limiter ? ALC_TRUE : ALC_FALSE;
ClockLatency clock{GetClockLatency(dev.get())};
values[i++] = ALC_DEVICE_CLOCK_SOFT;
values[i++] = clock.ClockTime.count();
values[i++] = ALC_DEVICE_LATENCY_SOFT;
values[i++] = clock.Latency.count();
values[i++] = 0;
}
break;
case ALC_DEVICE_CLOCK_SOFT:
{ std::lock_guard<std::mutex> _{dev->StateLock};
nanoseconds basecount;
ALuint samplecount;
ALuint refcount;
do {
while(((refcount=ReadRef(dev->MixCount))&1) != 0)
std::this_thread::yield();
basecount = dev->ClockBase;
samplecount = dev->SamplesDone;
} while(refcount != ReadRef(dev->MixCount));
basecount += nanoseconds{seconds{samplecount}} / dev->Frequency;
*values = basecount.count();
}
break;
case ALC_DEVICE_LATENCY_SOFT:
{ std::lock_guard<std::mutex> _{dev->StateLock};
ClockLatency clock{GetClockLatency(dev.get())};
*values = clock.Latency.count();
}
break;
case ALC_DEVICE_CLOCK_LATENCY_SOFT:
if(size < 2)
alcSetError(dev.get(), ALC_INVALID_VALUE);
else
{
std::lock_guard<std::mutex> _{dev->StateLock};
ClockLatency clock{GetClockLatency(dev.get())};
values[0] = clock.ClockTime.count();
values[1] = clock.Latency.count();
}
break;
default:
auto ivals = al::vector<ALCint>(static_cast<ALuint>(size));
size_t got{GetIntegerv(dev.get(), pname, {ivals.data(), ivals.size()})};
std::copy_n(ivals.begin(), got, values);
break;
}
}
END_API_FUNC
/* alcIsExtensionPresent
*
* Determines if there is support for a particular extension
*/
ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!extName)
alcSetError(dev.get(), ALC_INVALID_VALUE);
else
{
size_t len = strlen(extName);
const char *ptr = (dev ? alcExtensionList : alcNoDeviceExtList);
while(ptr && *ptr)
{
if(al::strncasecmp(ptr, extName, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len])))
return ALC_TRUE;
if((ptr=strchr(ptr, ' ')) != nullptr)
{
do {
++ptr;
} while(isspace(*ptr));
}
}
}
return ALC_FALSE;
}
END_API_FUNC
/* alcGetProcAddress
*
* Retrieves the function address for a particular extension function
*/
ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
START_API_FUNC
{
if(!funcName)
{
DeviceRef dev{VerifyDevice(device)};
alcSetError(dev.get(), ALC_INVALID_VALUE);
}
else
{
for(const auto &func : alcFunctions)
{
if(strcmp(func.funcName, funcName) == 0)
return func.address;
}
}
return nullptr;
}
END_API_FUNC
/* alcGetEnumValue
*
* Get the value for a particular ALC enumeration name
*/
ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
START_API_FUNC
{
if(!enumName)
{
DeviceRef dev{VerifyDevice(device)};
alcSetError(dev.get(), ALC_INVALID_VALUE);
}
else
{
for(const auto &enm : alcEnumerations)
{
if(strcmp(enm.enumName, enumName) == 0)
return enm.value;
}
}
return 0;
}
END_API_FUNC
/* alcCreateContext
*
* Create and attach a context to the given device.
*/
ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
START_API_FUNC
{
/* Explicitly hold the list lock while taking the StateLock in case the
* device is asynchronously destroyed, to ensure this new context is
* properly cleaned up after being made.
*/
std::unique_lock<std::recursive_mutex> listlock{ListLock};
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type == Capture || !dev->Connected.load(std::memory_order_relaxed))
{
listlock.unlock();
alcSetError(dev.get(), ALC_INVALID_DEVICE);
return nullptr;
}
std::unique_lock<std::mutex> statelock{dev->StateLock};
listlock.unlock();
dev->LastError.store(ALC_NO_ERROR);
ALCenum err{UpdateDeviceParams(dev.get(), attrList)};
if(err != ALC_NO_ERROR)
{
alcSetError(dev.get(), err);
if(err == ALC_INVALID_DEVICE)
aluHandleDisconnect(dev.get(), "Device update failure");
return nullptr;
}
ContextRef context{new ALCcontext{dev}};
context->init();
if(auto volopt = ConfigValueFloat(dev->DeviceName.c_str(), nullptr, "volume-adjust"))
{
const ALfloat valf{*volopt};
if(!std::isfinite(valf))
ERR("volume-adjust must be finite: %f\n", valf);
else
{
const ALfloat db{clampf(valf, -24.0f, 24.0f)};
if(db != valf)
WARN("volume-adjust clamped: %f, range: +/-%f\n", valf, 24.0f);
context->mGainBoost = std::pow(10.0f, db/20.0f);
TRACE("volume-adjust gain: %f\n", context->mGainBoost);
}
}
UpdateListenerProps(context.get());
{
using ContextArray = al::FlexArray<ALCcontext*>;
/* Allocate a new context array, which holds 1 more than the current/
* old array.
*/
auto *oldarray = device->mContexts.load();
const size_t newcount{oldarray->size()+1};
std::unique_ptr<ContextArray> newarray{ContextArray::Create(newcount)};
/* Copy the current/old context handles to the new array, appending the
* new context.
*/
auto iter = std::copy(oldarray->begin(), oldarray->end(), newarray->begin());
*iter = context.get();
/* Store the new context array in the device. Wait for any current mix
* to finish before deleting the old array.
*/
dev->mContexts.store(newarray.release());
if(oldarray != &EmptyContextArray)
{
while((dev->MixCount.load(std::memory_order_acquire)&1))
std::this_thread::yield();
delete oldarray;
}
}
statelock.unlock();
{
std::lock_guard<std::recursive_mutex> _{ListLock};
auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context.get());
ContextList.emplace(iter, context.get());
}
if(context->mDefaultSlot)
{
if(InitializeEffect(context.get(), context->mDefaultSlot.get(), &DefaultEffect) == AL_NO_ERROR)
UpdateEffectSlotProps(context->mDefaultSlot.get(), context.get());
else
ERR("Failed to initialize the default effect\n");
}
TRACE("Created context %p\n", decltype(std::declval<void*>()){context.get()});
return context.release();
}
END_API_FUNC
/* alcDestroyContext
*
* Remove a context from its device
*/
ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
START_API_FUNC
{
std::unique_lock<std::recursive_mutex> listlock{ListLock};
auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context);
if(iter == ContextList.end() || *iter != context)
{
listlock.unlock();
alcSetError(nullptr, ALC_INVALID_CONTEXT);
return;
}
/* Hold a reference to this context so it remains valid until the ListLock
* is released.
*/
ContextRef ctx{*iter};
ContextList.erase(iter);
ALCdevice *Device{ctx->mDevice.get()};
std::lock_guard<std::mutex> _{Device->StateLock};
if(!ctx->deinit() && Device->Flags.get<DeviceRunning>())
{
Device->Backend->stop();
Device->Flags.unset<DeviceRunning>();
}
}
END_API_FUNC
/* alcGetCurrentContext
*
* Returns the currently active context on the calling thread
*/
ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(void)
START_API_FUNC
{
ALCcontext *Context{LocalContext.get()};
if(!Context) Context = GlobalContext.load();
return Context;
}
END_API_FUNC
/* alcGetThreadContext
*
* Returns the currently active thread-local context
*/
ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
START_API_FUNC
{ return LocalContext.get(); }
END_API_FUNC
/* alcMakeContextCurrent
*
* Makes the given context the active process-wide context, and removes the
* thread-local context for the calling thread.
*/
ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
START_API_FUNC
{
/* context must be valid or nullptr */
ContextRef ctx;
if(context)
{
ctx = VerifyContext(context);
if(!ctx)
{
alcSetError(nullptr, ALC_INVALID_CONTEXT);
return ALC_FALSE;
}
}
/* Release this reference (if any) to store it in the GlobalContext
* pointer. Take ownership of the reference (if any) that was previously
* stored there.
*/
ctx = ContextRef{GlobalContext.exchange(ctx.release())};
/* Reset (decrement) the previous global reference by replacing it with the
* thread-local context. Take ownership of the thread-local context
* reference (if any), clearing the storage to null.
*/
ctx = ContextRef{LocalContext.get()};
if(ctx) LocalContext.set(nullptr);
/* Reset (decrement) the previous thread-local reference. */
return ALC_TRUE;
}
END_API_FUNC
/* alcSetThreadContext
*
* Makes the given context the active context for the current thread
*/
ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
START_API_FUNC
{
/* context must be valid or nullptr */
ContextRef ctx;
if(context)
{
ctx = VerifyContext(context);
if(!ctx)
{
alcSetError(nullptr, ALC_INVALID_CONTEXT);
return ALC_FALSE;
}
}
/* context's reference count is already incremented */
ContextRef old{LocalContext.get()};
LocalContext.set(ctx.release());
return ALC_TRUE;
}
END_API_FUNC
/* alcGetContextsDevice
*
* Returns the device that a particular context is attached to
*/
ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
START_API_FUNC
{
ContextRef ctx{VerifyContext(Context)};
if(!ctx)
{
alcSetError(nullptr, ALC_INVALID_CONTEXT);
return nullptr;
}
return ctx->mDevice.get();
}
END_API_FUNC
/* alcOpenDevice
*
* Opens the named device.
*/
ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
START_API_FUNC
{
DO_INITCONFIG();
if(!PlaybackFactory)
{
alcSetError(nullptr, ALC_INVALID_VALUE);
return nullptr;
}
if(deviceName)
{
if(!deviceName[0] || al::strcasecmp(deviceName, alcDefaultName) == 0
#ifdef _WIN32
/* Some old Windows apps hardcode these expecting OpenAL to use a
* specific audio API, even when they're not enumerated. Creative's
* router effectively ignores them too.
*/
|| al::strcasecmp(deviceName, "DirectSound3D") == 0
|| al::strcasecmp(deviceName, "DirectSound") == 0
|| al::strcasecmp(deviceName, "MMSYSTEM") == 0
#endif
|| al::strcasecmp(deviceName, "openal-soft") == 0)
deviceName = nullptr;
}
DeviceRef device{new ALCdevice{Playback}};
/* Set output format */
device->FmtChans = DevFmtChannelsDefault;
device->FmtType = DevFmtTypeDefault;
device->Frequency = DEFAULT_OUTPUT_RATE;
device->UpdateSize = DEFAULT_UPDATE_SIZE;
device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES;
device->SourcesMax = 256;
device->AuxiliaryEffectSlotMax = 64;
device->NumAuxSends = DEFAULT_SENDS;
try {
auto backend = PlaybackFactory->createBackend(device.get(), BackendType::Playback);
backend->open(deviceName);
device->Backend = std::move(backend);
}
catch(al::backend_exception &e) {
WARN("Failed to open playback device: %s\n", e.what());
alcSetError(nullptr, e.errorCode());
return nullptr;
}
deviceName = device->DeviceName.c_str();
if(auto chanopt = ConfigValueStr(deviceName, nullptr, "channels"))
{
static const struct ChannelMap {
const char name[16];
DevFmtChannels chans;
ALuint order;
} chanlist[] = {
{ "mono", DevFmtMono, 0 },
{ "stereo", DevFmtStereo, 0 },
{ "quad", DevFmtQuad, 0 },
{ "surround51", DevFmtX51, 0 },
{ "surround61", DevFmtX61, 0 },
{ "surround71", DevFmtX71, 0 },
{ "surround51rear", DevFmtX51Rear, 0 },
{ "ambi1", DevFmtAmbi3D, 1 },
{ "ambi2", DevFmtAmbi3D, 2 },
{ "ambi3", DevFmtAmbi3D, 3 },
};
const ALCchar *fmt{chanopt->c_str()};
auto iter = std::find_if(std::begin(chanlist), std::end(chanlist),
[fmt](const ChannelMap &entry) -> bool
{ return al::strcasecmp(entry.name, fmt) == 0; }
);
if(iter == std::end(chanlist))
ERR("Unsupported channels: %s\n", fmt);
else
{
device->FmtChans = iter->chans;
device->mAmbiOrder = iter->order;
device->Flags.set<ChannelsRequest>();
}
}
if(auto typeopt = ConfigValueStr(deviceName, nullptr, "sample-type"))
{
static const struct TypeMap {
const char name[16];
DevFmtType type;
} typelist[] = {
{ "int8", DevFmtByte },
{ "uint8", DevFmtUByte },
{ "int16", DevFmtShort },
{ "uint16", DevFmtUShort },
{ "int32", DevFmtInt },
{ "uint32", DevFmtUInt },
{ "float32", DevFmtFloat },
};
const ALCchar *fmt{typeopt->c_str()};
auto iter = std::find_if(std::begin(typelist), std::end(typelist),
[fmt](const TypeMap &entry) -> bool
{ return al::strcasecmp(entry.name, fmt) == 0; }
);
if(iter == std::end(typelist))
ERR("Unsupported sample-type: %s\n", fmt);
else
{
device->FmtType = iter->type;
device->Flags.set<SampleTypeRequest>();
}
}
if(ALuint freq{ConfigValueUInt(deviceName, nullptr, "frequency").value_or(0)})
{
if(freq < MIN_OUTPUT_RATE)
{
ERR("%uhz request clamped to %uhz minimum\n", freq, MIN_OUTPUT_RATE);
freq = MIN_OUTPUT_RATE;
}
device->UpdateSize = (device->UpdateSize*freq + device->Frequency/2) / device->Frequency;
device->BufferSize = (device->BufferSize*freq + device->Frequency/2) / device->Frequency;
device->Frequency = freq;
device->Flags.set<FrequencyRequest>();
}
if(auto persizeopt = ConfigValueUInt(deviceName, nullptr, "period_size"))
device->UpdateSize = clampu(*persizeopt, 64, 8192);
if(auto peropt = ConfigValueUInt(deviceName, nullptr, "periods"))
device->BufferSize = device->UpdateSize * clampu(*peropt, 2, 16);
else
device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2);
if(auto srcsopt = ConfigValueUInt(deviceName, nullptr, "sources"))
{
if(*srcsopt > 0) device->SourcesMax = *srcsopt;
}
if(auto slotsopt = ConfigValueUInt(deviceName, nullptr, "slots"))
{
if(*slotsopt > 0)
device->AuxiliaryEffectSlotMax = minu(*slotsopt, INT_MAX);
}
if(auto sendsopt = ConfigValueInt(deviceName, nullptr, "sends"))
device->NumAuxSends = clampu(DEFAULT_SENDS, 0,
static_cast<ALuint>(clampi(*sendsopt, 0, MAX_SENDS)));
device->NumStereoSources = 1;
device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
if(auto ambiopt = ConfigValueStr(deviceName, nullptr, "ambi-format"))
{
const ALCchar *fmt{ambiopt->c_str()};
if(al::strcasecmp(fmt, "fuma") == 0)
{
if(device->mAmbiOrder > 3)
ERR("FuMa is incompatible with %d%s order ambisonics (up to third-order only)\n",
device->mAmbiOrder,
(((device->mAmbiOrder%100)/10) == 1) ? "th" :
((device->mAmbiOrder%10) == 1) ? "st" :
((device->mAmbiOrder%10) == 2) ? "nd" :
((device->mAmbiOrder%10) == 3) ? "rd" : "th");
else
{
device->mAmbiLayout = AmbiLayout::FuMa;
device->mAmbiScale = AmbiNorm::FuMa;
}
}
else if(al::strcasecmp(fmt, "ambix") == 0 || al::strcasecmp(fmt, "acn+sn3d") == 0)
{
device->mAmbiLayout = AmbiLayout::ACN;
device->mAmbiScale = AmbiNorm::SN3D;
}
else if(al::strcasecmp(fmt, "acn+n3d") == 0)
{
device->mAmbiLayout = AmbiLayout::ACN;
device->mAmbiScale = AmbiNorm::N3D;
}
else
ERR("Unsupported ambi-format: %s\n", fmt);
}
{
std::lock_guard<std::recursive_mutex> _{ListLock};
auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
DeviceList.emplace(iter, device.get());
}
TRACE("Created device %p, \"%s\"\n", decltype(std::declval<void*>()){device.get()},
device->DeviceName.c_str());
return device.release();
}
END_API_FUNC
/* alcCloseDevice
*
* Closes the given device.
*/
ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device)
START_API_FUNC
{
std::unique_lock<std::recursive_mutex> listlock{ListLock};
auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
if(iter == DeviceList.end() || *iter != device)
{
alcSetError(nullptr, ALC_INVALID_DEVICE);
return ALC_FALSE;
}
if((*iter)->Type == Capture)
{
alcSetError(*iter, ALC_INVALID_DEVICE);
return ALC_FALSE;
}
/* Erase the device, and any remaining contexts left on it, from their
* respective lists.
*/
DeviceRef dev{*iter};
DeviceList.erase(iter);
std::unique_lock<std::mutex> statelock{dev->StateLock};
al::vector<ContextRef> orphanctxs;
for(ALCcontext *ctx : *dev->mContexts.load())
{
auto ctxiter = std::lower_bound(ContextList.begin(), ContextList.end(), ctx);
if(ctxiter != ContextList.end() && *ctxiter == ctx)
{
orphanctxs.emplace_back(ContextRef{*ctxiter});
ContextList.erase(ctxiter);
}
}
listlock.unlock();
for(ContextRef &context : orphanctxs)
{
WARN("Releasing orphaned context %p\n", decltype(std::declval<void*>()){context.get()});
context->deinit();
}
orphanctxs.clear();
if(dev->Flags.get<DeviceRunning>())
dev->Backend->stop();
dev->Flags.unset<DeviceRunning>();
return ALC_TRUE;
}
END_API_FUNC
/************************************************
* ALC capture functions
************************************************/
ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples)
START_API_FUNC
{
DO_INITCONFIG();
if(!CaptureFactory)
{
alcSetError(nullptr, ALC_INVALID_VALUE);
return nullptr;
}
if(samples <= 0)
{
alcSetError(nullptr, ALC_INVALID_VALUE);
return nullptr;
}
if(deviceName)
{
if(!deviceName[0] || al::strcasecmp(deviceName, alcDefaultName) == 0
|| al::strcasecmp(deviceName, "openal-soft") == 0)
deviceName = nullptr;
}
DeviceRef device{new ALCdevice{Capture}};
auto decompfmt = DecomposeDevFormat(format);
if(!decompfmt)
{
alcSetError(nullptr, ALC_INVALID_ENUM);
return nullptr;
}
device->Frequency = frequency;
device->FmtChans = decompfmt->chans;
device->FmtType = decompfmt->type;
device->Flags.set<FrequencyRequest, ChannelsRequest, SampleTypeRequest>();
device->UpdateSize = static_cast<ALuint>(samples);
device->BufferSize = static_cast<ALuint>(samples);
try {
TRACE("Capture format: %s, %s, %uhz, %u / %u buffer\n",
DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
device->Frequency, device->UpdateSize, device->BufferSize);
auto backend = CaptureFactory->createBackend(device.get(), BackendType::Capture);
backend->open(deviceName);
device->Backend = std::move(backend);
}
catch(al::backend_exception &e) {
WARN("Failed to open capture device: %s\n", e.what());
alcSetError(nullptr, e.errorCode());
return nullptr;
}
{
std::lock_guard<std::recursive_mutex> _{ListLock};
auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
DeviceList.emplace(iter, device.get());
}
TRACE("Created capture device %p, \"%s\"\n", decltype(std::declval<void*>()){device.get()},
device->DeviceName.c_str());
return device.release();
}
END_API_FUNC
ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device)
START_API_FUNC
{
std::unique_lock<std::recursive_mutex> listlock{ListLock};
auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
if(iter == DeviceList.end() || *iter != device)
{
alcSetError(nullptr, ALC_INVALID_DEVICE);
return ALC_FALSE;
}
if((*iter)->Type != Capture)
{
alcSetError(*iter, ALC_INVALID_DEVICE);
return ALC_FALSE;
}
DeviceRef dev{*iter};
DeviceList.erase(iter);
listlock.unlock();
std::lock_guard<std::mutex> _{dev->StateLock};
if(dev->Flags.get<DeviceRunning>())
dev->Backend->stop();
dev->Flags.unset<DeviceRunning>();
return ALC_TRUE;
}
END_API_FUNC
ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type != Capture)
{
alcSetError(dev.get(), ALC_INVALID_DEVICE);
return;
}
std::lock_guard<std::mutex> _{dev->StateLock};
if(!dev->Connected.load(std::memory_order_acquire))
alcSetError(dev.get(), ALC_INVALID_DEVICE);
else if(!dev->Flags.get<DeviceRunning>())
{
try {
auto backend = dev->Backend.get();
if(!backend->start())
throw al::backend_exception{ALC_INVALID_DEVICE, "Device start failure"};
dev->Flags.set<DeviceRunning>();
}
catch(al::backend_exception& e) {
aluHandleDisconnect(dev.get(), "%s", e.what());
alcSetError(dev.get(), ALC_INVALID_DEVICE);
}
}
}
END_API_FUNC
ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type != Capture)
alcSetError(dev.get(), ALC_INVALID_DEVICE);
else
{
std::lock_guard<std::mutex> _{dev->StateLock};
if(dev->Flags.get<DeviceRunning>())
dev->Backend->stop();
dev->Flags.unset<DeviceRunning>();
}
}
END_API_FUNC
ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type != Capture)
{
alcSetError(dev.get(), ALC_INVALID_DEVICE);
return;
}
if(samples < 0 || (samples > 0 && buffer == nullptr))
{
alcSetError(dev.get(), ALC_INVALID_VALUE);
return;
}
if(samples < 1)
return;
std::lock_guard<std::mutex> _{dev->StateLock};
BackendBase *backend{dev->Backend.get()};
const auto usamples = static_cast<ALCuint>(samples);
if(usamples > backend->availableSamples())
{
alcSetError(dev.get(), ALC_INVALID_VALUE);
return;
}
auto *bbuffer = static_cast<al::byte*>(buffer);
if(ALCenum err{backend->captureSamples(bbuffer, usamples)})
alcSetError(dev.get(), err);
}
END_API_FUNC
/************************************************
* ALC loopback functions
************************************************/
/* alcLoopbackOpenDeviceSOFT
*
* Open a loopback device, for manual rendering.
*/
ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName)
START_API_FUNC
{
DO_INITCONFIG();
/* Make sure the device name, if specified, is us. */
if(deviceName && strcmp(deviceName, alcDefaultName) != 0)
{
alcSetError(nullptr, ALC_INVALID_VALUE);
return nullptr;
}
DeviceRef device{new ALCdevice{Loopback}};
device->SourcesMax = 256;
device->AuxiliaryEffectSlotMax = 64;
device->NumAuxSends = DEFAULT_SENDS;
//Set output format
device->BufferSize = 0;
device->UpdateSize = 0;
device->Frequency = DEFAULT_OUTPUT_RATE;
device->FmtChans = DevFmtChannelsDefault;
device->FmtType = DevFmtTypeDefault;
if(auto srcsopt = ConfigValueUInt(nullptr, nullptr, "sources"))
{
if(*srcsopt > 0) device->SourcesMax = *srcsopt;
}
if(auto slotsopt = ConfigValueUInt(nullptr, nullptr, "slots"))
{
if(*slotsopt > 0)
device->AuxiliaryEffectSlotMax = minu(*slotsopt, INT_MAX);
}
if(auto sendsopt = ConfigValueInt(nullptr, nullptr, "sends"))
device->NumAuxSends = clampu(DEFAULT_SENDS, 0,
static_cast<ALuint>(clampi(*sendsopt, 0, MAX_SENDS)));
device->NumStereoSources = 1;
device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
try {
auto backend = LoopbackBackendFactory::getFactory().createBackend(device.get(),
BackendType::Playback);
backend->open("Loopback");
device->Backend = std::move(backend);
}
catch(al::backend_exception &e) {
WARN("Failed to open loopback device: %s\n", e.what());
alcSetError(nullptr, e.errorCode());
return nullptr;
}
{
std::lock_guard<std::recursive_mutex> _{ListLock};
auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
DeviceList.emplace(iter, device.get());
}
TRACE("Created loopback device %p\n", decltype(std::declval<void*>()){device.get()});
return device.release();
}
END_API_FUNC
/* alcIsRenderFormatSupportedSOFT
*
* Determines if the loopback device supports the given format for rendering.
*/
ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type != Loopback)
alcSetError(dev.get(), ALC_INVALID_DEVICE);
else if(freq <= 0)
alcSetError(dev.get(), ALC_INVALID_VALUE);
else
{
if(IsValidALCType(type) && IsValidALCChannels(channels) && freq >= MIN_OUTPUT_RATE)
return ALC_TRUE;
}
return ALC_FALSE;
}
END_API_FUNC
/* alcRenderSamplesSOFT
*
* Renders some samples into a buffer, using the format last set by the
* attributes given to alcCreateContext.
*/
FORCE_ALIGN ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type != Loopback)
alcSetError(dev.get(), ALC_INVALID_DEVICE);
else if(samples < 0 || (samples > 0 && buffer == nullptr))
alcSetError(dev.get(), ALC_INVALID_VALUE);
else
{
BackendLockGuard _{*dev->Backend};
aluMixData(dev.get(), buffer, static_cast<ALuint>(samples), dev->channelsFromFmt());
}
}
END_API_FUNC
/************************************************
* ALC DSP pause/resume functions
************************************************/
/* alcDevicePauseSOFT
*
* Pause the DSP to stop audio processing.
*/
ALC_API void ALC_APIENTRY alcDevicePauseSOFT(ALCdevice *device)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type != Playback)
alcSetError(dev.get(), ALC_INVALID_DEVICE);
else
{
std::lock_guard<std::mutex> _{dev->StateLock};
if(dev->Flags.get<DeviceRunning>())
dev->Backend->stop();
dev->Flags.unset<DeviceRunning>();
dev->Flags.set<DevicePaused>();
}
}
END_API_FUNC
/* alcDeviceResumeSOFT
*
* Resume the DSP to restart audio processing.
*/
ALC_API void ALC_APIENTRY alcDeviceResumeSOFT(ALCdevice *device)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type != Playback)
{
alcSetError(dev.get(), ALC_INVALID_DEVICE);
return;
}
std::lock_guard<std::mutex> _{dev->StateLock};
if(!dev->Flags.get<DevicePaused>())
return;
dev->Flags.unset<DevicePaused>();
if(dev->mContexts.load()->empty())
return;
try {
auto backend = dev->Backend.get();
if(!backend->start())
throw al::backend_exception{ALC_INVALID_DEVICE, "Device start failure"};
dev->Flags.set<DeviceRunning>();
}
catch(al::backend_exception& e) {
aluHandleDisconnect(dev.get(), "%s", e.what());
alcSetError(dev.get(), ALC_INVALID_DEVICE);
}
}
END_API_FUNC
/************************************************
* ALC HRTF functions
************************************************/
/* alcGetStringiSOFT
*
* Gets a string parameter at the given index.
*/
ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum paramName, ALCsizei index)
START_API_FUNC
{
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type == Capture)
alcSetError(dev.get(), ALC_INVALID_DEVICE);
else switch(paramName)
{
case ALC_HRTF_SPECIFIER_SOFT:
if(index >= 0 && static_cast<size_t>(index) < dev->HrtfList.size())
return dev->HrtfList[static_cast<ALuint>(index)].c_str();
alcSetError(dev.get(), ALC_INVALID_VALUE);
break;
default:
alcSetError(dev.get(), ALC_INVALID_ENUM);
break;
}
return nullptr;
}
END_API_FUNC
/* alcResetDeviceSOFT
*
* Resets the given device output, using the specified attribute list.
*/
ALC_API ALCboolean ALC_APIENTRY alcResetDeviceSOFT(ALCdevice *device, const ALCint *attribs)
START_API_FUNC
{
std::unique_lock<std::recursive_mutex> listlock{ListLock};
DeviceRef dev{VerifyDevice(device)};
if(!dev || dev->Type == Capture)
{
listlock.unlock();
alcSetError(dev.get(), ALC_INVALID_DEVICE);
return ALC_FALSE;
}
std::lock_guard<std::mutex> _{dev->StateLock};
listlock.unlock();
/* Force the backend to stop mixing first since we're resetting. Also reset
* the connected state so lost devices can attempt recover.
*/
if(dev->Flags.get<DeviceRunning>())
dev->Backend->stop();
dev->Flags.unset<DeviceRunning>();
device->Connected.store(true);
ALCenum err{UpdateDeviceParams(dev.get(), attribs)};
if LIKELY(err == ALC_NO_ERROR) return ALC_TRUE;
alcSetError(dev.get(), err);
if(err == ALC_INVALID_DEVICE)
aluHandleDisconnect(dev.get(), "Device start failure");
return ALC_FALSE;
}
END_API_FUNC
|
/*
poet::future defines a templated future class which can be used,
for example, to implement "active objects" and asynchronous function
calls. See the paper "Active Object, An Object Behavioral Pattern for
Concurrent Programming." by R. Greg Lavender and Douglas C. Schmidt
for more information about active objects and futures.
Active objects that use futures for both input parameters and
return values can be chained together in pipelines or do
dataflow-like processing, thereby achieving good concurrency.
begin: Frank Hess <frank.hess@nist.gov> 2007-01-22
*/
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef _POET_FUTURE_H
#define _POET_FUTURE_H
#include <boost/assert.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/optional.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/weak_ptr.hpp>
#include <poet/detail/condition.hpp>
#include <poet/detail/event_queue.hpp>
#include <poet/detail/nonvoid.hpp>
#include <poet/detail/utility.hpp>
#include <poet/exception_ptr.hpp>
#include <poet/exceptions.hpp>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <typeinfo>
namespace poet
{
template <typename T>
class future;
namespace detail
{
// forward declarations
class future_body_untyped_base;
template<typename T>
class future_body_base;
template<typename T>
class nonvoid_future_body_base
{
public:
typedef future_body_base<T> type;
};
template<>
class nonvoid_future_body_base<void>
{
public:
typedef future_body_untyped_base type;
};
template<typename T>
const boost::shared_ptr<typename nonvoid_future_body_base<T>::type>& get_future_body(const poet::future<T> &f);
/* class for holding wait callbacks. Any thread can post a functor to the waiter_event_queue,
but only future-waiting threads should pop them off and execute them. */
class waiter_event_queue
{
typedef boost::signals2::signal<void (const event_queue::event_type &)> event_posted_type;
typedef event_posted_type::slot_type slot_type;
typedef std::vector<boost::signals2::connection> connections_type;
public:
waiter_event_queue(boost::mutex &condition_mutex, boost::condition &condition):
_condition_mutex(condition_mutex), _condition(condition), _posting_closed(false)
{}
void set_owner(const boost::shared_ptr<const void> &queue_owner)
{
boost::unique_lock<boost::mutex> lock(_mutex);
boost::shared_ptr<waiter_event_queue> shared_this(queue_owner, this);
_weak_this = shared_this;
}
template<typename Event>
void post(const Event &event)
{
{
boost::unique_lock<boost::mutex> lock(_mutex);
if(_posting_closed) return;
}
_events.post(event);
_event_posted(create_poll_event());
{
boost::unique_lock<boost::mutex> lock(_condition_mutex);
_condition.notify_all();
}
}
void poll()
{
_events.poll();
}
boost::signals2::connection observe(waiter_event_queue &other)
{
boost::signals2::connection connection;
{
boost::unique_lock<boost::mutex> lock(_mutex);
if(_posting_closed) return connection;
//The following static_cast is just there to work around what I think is a g++ 4.4.5 bug when
//compiling in c++0x mode (it gives a compile error without the cast)
slot_type slot(static_cast<void (waiter_event_queue::*)(const event_queue::event_type &)>
(&waiter_event_queue::post<event_queue::event_type>), this, _1);
BOOST_ASSERT(_weak_this.expired() == false);
slot.track(_weak_this);
connection = other._event_posted.connect(slot);
_connections.push_back(connection);
}
post(other.create_poll_event());
return connection;
}
void close_posting()
{
boost::unique_lock<boost::mutex> lock(_mutex);
_posting_closed = true;
connections_type::iterator it;
for(it = _connections.begin(); it != _connections.end(); ++it)
{
it->disconnect();
}
}
private:
event_queue::event_type create_poll_event() const
{
BOOST_ASSERT(_weak_this.expired() == false);
event_queue::event_type event = boost::bind(&waiter_event_queue::poll_event_impl, _weak_this);
return event;
}
static void poll_event_impl(const boost::weak_ptr<waiter_event_queue> &weak_this)
{
boost::shared_ptr<waiter_event_queue> shared_this = weak_this.lock();
if(!shared_this) return;
shared_this->poll();
}
event_queue _events;
boost::mutex _mutex;
boost::mutex &_condition_mutex;
boost::condition &_condition;
event_posted_type _event_posted;
boost::weak_ptr<waiter_event_queue> _weak_this;
connections_type _connections;
bool _posting_closed;
};
class future_body_untyped_base: public boost::enable_shared_from_this<future_body_untyped_base>
{
public:
typedef boost::signals2::signal<void ()> update_signal_type;
typedef update_signal_type::slot_type update_slot_type;
future_body_untyped_base()
{
}
virtual ~future_body_untyped_base()
{
}
virtual bool ready() const = 0;
virtual void join() const = 0;
virtual bool timed_join(const boost::system_time &absolute_time) const = 0;
virtual void cancel(const poet::exception_ptr &) = 0;
virtual exception_ptr get_exception_ptr() const = 0;
virtual waiter_event_queue& waiter_callbacks() const = 0;
boost::signals2::connection connectUpdate(const update_signal_type::slot_type &slot)
{
return _updateSignal.connect(slot);
}
boost::mutex & mutex() const
{
return _mutex;
}
boost::condition & condition() const
{
return _condition;
}
protected:
update_signal_type _updateSignal;
mutable poet::exception_ptr _exception;
private:
mutable boost::mutex _mutex;
mutable boost::condition _condition;
};
template <typename T> class future_body_base: public virtual future_body_untyped_base
{
public:
virtual const typename nonvoid<T>::type& getValue() const = 0;
virtual void setValue(const typename nonvoid<T>::type &value) = 0;
};
template <typename T> class future_body: public future_body_base<T>
{
public:
static boost::shared_ptr<future_body> create()
{
boost::shared_ptr<future_body> new_object(new future_body);
new_object->_waiter_callbacks.set_owner(new_object);
return new_object;
}
static boost::shared_ptr<future_body> create(const T &value)
{
boost::shared_ptr<future_body> new_object(new future_body(value));
new_object->_waiter_callbacks.set_owner(new_object);
return new_object;
}
virtual ~future_body() {}
virtual void setValue(const T &value)
{
bool emit_signal = false;
{
boost::unique_lock<boost::mutex> lock(this->mutex());
if(this->_exception == false && !_value)
{
_value = value;
this->condition().notify_all();
emit_signal = true;
clear_dependencies();
}
}
if(emit_signal)
{
this->_updateSignal();
}
}
virtual bool ready() const
{
boost::unique_lock<boost::mutex> lock(this->mutex());
return static_cast<bool>(_value);
}
virtual const T& getValue() const
{
boost::unique_lock<boost::mutex> lock(this->mutex());
this->condition().wait(lock, boost::bind(&future_body<T>::check_if_complete, this, &lock));
if(this->_exception)
{
rethrow_exception(this->_exception);
}
BOOST_ASSERT(_value);
return _value.get();
}
virtual void join() const
{
boost::unique_lock<boost::mutex> lock(this->mutex());
this->condition().wait(lock, boost::bind(&future_body<T>::check_if_complete, this, &lock));
if(this->_exception)
{
rethrow_exception(this->_exception);
}
BOOST_ASSERT(_value);
}
virtual bool timed_join(const boost::system_time &absolute_time) const
{
boost::unique_lock<boost::mutex> lock(this->mutex());
return this->condition().timed_wait(lock, absolute_time, boost::bind(&future_body<T>::check_if_complete, this, &lock));
}
virtual void cancel(const poet::exception_ptr &exp)
{
bool emitSignal = false;
{
boost::unique_lock<boost::mutex> lock(this->mutex());
if(this->_exception == false && !_value)
{
emitSignal = true;
this->condition().notify_all();
this->_exception = exp;
clear_dependencies();
}
}
if(emitSignal)
{
this->_updateSignal();
}
}
virtual exception_ptr get_exception_ptr() const
{
boost::unique_lock<boost::mutex> lock(this->mutex());
return this->_exception;
}
virtual waiter_event_queue& waiter_callbacks() const
{
return _waiter_callbacks;
}
void add_dependency(const boost::shared_ptr<void> &dependency)
{
boost::unique_lock<boost::mutex> lock(this->mutex());
if(_value || this->_exception) return;
_dependencies.push_back(dependency);
}
private:
future_body(): _waiter_callbacks(future_body_untyped_base::mutex(), future_body_untyped_base::condition())
{}
future_body(const T &value): _value(value),
_waiter_callbacks(future_body_untyped_base::mutex(), future_body_untyped_base::condition())
{}
bool check_if_complete(boost::unique_lock<boost::mutex> *lock) const
{
// do initial check to make sure we don't run any wait callbacks if we are already complete
const bool complete = _value || this->_exception;
if(complete) return complete;
lock->unlock();
_waiter_callbacks.poll();
lock->lock();
return _value || this->_exception;
}
void clear_dependencies()
{
std::vector<boost::shared_ptr<void> >().swap(_dependencies);
_waiter_callbacks.close_posting();
}
boost::optional<T> _value;
mutable waiter_event_queue _waiter_callbacks;
std::vector<boost::shared_ptr<void> > _dependencies;
};
template<typename ProxyType, typename ActualType>
static ProxyType default_conversion_function(const ActualType& actualValue)
{
return ProxyType(actualValue);
}
template<typename ActualType>
static null_type null_conversion_function(const ActualType& actualValue)
{
return null_type();
}
/* class which monitors another future_body_base<ActualType>, while returning values of type ProxyType.
Allows for implicit and explicit conversions between Futures with different template types.
*/
template <typename ProxyType, typename ActualType> class future_body_proxy:
public future_body_base<ProxyType>
{
public:
// static factory function
static boost::shared_ptr<future_body_proxy> create(
const boost::shared_ptr<future_body_base<ActualType> > &actualFutureBody,
const boost::function<ProxyType (const ActualType&)> &conversionFunction)
{
boost::shared_ptr<future_body_proxy> new_object(new future_body_proxy(actualFutureBody, conversionFunction));
new_object->_waiter_callbacks.set_owner(new_object);
typedef typename future_body_untyped_base::update_slot_type slot_type;
slot_type update_slot(&future_body_proxy::handle_actual_body_complete, new_object.get());
update_slot.track(new_object);
boost::signals2::connection conn;
conn = new_object->_actualFutureBody->connectUpdate(update_slot);
if(actualFutureBody->ready() || actualFutureBody->get_exception_ptr())
{
try
{
update_slot();
}
catch(const boost::signals2::expired_slot &)
{
conn.disconnect();
}
/* we don't need to bother observing actualFutureBody's waiter_event_queue
if it was already complete */
return new_object;
}
new_object->waiter_callbacks().observe(actualFutureBody->waiter_callbacks());
return new_object;
}
virtual void setValue(const ProxyType &value)
{
BOOST_ASSERT(false);
}
virtual bool ready() const
{
boost::unique_lock<boost::mutex> lock(this->mutex());
return static_cast<bool>(_proxyValue);
}
virtual const ProxyType& getValue() const
{
_actualFutureBody->join();
boost::unique_lock<boost::mutex> lock(this->mutex());
this->condition().wait(lock, boost::bind(&future_body_proxy::check_if_complete, this, &lock));
if(this->_exception) rethrow_exception(this->_exception);
BOOST_ASSERT(_proxyValue);
return _proxyValue.get();
}
virtual void join() const
{
_actualFutureBody->join();
boost::unique_lock<boost::mutex> lock(this->mutex());
this->condition().wait(lock, boost::bind(&future_body_proxy::check_if_complete, this, &lock));
}
virtual bool timed_join(const boost::system_time &absolute_time) const
{
if(_actualFutureBody->timed_join(absolute_time) == false) return false;
boost::unique_lock<boost::mutex> lock(this->mutex());
return this->condition().timed_wait(lock, absolute_time, boost::bind(&future_body_proxy::check_if_complete, this, &lock));
}
virtual void cancel(const poet::exception_ptr &exp)
{
_actualFutureBody->cancel(exp);
boost::unique_lock<boost::mutex> lock(this->mutex());
this->condition().notify_all();
}
virtual exception_ptr get_exception_ptr() const
{
boost::unique_lock<boost::mutex> lock(this->mutex());
return this->_exception;
}
virtual waiter_event_queue& waiter_callbacks() const
{
return _waiter_callbacks;
}
private:
future_body_proxy(boost::shared_ptr<future_body_base<ActualType> > actualFutureBody,
const boost::function<ProxyType (const ActualType&)> &conversionFunction):
_actualFutureBody(actualFutureBody),
_conversionFunction(conversionFunction),
_waiter_callbacks(future_body_untyped_base::mutex(), future_body_untyped_base::condition()),
_conversionEventPosted(false)
{}
void waiter_event()
{
boost::optional<ProxyType> value;
try
{
value = _conversionFunction(_actualFutureBody->getValue());
}catch(...)
{
{
boost::unique_lock<boost::mutex> lock(this->mutex());
this->_exception = current_exception();
}
this->_updateSignal();
return;
}
{
boost::unique_lock<boost::mutex> lock(this->mutex());
BOOST_ASSERT(!_proxyValue);
_proxyValue = value;
}
this->_updateSignal();
}
void handle_actual_body_complete()
{
{
boost::unique_lock<boost::mutex> lock(this->mutex());
if(_conversionEventPosted) return;
_conversionEventPosted = true;
}
_waiter_callbacks.post(boost::bind(&future_body_proxy::waiter_event, this));
_waiter_callbacks.close_posting();
throw boost::signals2::expired_slot();
}
bool check_if_complete(boost::unique_lock<boost::mutex> *lock) const
{
// do initial check to make sure we don't run any wait callbacks if we are already complete
const bool complete = _proxyValue || this->_exception;
if(complete) return complete;
lock->unlock();
_waiter_callbacks.poll();
lock->lock();
return _proxyValue || this->_exception;
}
boost::shared_ptr<future_body_base<ActualType> > _actualFutureBody;
boost::function<ProxyType (const ActualType&)> _conversionFunction;
mutable boost::optional<ProxyType> _proxyValue;
mutable waiter_event_queue _waiter_callbacks;
mutable bool _conversionEventPosted;
};
class promise_body_untyped_base
{
public:
virtual ~promise_body_untyped_base()
{}
virtual void renege(const exception_ptr &exp) = 0;
virtual bool has_future() const = 0;
virtual boost::shared_ptr<future_body_untyped_base> shared_future_body() const = 0;
};
template <typename T> class promise_body: public promise_body_untyped_base
{
public:
promise_body(): _future_body(future_body<T>::create())
{}
~promise_body()
{
renege(poet::copy_exception(uncertain_future()));
}
void fulfill(const T &value)
{
_future_body->setValue(value);
}
void future_fulfill(const future<T> &future_value)
{
typedef typename future_body_untyped_base::update_slot_type slot_type;
slot_type update_slot(&promise_body::handle_future_fulfillment,
_future_body.get(), get_future_body(future_value).get());
update_slot.track(_future_body);
update_slot.track(get_future_body(future_value));
future_fulfill_guts(get_future_body(future_value), update_slot);
}
// provided for promise<void>
void future_void_fulfill(const future<void> &future_value)
{
typedef typename future_body_untyped_base::update_slot_type slot_type;
slot_type update_slot(&promise_body::handle_future_void_fulfillment,
_future_body.get(), get_future_body(future_value).get());
update_slot.track(_future_body);
update_slot.track(get_future_body(future_value));
future_fulfill_guts(get_future_body(future_value), update_slot);
}
virtual void renege(const exception_ptr &exp)
{
_future_body->cancel(exp);
}
virtual bool has_future() const
{
return !_future_body.unique();
}
virtual boost::shared_ptr<future_body_untyped_base> shared_future_body() const
{
return _future_body;
}
boost::shared_ptr<future_body<T> > _future_body;
private:
template<typename U>
void future_fulfill_guts(const boost::shared_ptr<U> &fulfiller_body,
const future_body_untyped_base::update_slot_type &update_slot)
{
boost::signals2::connection conn;
conn = fulfiller_body->connectUpdate(update_slot);
if(fulfiller_body->ready() || fulfiller_body->get_exception_ptr())
{
try
{
update_slot();
}
catch(const boost::signals2::expired_slot &)
{
conn.disconnect();
}
/* if fulfiller_body was already complete, we are finished. */
return;
}
_future_body->waiter_callbacks().observe(fulfiller_body->waiter_callbacks());
// stick shared_ptr to future_value in dependent _future_body
_future_body->add_dependency(fulfiller_body);
}
inline static void handle_future_fulfillment(future_body_base<T> *fulfillee,
future_body_base<T> *fulfiller);
inline static void handle_future_void_fulfillment(future_body_base<nonvoid<void>::type> *fulfillee,
future_body_untyped_base *fulfiller);
};
template<typename T>
future<T> create_future(const boost::shared_ptr<future_body_untyped_base> &body);
template<>
future<void> create_future<void>(const boost::shared_ptr<future_body_untyped_base> &body);
} // namespace detail
template <typename T>
class promise
{
template <typename U>
friend class future;
template <typename U>
friend class promise;
friend class promise<void>;
public:
typedef T value_type;
promise(): _pimpl(new detail::promise_body<T>)
{}
virtual ~promise() {}
template<typename U>
void fulfill(const U &value)
{
_pimpl->fulfill(value);
}
template<typename U>
void fulfill(const future<U> &future_value)
{
_pimpl->future_fulfill(future_value);
}
template <typename E>
void renege(const E &exception)
{
_pimpl->renege(poet::copy_exception(exception));
}
void renege(const poet::exception_ptr &exp)
{
_pimpl->renege(exp);
}
bool has_future() const
{
return _pimpl->has_future();
}
void reset()
{
promise temp;
swap(temp);
}
void swap(promise &other)
{
using std::swap;
swap(_pimpl, other._pimpl);
}
private:
boost::shared_ptr<detail::promise_body<T> > _pimpl;
};
// void specialization
template<>
class promise<void>
{
template <typename U>
friend class future;
template <typename U>
friend class promise;
public:
typedef void value_type;
promise(): _pimpl(new detail::promise_body<detail::nonvoid<void>::type>)
{}
// allow conversion from a promise with any template type to a promise<void>
template <typename OtherType>
promise(const promise<OtherType> &other): _pimpl(other._pimpl)
{}
virtual ~promise() {}
void fulfill()
{
downcast_pimpl()->fulfill(detail::nonvoid<void>::type());
}
void fulfill(const future<void> &future_value)
{
downcast_pimpl()->future_void_fulfill(future_value);
}
template <typename E>
void renege(const E &exception)
{
_pimpl->renege(poet::copy_exception(exception));
}
void renege(const poet::exception_ptr &exp)
{
_pimpl->renege(exp);
}
bool has_future() const
{
return _pimpl->has_future();
}
void reset()
{
promise temp;
swap(temp);
}
void swap(promise &other)
{
using std::swap;
swap(_pimpl, other._pimpl);
}
private:
boost::shared_ptr<detail::promise_body<detail::nonvoid<void>::type> > downcast_pimpl() const
{
using boost::dynamic_pointer_cast;
boost::shared_ptr<detail::promise_body<detail::nonvoid<void>::type> > downcast =
dynamic_pointer_cast<detail::promise_body<detail::nonvoid<void>::type> >(_pimpl);
if(downcast == false)
{
throw std::invalid_argument("Cannot fulfill a promise<T> for non-void T through a promise<void>");
}
return downcast;
}
boost::shared_ptr<detail::promise_body_untyped_base> _pimpl;
};
template<typename T>
void swap(promise<T> &a, promise<T> &b)
{
a.swap(b);
}
template <typename T> class future
{
friend future<T> detail::create_future<T>(const boost::shared_ptr<detail::future_body_untyped_base> &body);
friend const boost::shared_ptr<typename detail::nonvoid_future_body_base<T>::type>& detail::get_future_body<T>(const poet::future<T> &f);
typedef boost::shared_ptr<detail::future_body_base<T> > future_body_type;
public:
template <typename OtherType> friend class future;
friend class future<void>;
typedef T value_type;
future(const promise<T> &promise): _future_body(promise._pimpl->_future_body)
{}
template <typename OtherType>
future(const promise<OtherType> &promise)
{
future<OtherType> other_future(promise);
*this = other_future;
}
future(const T &value): _future_body(detail::future_body<T>::create(value))
{}
template <typename OtherType> future(const future<OtherType> &other)
{
BOOST_ASSERT(typeid(T) != typeid(OtherType));
if(other._future_body == 0)
{
_future_body.reset();
return;
}
boost::function<T (const OtherType&)> typedConversionFunction =
boost::bind(&detail::default_conversion_function<T, OtherType>, _1);
_future_body = detail::future_body_proxy<T, OtherType>::create(
other._future_body, typedConversionFunction);
}
template <typename OtherType>
future(const OtherType &other): _future_body(detail::future_body<T>::create(other))
{}
future()
{}
virtual ~future() {}
bool ready() const
{
if(_future_body == 0) return false;
bool result = _future_body->ready();
if(result == true) return result;
_future_body->waiter_callbacks().poll();
return _future_body->ready();
}
const T& get() const
{
if(_future_body == 0)
{
throw uncertain_future();
}
return _future_body->getValue();
}
operator const T&() const
{
return get();
}
void join() const
{
if(_future_body == 0)
{
return;
}
_future_body->join();
}
bool timed_join(const boost::system_time &absolute_time) const
{
if(_future_body == false) return true;
return _future_body->timed_join(absolute_time);
}
template <typename OtherType> const future<T>& operator=(const future<OtherType> &other)
{
BOOST_ASSERT(typeid(T) != typeid(OtherType));
_future_body = detail::future_body_proxy<T, OtherType>::create(other._future_body);
return *this;
}
bool has_exception() const
{
if(_future_body == 0) return true;
bool result = _future_body->get_exception_ptr();
if(result == true) return result;
_future_body->waiter_callbacks().poll();
return _future_body->get_exception_ptr().get() != 0;
}
void swap(future &other)
{
using std::swap;
swap(_future_body, other._future_body);
}
private:
future(const boost::shared_ptr<detail::future_body_base<T> > &future_body):_future_body(future_body)
{}
future_body_type _future_body;
};
template <>
class future<void>
{
friend future<void> detail::create_future<void>(const boost::shared_ptr<detail::future_body_untyped_base> &body);
friend const boost::shared_ptr<detail::nonvoid_future_body_base<void>::type>& detail::get_future_body<void>(const poet::future<void> &f);
typedef boost::shared_ptr<detail::future_body_untyped_base > future_body_type;
public:
template <typename OtherType> friend class future;
friend class promise<void>;
typedef void value_type;
future(const promise<void> &promise): _future_body(promise._pimpl->shared_future_body())
{}
template <typename OtherType>
future(const promise<OtherType> &promise)
{
future<OtherType> other_future(promise);
*this = other_future;
}
template <typename OtherType> future(const future<OtherType> &other)
{
BOOST_ASSERT(typeid(void) != typeid(OtherType));
if(other._future_body == 0)
{
_future_body.reset();
return;
}
_future_body = other._future_body;
}
future()
{}
virtual ~future() {}
void get() const
{
if(_future_body == 0)
{
throw uncertain_future();
}
_future_body->join();
exception_ptr ep = _future_body->get_exception_ptr();
if(ep) rethrow_exception(ep);
}
operator void () const
{
get();
}
template <typename OtherType> const future<void>& operator=(const future<OtherType> &other)
{
BOOST_ASSERT(typeid(void) != typeid(OtherType));
_future_body = other._future_body;
return *this;
}
void join() const
{
if(_future_body == 0)
{
return;
}
_future_body->join();
}
bool timed_join(const boost::system_time &absolute_time) const
{
if(_future_body == 0)
{
return true;
}
return _future_body->timed_join(absolute_time);
}
bool ready() const
{
if(_future_body == 0) return false;
_future_body->waiter_callbacks().poll();
return _future_body->ready();
}
bool has_exception() const
{
if(_future_body == 0) return true;
_future_body->waiter_callbacks().poll();
return _future_body->get_exception_ptr().get() != 0;
}
void swap(future &other)
{
using std::swap;
swap(_future_body, other._future_body);
}
private:
future(const boost::shared_ptr<detail::future_body_untyped_base > &future_body):_future_body(future_body)
{}
future_body_type _future_body;
};
template<typename T>
void swap(future<T> &a, future<T> &b)
{
a.swap(b);
}
namespace detail
{
template<typename T>
void promise_body<T>::handle_future_fulfillment(future_body_base<T> *fulfillee,
future_body_base<T> *fulfiller)
{
try
{
fulfillee->setValue(fulfiller->getValue());
}
catch(...)
{
fulfillee->cancel(current_exception());
}
throw boost::signals2::expired_slot();
}
template <typename T>
void promise_body<T>::handle_future_void_fulfillment(future_body_base<nonvoid<void>::type> * fulfillee,
future_body_untyped_base * fulfiller)
{
exception_ptr ep = fulfiller->get_exception_ptr();
if(ep)
{
fulfillee->cancel(ep);
}else
{
BOOST_ASSERT(fulfiller->ready());
fulfillee->setValue(null_type());
}
throw boost::signals2::expired_slot();
}
template<typename T>
future<T> create_future(const boost::shared_ptr<future_body_untyped_base> &body)
{
using boost::dynamic_pointer_cast;
return future<T>(dynamic_pointer_cast<future_body_base<T> >(body));
}
template<>
inline future<void> create_future<void>(const boost::shared_ptr<future_body_untyped_base> &body)
{
return future<void>(body);
}
template<typename T>
class shared_uncertain_future_body
{
public:
static boost::shared_ptr<typename nonvoid_future_body_base<T>::type> value;
private:
static boost::shared_ptr<typename nonvoid_future_body_base<T>::type> create()
{
boost::shared_ptr<typename nonvoid_future_body_base<T>::type> new_object(
future_body<typename nonvoid<T>::type>::create());
new_object->cancel(poet::copy_exception(uncertain_future()));
return new_object;
}
};
template<typename T>
boost::shared_ptr<typename nonvoid_future_body_base<T>::type>
shared_uncertain_future_body<T>::value(shared_uncertain_future_body<T>::create());
template<typename T>
const boost::shared_ptr<typename nonvoid_future_body_base<T>::type>& get_future_body(const poet::future<T> &f)
{
if(!f._future_body) return shared_uncertain_future_body<T>::value;
return f._future_body;
}
} // namespace detail
}
#endif // _POET_FUTURE_H
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Dash Core developers
// Copyright (c) 2020 The But developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include "chainparams.h"
#include "primitives/transaction.h"
#include <QSettings>
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BUTK);
unitlist.append(mBUTK);
unitlist.append(uBUTK);
unitlist.append(ruffs);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BUTK:
case mBUTK:
case uBUTK:
case ruffs:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
if(Params().NetworkIDString() == CBaseChainParams::MAIN)
{
switch(unit)
{
case BUTK: return QString("BUTK");
case mBUTK: return QString("mBUTK");
case uBUTK: return QString::fromUtf8("μBUTK");
case ruffs: return QString("ruffs");
default: return QString("???");
}
}
else
{
switch(unit)
{
case BUTK: return QString("tBUTK");
case mBUTK: return QString("mtBUTK");
case uBUTK: return QString::fromUtf8("μtBUTK");
case ruffs: return QString("tduffs");
default: return QString("???");
}
}
}
QString BitcoinUnits::description(int unit)
{
if(Params().NetworkIDString() == CBaseChainParams::MAIN)
{
switch(unit)
{
case BUTK: return QString("ButK");
case mBUTK: return QString("Milli-ButK (1 / 1" THIN_SP_UTF8 "000)");
case uBUTK: return QString("Micro-ButK (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
case ruffs: return QString("Ten Nano-ButK (1 / 100" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default: return QString("???");
}
}
else
{
switch(unit)
{
case BUTK: return QString("TestButKs");
case mBUTK: return QString("Milli-TestButK (1 / 1" THIN_SP_UTF8 "000)");
case uBUTK: return QString("Micro-TestButK (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
case ruffs: return QString("Ten Nano-TestButK (1 / 100" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default: return QString("???");
}
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BUTK: return 100000000;
case mBUTK: return 100000;
case uBUTK: return 100;
case ruffs: return 1;
default: return 100000000;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BUTK: return 8;
case mBUTK: return 5;
case uBUTK: return 2;
case ruffs: return 0;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 n = (qint64)nIn;
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Use SI-style thin space separators as these are locale independent and can't be
// confused with the decimal marker.
QChar thin_sp(THIN_SP_CP);
int q_size = quotient_str.size();
if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
for (int i = 3; i < q_size; i += 3)
quotient_str.insert(q_size - i, thin_sp);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
if (num_decimals <= 0)
return quotient_str;
return quotient_str + QString(".") + remainder_str;
}
// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.
QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(formatWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QSettings settings;
int digits = settings.value("digits").toInt();
QString result = format(unit, amount, plussign, separators);
if(decimals(unit) > digits) result.chop(decimals(unit) - digits);
return result + QString(" ") + name(unit);
}
QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(floorWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
bool BitcoinUnits::parse(int unit, const QString &value, CAmount *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
// Ignore spaces and thin spaces when parsing
QStringList parts = removeSpaces(value).split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
CAmount retvalue(str.toLongLong(&ok));
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
QString BitcoinUnits::getAmountColumnTitle(int unit)
{
QString amountTitle = QObject::tr("Amount");
if (BitcoinUnits::valid(unit))
{
amountTitle += " ("+BitcoinUnits::name(unit) + ")";
}
return amountTitle;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
CAmount BitcoinUnits::maxMoney()
{
return MAX_MONEY;
}
|
#include <cstdio>
#include <vector>
using namespace std;
typedef vector<int> vi;
class FenwickTree {
private:
vi ft;
int LSOne(int x) { return (x & (-x)); }
public:
FenwickTree(int n) { ft.assign(n + 1, 0); } // init n + 1 zeros
int rsq(int b) {
int sum = 0;
for(; b; b -= LSOne(b)) sum += ft[b]; // ft[b] contains sum of cfs from (b - LSOne(b) + 1) to (b), iteration \
// is from leaf to root
return sum;
}
int rsq(int a, int b) { return rsq(b) - (a == 1 ? 0 : rsq(a - 1)); } // returns RSQ(a, b)
int adjust(int k, int v) { for(; k < static_cast<int>(ft.size()); k += LSOne(k)) ft[k] += v; } // n = ft.size() - 1, iterates \
//from root to leaf
};
int main() {
int f[] = {2, 4, 5, 5, 6, 6, 6, 7, 7, 8, 9}; // m = 11
FenwickTree ft(10); // declare a Fenwick Tree for range [1..10]
for(int i = 0; i < 11; i++) ft.adjust(f[i], 1); // insert these scores manually one by one into an empty Fenwick Tree
// here each operation is increasing f[i](score at index i) by 1, O(mlogn)
printf("%d\n", ft.rsq(1, 1)); // 0 => ft[1] = 0
printf("%d\n", ft.rsq(1, 2)); // 1 => ft[2] = 1
printf("%d\n", ft.rsq(1, 6)); // 7 => ft[6] + ft[4] = 5 + 2 = 7
printf("%d\n", ft.rsq(1, 10)); // 11 => ft[10] + ft[8] = 1 + 10 = 11
printf("%d\n", ft.rsq(3, 6)); // 6 => rsq(1, 6) - rsq(1, 2) = 7 - 1
ft.adjust(5, 2); // update demo
printf("%d\n", ft.rsq(1, 10)); // now 13
return 0;
}
|
/*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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 "OScintillatorLib.hh"
#include "Opticks.hh"
#include "OContext.hh"
#include "GScintillatorLib.hh"
#include "OPTICKS_LOG.hh"
int main(int argc, char** argv)
{
OPTICKS_LOG(argc, argv);
Opticks ok(argc, argv);
ok.configure();
GScintillatorLib* slib = GScintillatorLib::load(&ok);
slib->dump();
OContext::SetupOptiXCachePathEnvvar();
optix::Context context = optix::Context::create();
OScintillatorLib* oscin ;
oscin = new OScintillatorLib(context, slib );
const char* slice = "0:1" ;
oscin->convert(slice);
LOG(info) << "DONE" ;
return 0 ;
}
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/api/declarative_net_request/request_action.h"
namespace extensions {
namespace declarative_net_request {
RequestAction::RequestAction(
RequestAction::Type type,
uint32_t rule_id,
uint64_t index_priority,
api::declarative_net_request::SourceType source_type,
const ExtensionId& extension_id)
: type(type),
rule_id(rule_id),
index_priority(index_priority),
source_type(source_type),
extension_id(extension_id) {}
RequestAction::~RequestAction() = default;
RequestAction::RequestAction(RequestAction&&) = default;
RequestAction& RequestAction::operator=(RequestAction&&) = default;
RequestAction RequestAction::Clone() const {
// Use the private copy constructor to create a copy.
return *this;
}
RequestAction::RequestAction(const RequestAction&) = default;
base::Optional<RequestAction> GetMaxPriorityAction(
base::Optional<RequestAction> lhs,
base::Optional<RequestAction> rhs) {
if (!lhs)
return rhs;
if (!rhs)
return lhs;
return lhs->index_priority >= rhs->index_priority ? std::move(lhs)
: std::move(rhs);
}
} // namespace declarative_net_request
} // namespace extensions
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypter.h"
#include "crypto/aes.h"
#include "crypto/sha512.h"
#include "script/script.h"
#include "script/standard.h"
#include "util.h"
#include <string>
#include <vector>
#include <boost/foreach.hpp>
int CCrypter::BytesToKeySHA512AES(const std::vector<unsigned char>& chSalt, const SecureString& strKeyData, int count, unsigned char *key,unsigned char *iv) const
{
// This mimics the behavior of openssl's EVP_BytesToKey with an aes256cbc
// cipher and sha512 message digest. Because sha512's output size (64b) is
// greater than the aes256 block size (16b) + aes256 key size (32b),
// there's no need to process more than once (D_0).
if(!count || !key || !iv)
return 0;
unsigned char buf[CSHA512::OUTPUT_SIZE];
CSHA512 di;
di.Write((const unsigned char*)strKeyData.c_str(), strKeyData.size());
if(chSalt.size())
di.Write(&chSalt[0], chSalt.size());
di.Finalize(buf);
for(int i = 0; i != count - 1; i++)
di.Reset().Write(buf, sizeof(buf)).Finalize(buf);
memcpy(key, buf, WALLET_CRYPTO_KEY_SIZE);
memcpy(iv, buf + WALLET_CRYPTO_KEY_SIZE, WALLET_CRYPTO_IV_SIZE);
memory_cleanse(buf, sizeof(buf));
return WALLET_CRYPTO_KEY_SIZE;
}
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = BytesToKeySHA512AES(chSalt, strKeyData, nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
memory_cleanse(chKey, sizeof(chKey));
memory_cleanse(chIV, sizeof(chIV));
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_IV_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) const
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCKSIZE bytes
vchCiphertext.resize(vchPlaintext.size() + AES_BLOCKSIZE);
AES256CBCEncrypt enc(chKey, chIV, true);
size_t nLen = enc.Encrypt(&vchPlaintext[0], vchPlaintext.size(), &vchCiphertext[0]);
if(nLen < vchPlaintext.size())
return false;
vchCiphertext.resize(nLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) const
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
vchPlaintext.resize(nLen);
AES256CBCDecrypt dec(chKey, chIV, true);
nLen = dec.Decrypt(&vchCiphertext[0], vchCiphertext.size(), &vchPlaintext[0]);
if(nLen == 0)
return false;
vchPlaintext.resize(nLen);
return true;
}
static bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
static bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
static bool DecryptKey(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key)
{
CKeyingMaterial vchSecret;
if(!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
return key.VerifyPubKey(vchPubKey);
}
bool CCryptoKeyStore::SetCrypted()
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
bool keyPass = false;
bool keyFail = false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKey key;
if (!DecryptKey(vMasterKeyIn, vchCryptedSecret, vchPubKey, key))
{
keyFail = true;
break;
}
keyPass = true;
if (fDecryptionThoroughlyChecked)
break;
}
if (keyPass && keyFail)
{
LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
assert(false);
}
if (keyFail || !keyPass)
return false;
vMasterKey = vMasterKeyIn;
fDecryptionThoroughlyChecked = true;
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKeyPubKey(key, pubkey);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(pubkey, vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
return DecryptKey(vMasterKey, vchCryptedSecret, vchPubKey, keyOut);
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
// Check for watch-only pubkeys
return CBasicKeyStore::GetPubKey(address, vchPubKeyOut);
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
const CKey &key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "test/fake_producer.h"
#include <mutex>
#include <thread>
#include "perfetto/base/logging.h"
#include "perfetto/base/time.h"
#include "perfetto/ext/base/utils.h"
#include "perfetto/ext/tracing/core/commit_data_request.h"
#include "perfetto/ext/tracing/core/shared_memory_arbiter.h"
#include "perfetto/ext/tracing/core/trace_packet.h"
#include "perfetto/ext/tracing/core/trace_writer.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "src/ipc/client_impl.h"
#include "src/tracing/ipc/producer/producer_ipc_client_impl.h"
#include "protos/perfetto/config/test_config.gen.h"
#include "protos/perfetto/trace/test_event.pbzero.h"
#include "protos/perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
const MaybeUnboundBufferID kStartupTargetBufferReservationId = 1;
} // namespace
FakeProducer::FakeProducer(const std::string& name,
base::TaskRunner* task_runner)
: name_(name), task_runner_(task_runner) {}
FakeProducer::~FakeProducer() = default;
void FakeProducer::Connect(const char* socket_name,
std::function<void()> on_connect,
std::function<void()> on_setup_data_source_instance,
std::function<void()> on_create_data_source_instance,
std::unique_ptr<SharedMemory> shm,
std::unique_ptr<SharedMemoryArbiter> shm_arbiter) {
PERFETTO_DCHECK_THREAD(thread_checker_);
endpoint_ = ProducerIPCClient::Connect(
socket_name, this, "android.perfetto.FakeProducer", task_runner_,
TracingService::ProducerSMBScrapingMode::kDefault,
/*shared_memory_size_hint_bytes=*/0,
/*shared_memory_page_size_hint_bytes=*/4096, std::move(shm),
std::move(shm_arbiter));
on_connect_ = std::move(on_connect);
on_setup_data_source_instance_ = std::move(on_setup_data_source_instance);
on_create_data_source_instance_ = std::move(on_create_data_source_instance);
}
void FakeProducer::OnConnect() {
PERFETTO_DCHECK_THREAD(thread_checker_);
DataSourceDescriptor descriptor;
descriptor.set_name(name_);
endpoint_->RegisterDataSource(descriptor);
auto on_connect_callback = std::move(on_connect_);
auto task_runner = task_runner_;
endpoint_->Sync([task_runner, on_connect_callback] {
task_runner->PostTask(on_connect_callback);
});
}
void FakeProducer::OnDisconnect() {
PERFETTO_DCHECK_THREAD(thread_checker_);
PERFETTO_FATAL("Producer unexpectedly disconnected from the service");
}
void FakeProducer::SetupDataSource(DataSourceInstanceID,
const DataSourceConfig&) {
task_runner_->PostTask(on_setup_data_source_instance_);
}
void FakeProducer::StartDataSource(DataSourceInstanceID,
const DataSourceConfig& source_config) {
PERFETTO_DCHECK_THREAD(thread_checker_);
if (trace_writer_) {
// Startup tracing was already active, just bind the target buffer.
endpoint_->MaybeSharedMemoryArbiter()->BindStartupTargetBuffer(
kStartupTargetBufferReservationId,
static_cast<BufferID>(source_config.target_buffer()));
} else {
// Common case: Start tracing now.
trace_writer_ = endpoint_->CreateTraceWriter(
static_cast<BufferID>(source_config.target_buffer()));
SetupFromConfig(source_config.for_testing());
}
if (source_config.for_testing().send_batch_on_register()) {
ProduceEventBatch(on_create_data_source_instance_);
} else {
task_runner_->PostTask(on_create_data_source_instance_);
}
}
void FakeProducer::StopDataSource(DataSourceInstanceID) {
PERFETTO_DCHECK_THREAD(thread_checker_);
trace_writer_.reset();
}
// Note: this can be called on a different thread.
void FakeProducer::ProduceStartupEventBatch(
const protos::gen::TestConfig& config,
SharedMemoryArbiter* arbiter,
std::function<void()> callback) {
task_runner_->PostTask([this, config, arbiter, callback] {
SetupFromConfig(config);
PERFETTO_CHECK(!trace_writer_);
trace_writer_ =
arbiter->CreateStartupTraceWriter(kStartupTargetBufferReservationId);
EmitEventBatchOnTaskRunner({});
// Issue callback right after writing - cannot wait for flush yet because
// we're not connected yet.
callback();
});
}
// Note: this can be called on a different thread.
void FakeProducer::ProduceEventBatch(std::function<void()> callback) {
task_runner_->PostTask(
[this, callback] { EmitEventBatchOnTaskRunner(callback); });
}
void FakeProducer::RegisterDataSource(const DataSourceDescriptor& desc) {
task_runner_->PostTask([this, desc] { endpoint_->RegisterDataSource(desc); });
}
void FakeProducer::CommitData(const CommitDataRequest& req,
std::function<void()> callback) {
task_runner_->PostTask(
[this, req, callback] { endpoint_->CommitData(req, callback); });
}
void FakeProducer::Sync(std::function<void()> callback) {
task_runner_->PostTask([this, callback] { endpoint_->Sync(callback); });
}
void FakeProducer::OnTracingSetup() {}
void FakeProducer::Flush(FlushRequestID flush_request_id,
const DataSourceInstanceID*,
size_t num_data_sources) {
PERFETTO_DCHECK(num_data_sources > 0);
if (trace_writer_)
trace_writer_->Flush();
endpoint_->NotifyFlushComplete(flush_request_id);
}
base::SocketHandle FakeProducer::unix_socket_fd() {
// Since FakeProducer is only used in tests we can include and assume the
// implementation.
auto* producer = static_cast<ProducerIPCClientImpl*>(endpoint_.get());
auto* ipc_client =
static_cast<ipc::ClientImpl*>(producer->GetClientForTesting());
return ipc_client->GetUnixSocketForTesting()->fd();
}
void FakeProducer::SetupFromConfig(const protos::gen::TestConfig& config) {
rnd_engine_ = std::minstd_rand0(config.seed());
message_count_ = config.message_count();
message_size_ = config.message_size();
max_messages_per_second_ = config.max_messages_per_second();
}
void FakeProducer::EmitEventBatchOnTaskRunner(std::function<void()> callback) {
PERFETTO_CHECK(trace_writer_);
PERFETTO_CHECK(message_size_ > 1);
std::unique_ptr<char, base::FreeDeleter> payload(
static_cast<char*>(malloc(message_size_)));
memset(payload.get(), '.', message_size_);
payload.get()[message_size_ - 1] = 0;
base::TimeMillis start = base::GetWallTimeMs();
int64_t iterations = 0;
uint32_t messages_to_emit = message_count_;
while (messages_to_emit > 0) {
uint32_t messages_in_minibatch =
max_messages_per_second_ == 0
? messages_to_emit
: std::min(max_messages_per_second_, messages_to_emit);
PERFETTO_DCHECK(messages_to_emit >= messages_in_minibatch);
for (uint32_t i = 0; i < messages_in_minibatch; i++) {
auto handle = trace_writer_->NewTracePacket();
handle->set_for_testing()->set_seq_value(
static_cast<uint32_t>(rnd_engine_()));
handle->set_for_testing()->set_str(payload.get(), message_size_);
}
messages_to_emit -= messages_in_minibatch;
iterations++;
// Pause until the second boundary to make sure that we are adhering to
// the speed limitation.
if (max_messages_per_second_ > 0) {
int64_t expected_time_taken = iterations * 1000;
base::TimeMillis time_taken = base::GetWallTimeMs() - start;
while (time_taken.count() < expected_time_taken) {
std::this_thread::sleep_for(
base::TimeMillis(expected_time_taken - time_taken.count()));
time_taken = base::GetWallTimeMs() - start;
}
}
trace_writer_->Flush(messages_to_emit > 0 ? [] {} : callback);
}
}
} // namespace perfetto
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <BeastConfig.h>
#include <ripple/app/misc/CanonicalTXSet.h>
namespace ripple {
bool CanonicalTXSet::Key::operator< (Key const& rhs) const
{
if (mAccount < rhs.mAccount) return true;
if (mAccount > rhs.mAccount) return false;
if (mSeq < rhs.mSeq) return true;
if (mSeq > rhs.mSeq) return false;
return mTXid < rhs.mTXid;
}
bool CanonicalTXSet::Key::operator> (Key const& rhs) const
{
if (mAccount > rhs.mAccount) return true;
if (mAccount < rhs.mAccount) return false;
if (mSeq > rhs.mSeq) return true;
if (mSeq < rhs.mSeq) return false;
return mTXid > rhs.mTXid;
}
bool CanonicalTXSet::Key::operator<= (Key const& rhs) const
{
if (mAccount < rhs.mAccount) return true;
if (mAccount > rhs.mAccount) return false;
if (mSeq < rhs.mSeq) return true;
if (mSeq > rhs.mSeq) return false;
return mTXid <= rhs.mTXid;
}
bool CanonicalTXSet::Key::operator>= (Key const& rhs)const
{
if (mAccount > rhs.mAccount) return true;
if (mAccount < rhs.mAccount) return false;
if (mSeq > rhs.mSeq) return true;
if (mSeq < rhs.mSeq) return false;
return mTXid >= rhs.mTXid;
}
void CanonicalTXSet::insert (std::shared_ptr<STTx const> const& txn)
{
uint256 effectiveAccount = mSetHash;
effectiveAccount ^= to256 (txn->getAccountID(sfAccount));
mMap.insert (std::make_pair (
Key (effectiveAccount, txn->getSequence (), txn->getTransactionID ()),
txn));
}
CanonicalTXSet::iterator CanonicalTXSet::erase (iterator const& it)
{
iterator tmp = it;
++tmp;
mMap.erase (it);
return tmp;
}
} // ripple
|
// Copyright (c) 2016, Monero Research Labs
//
// Author: Shen Noether <shen.noether@gmx.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:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "epee/misc_log_ex.h"
#include "common/perf_timer.h"
#include "common/threadpool.h"
#include "common/util.h"
#include "rctSigs.h"
#include "bulletproofs.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_config.h"
#undef OXEN_DEFAULT_LOG_CATEGORY
#define OXEN_DEFAULT_LOG_CATEGORY "ringct"
#define CHECK_AND_ASSERT_MES_L1(expr, ret, message) {if(!(expr)) {MCERROR("verify", message); return ret;}}
namespace
{
rct::Bulletproof make_dummy_bulletproof(const std::vector<uint64_t> &outamounts, rct::keyV &C, rct::keyV &masks)
{
const size_t n_outs = outamounts.size();
const rct::key I = rct::identity();
size_t nrl = 0;
while ((1u << nrl) < n_outs)
++nrl;
nrl += 6;
C.resize(n_outs);
masks.resize(n_outs);
for (size_t i = 0; i < n_outs; ++i)
{
masks[i] = I;
rct::key sv8, sv;
sv = rct::zero();
sv.bytes[0] = outamounts[i] & 255;
sv.bytes[1] = (outamounts[i] >> 8) & 255;
sv.bytes[2] = (outamounts[i] >> 16) & 255;
sv.bytes[3] = (outamounts[i] >> 24) & 255;
sv.bytes[4] = (outamounts[i] >> 32) & 255;
sv.bytes[5] = (outamounts[i] >> 40) & 255;
sv.bytes[6] = (outamounts[i] >> 48) & 255;
sv.bytes[7] = (outamounts[i] >> 56) & 255;
sc_mul(sv8.bytes, sv.bytes, rct::INV_EIGHT.bytes);
rct::addKeys2(C[i], rct::INV_EIGHT, sv8, rct::H);
}
return rct::Bulletproof{rct::keyV(n_outs, I), I, I, I, I, I, I, rct::keyV(nrl, I), rct::keyV(nrl, I), I, I, I};
}
}
namespace rct {
Bulletproof proveRangeBulletproof(keyV &C, keyV &masks, const std::vector<uint64_t> &amounts, epee::span<const key> sk, hw::device &hwdev)
{
CHECK_AND_ASSERT_THROW_MES(amounts.size() == sk.size(), "Invalid amounts/sk sizes");
masks.resize(amounts.size());
for (size_t i = 0; i < masks.size(); ++i)
masks[i] = hwdev.genCommitmentMask(sk[i]);
Bulletproof proof = bulletproof_PROVE(amounts, masks);
CHECK_AND_ASSERT_THROW_MES(proof.V.size() == amounts.size(), "V does not have the expected size");
C = proof.V;
return proof;
}
bool verBulletproof(const Bulletproof &proof)
{
try { return bulletproof_VERIFY(proof); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
bool verBulletproof(const std::vector<const Bulletproof*> &proofs)
{
try { return bulletproof_VERIFY(proofs); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
//Borromean (c.f. gmax/andytoshi's paper)
bool verifyBorromean(const boroSig &bb, const ge_p3 P1[64], const ge_p3 P2[64]) {
key64 Lv1; key chash, LL;
int ii = 0;
ge_p2 p2;
for (ii = 0 ; ii < 64 ; ii++) {
// equivalent of: addKeys2(LL, bb.s0[ii], bb.ee, P1[ii]);
ge_double_scalarmult_base_vartime(&p2, bb.ee.bytes, &P1[ii], bb.s0[ii].bytes);
ge_tobytes(LL.bytes, &p2);
chash = hash_to_scalar(LL);
// equivalent of: addKeys2(Lv1[ii], bb.s1[ii], chash, P2[ii]);
ge_double_scalarmult_base_vartime(&p2, chash.bytes, &P2[ii], bb.s1[ii].bytes);
ge_tobytes(Lv1[ii].bytes, &p2);
}
key eeComputed = hash_to_scalar(Lv1); //hash function fine
return equalKeys(eeComputed, bb.ee);
}
bool verifyBorromean(const boroSig &bb, const key64 P1, const key64 P2) {
ge_p3 P1_p3[64], P2_p3[64];
for (size_t i = 0 ; i < 64 ; ++i) {
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) == 0, false, "point conv failed");
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) == 0, false, "point conv failed");
}
return verifyBorromean(bb, P1_p3, P2_p3);
}
// Generate a CLSAG signature
// See paper by Goodell et al. (https://eprint.iacr.org/2019/654)
//
// The keys are set as follows:
// P[l] == p*G
// C[l] == z*G
// C[i] == C_nonzero[i] - C_offset (for hashing purposes) for all i
clsag CLSAG_Gen(const key &message, const keyV & P, const key & p, const keyV & C, const key & z, const keyV & C_nonzero, const key & C_offset, const unsigned int l, const multisig_kLRki *kLRki, key *mscout, key *mspout, hw::device &hwdev) {
clsag sig;
size_t n = P.size(); // ring size
CHECK_AND_ASSERT_THROW_MES(n == C.size(), "Signing and commitment key vector sizes must match!");
CHECK_AND_ASSERT_THROW_MES(n == C_nonzero.size(), "Signing and commitment key vector sizes must match!");
CHECK_AND_ASSERT_THROW_MES(l < n, "Signing index out of range!");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
CHECK_AND_ASSERT_THROW_MES((mscout && mspout) || !kLRki, "Multisig pointers are not all present");
// Key images
ge_p3 H_p3;
hash_to_p3(H_p3,P[l]);
key H;
ge_p3_tobytes(H.bytes,&H_p3);
key D;
// Initial values
key a;
key aG;
key aH;
// Multisig
if (kLRki)
{
sig.I = kLRki->ki;
scalarmultKey(D,H,z);
}
else
{
hwdev.clsag_prepare(p,z,sig.I,D,H,a,aG,aH);
}
geDsmp I_precomp;
geDsmp D_precomp;
precomp(I_precomp.k,sig.I);
precomp(D_precomp.k,D);
// Offset key image
scalarmultKey(sig.D,D,INV_EIGHT);
// Aggregation hashes
keyV mu_P_to_hash(2*n+4); // domain, I, D, P, C, C_offset
keyV mu_C_to_hash(2*n+4); // domain, I, D, P, C, C_offset
sc_0(mu_P_to_hash[0].bytes);
memcpy(mu_P_to_hash[0].bytes, cryptonote::hashkey::CLSAG_AGG_0.data(), cryptonote::hashkey::CLSAG_AGG_0.size());
sc_0(mu_C_to_hash[0].bytes);
memcpy(mu_C_to_hash[0].bytes, cryptonote::hashkey::CLSAG_AGG_1.data(), cryptonote::hashkey::CLSAG_AGG_1.size());
for (size_t i = 1; i < n+1; ++i) {
mu_P_to_hash[i] = P[i-1];
mu_C_to_hash[i] = P[i-1];
}
for (size_t i = n+1; i < 2*n+1; ++i) {
mu_P_to_hash[i] = C_nonzero[i-n-1];
mu_C_to_hash[i] = C_nonzero[i-n-1];
}
mu_P_to_hash[2*n+1] = sig.I;
mu_P_to_hash[2*n+2] = sig.D;
mu_P_to_hash[2*n+3] = C_offset;
mu_C_to_hash[2*n+1] = sig.I;
mu_C_to_hash[2*n+2] = sig.D;
mu_C_to_hash[2*n+3] = C_offset;
key mu_P, mu_C;
mu_P = hash_to_scalar(mu_P_to_hash);
mu_C = hash_to_scalar(mu_C_to_hash);
// Initial commitment
keyV c_to_hash(2*n+5); // domain, P, C, C_offset, message, aG, aH
key c;
sc_0(c_to_hash[0].bytes);
memcpy(c_to_hash[0].bytes, cryptonote::hashkey::CLSAG_ROUND.data(), cryptonote::hashkey::CLSAG_ROUND.size());
for (size_t i = 1; i < n+1; ++i)
{
c_to_hash[i] = P[i-1];
c_to_hash[i+n] = C_nonzero[i-1];
}
c_to_hash[2*n+1] = C_offset;
c_to_hash[2*n+2] = message;
// Multisig data is present
if (kLRki)
{
a = kLRki->k;
c_to_hash[2*n+3] = kLRki->L;
c_to_hash[2*n+4] = kLRki->R;
}
else
{
c_to_hash[2*n+3] = aG;
c_to_hash[2*n+4] = aH;
}
hwdev.clsag_hash(c_to_hash,c);
size_t i;
i = (l + 1) % n;
if (i == 0)
copy(sig.c1, c);
// Decoy indices
sig.s = keyV(n);
key c_new;
key L;
key R;
key c_p; // = c[i]*mu_P
key c_c; // = c[i]*mu_C
geDsmp P_precomp;
geDsmp C_precomp;
geDsmp H_precomp;
ge_p3 Hi_p3;
while (i != l) {
sig.s[i] = skGen();
sc_0(c_new.bytes);
sc_mul(c_p.bytes,mu_P.bytes,c.bytes);
sc_mul(c_c.bytes,mu_C.bytes,c.bytes);
// Precompute points
precomp(P_precomp.k,P[i]);
precomp(C_precomp.k,C[i]);
// Compute L
addKeys_aGbBcC(L,sig.s[i],c_p,P_precomp.k,c_c,C_precomp.k);
// Compute R
hash_to_p3(Hi_p3,P[i]);
ge_dsm_precomp(H_precomp.k, &Hi_p3);
addKeys_aAbBcC(R,sig.s[i],H_precomp.k,c_p,I_precomp.k,c_c,D_precomp.k);
c_to_hash[2*n+3] = L;
c_to_hash[2*n+4] = R;
hwdev.clsag_hash(c_to_hash,c_new);
copy(c,c_new);
i = (i + 1) % n;
if (i == 0)
copy(sig.c1,c);
}
// Compute final scalar
hwdev.clsag_sign(c,a,p,z,mu_P,mu_C,sig.s[l]);
memwipe(&a, sizeof(key));
if (mscout)
*mscout = c;
if (mspout)
*mspout = mu_P;
return sig;
}
clsag CLSAG_Gen(const key &message, const keyV & P, const key & p, const keyV & C, const key & z, const keyV & C_nonzero, const key & C_offset, const unsigned int l) {
return CLSAG_Gen(message, P, p, C, z, C_nonzero, C_offset, l, NULL, NULL, NULL, hw::get_device("default"));
}
// MLSAG signatures
// See paper by Noether (https://eprint.iacr.org/2015/1098)
// This generalization allows for some dimensions not to require linkability;
// this is used in practice for commitment data within signatures
// Note that using more than one linkable dimension is not recommended.
bool MLSAG_Ver(const key &message, const keyM & pk, const mgSig & rv, size_t dsRows) {
size_t cols = pk.size();
CHECK_AND_ASSERT_MES(cols >= 2, false, "Signature must contain more than one public key");
size_t rows = pk[0].size();
CHECK_AND_ASSERT_MES(rows >= 1, false, "Bad total row number");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_MES(pk[i].size() == rows, false, "Bad public key matrix dimensions");
}
CHECK_AND_ASSERT_MES(rv.II.size() == dsRows, false, "Wrong number of key images present");
CHECK_AND_ASSERT_MES(rv.ss.size() == cols, false, "Bad scalar matrix dimensions");
for (size_t i = 0; i < cols; ++i) {
CHECK_AND_ASSERT_MES(rv.ss[i].size() == rows, false, "Bad scalar matrix dimensions");
}
CHECK_AND_ASSERT_MES(dsRows <= rows, false, "Non-double-spend rows cannot exceed total rows");
for (size_t i = 0; i < rv.ss.size(); ++i) {
for (size_t j = 0; j < rv.ss[i].size(); ++j) {
CHECK_AND_ASSERT_MES(sc_check(rv.ss[i][j].bytes) == 0, false, "Bad signature scalar");
}
}
CHECK_AND_ASSERT_MES(sc_check(rv.cc.bytes) == 0, false, "Bad initial signature hash");
size_t i = 0, j = 0, ii = 0;
key c, L, R;
key c_old = copy(rv.cc);
std::vector<geDsmp> Ip(dsRows);
for (i = 0 ; i < dsRows ; i++) {
CHECK_AND_ASSERT_MES(!(rv.II[i] == rct::identity()), false, "Bad key image");
precomp(Ip[i].k, rv.II[i]);
}
size_t ndsRows = 3 * dsRows; // number of dimensions not requiring linkability
keyV toHash(1 + 3 * dsRows + 2 * (rows - dsRows));
toHash[0] = message;
i = 0;
while (i < cols) {
sc_0(c.bytes);
for (j = 0; j < dsRows; j++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
// Compute R directly
ge_p3 hash8_p3;
hash_to_p3(hash8_p3, pk[i][j]);
ge_p2 R_p2;
ge_double_scalarmult_precomp_vartime(&R_p2, rv.ss[i][j].bytes, &hash8_p3, c_old.bytes, Ip[j].k);
ge_tobytes(R.bytes, &R_p2);
toHash[3 * j + 1] = pk[i][j];
toHash[3 * j + 2] = L;
toHash[3 * j + 3] = R;
}
for (j = dsRows, ii = 0 ; j < rows ; j++, ii++) {
addKeys2(L, rv.ss[i][j], c_old, pk[i][j]);
toHash[ndsRows + 2 * ii + 1] = pk[i][j];
toHash[ndsRows + 2 * ii + 2] = L;
}
c = hash_to_scalar(toHash);
CHECK_AND_ASSERT_MES(!(c == rct::zero()), false, "Bad signature hash");
copy(c_old, c);
i = (i + 1);
}
sc_sub(c.bytes, c_old.bytes, rv.cc.bytes);
return sc_isnonzero(c.bytes) == 0;
}
//proveRange and verRange
//proveRange gives C, and mask such that \sumCi = C
// c.f. https://eprint.iacr.org/2015/1098 section 5.1
// and Ci is a commitment to either 0 or 2^i, i=0,...,63
// thus this proves that "amount" is in [0, 2^64]
// mask is a such that C = aG + bH, and b = amount
//verRange verifies that \sum Ci = C and that each Ci is a commitment to 0 or 2^i
bool verRange(const key & C, const rangeSig & as) {
try
{
PERF_TIMER(verRange);
ge_p3 CiH[64], asCi[64];
int i = 0;
ge_p3 Ctmp_p3 = ge_p3_identity;
for (i = 0; i < 64; i++) {
// faster equivalent of:
// subKeys(CiH[i], as.Ci[i], H2[i]);
// addKeys(Ctmp, Ctmp, as.Ci[i]);
ge_cached cached;
ge_p3 p3;
ge_p1p1 p1;
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, H2[i].bytes) == 0, false, "point conv failed");
ge_p3_to_cached(&cached, &p3);
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&asCi[i], as.Ci[i].bytes) == 0, false, "point conv failed");
ge_sub(&p1, &asCi[i], &cached);
ge_p3_to_cached(&cached, &asCi[i]);
ge_p1p1_to_p3(&CiH[i], &p1);
ge_add(&p1, &Ctmp_p3, &cached);
ge_p1p1_to_p3(&Ctmp_p3, &p1);
}
key Ctmp;
ge_p3_tobytes(Ctmp.bytes, &Ctmp_p3);
if (!equalKeys(C, Ctmp))
return false;
if (!verifyBorromean(as.asig, asCi, CiH))
return false;
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
key get_pre_clsag_hash(const rctSig &rv, hw::device &hwdev)
{
keyV hashes;
hashes.reserve(3);
hashes.push_back(rv.message);
crypto::hash h;
CHECK_AND_ASSERT_THROW_MES(!rv.mixRing.empty(), "Empty mixRing");
const size_t inputs = is_rct_simple(rv.type) ? rv.mixRing.size() : rv.mixRing[0].size();
const size_t outputs = rv.ecdhInfo.size();
key prehash;
std::string blob;
{
serialization::binary_string_archiver ba;
const_cast<rctSig&>(rv).serialize_rctsig_base(ba, inputs, outputs);
blob = ba.str();
}
cryptonote::get_blob_hash(blob, h);
hashes.push_back(hash2rct(h));
keyV kv;
if (rct::is_rct_bulletproof(rv.type))
{
kv.reserve((6*2+9) * rv.p.bulletproofs.size());
for (const auto &p: rv.p.bulletproofs)
{
// V are not hashed as they're expanded from outPk.mask
// (and thus hashed as part of rctSigBase above)
kv.push_back(p.A);
kv.push_back(p.S);
kv.push_back(p.T1);
kv.push_back(p.T2);
kv.push_back(p.taux);
kv.push_back(p.mu);
for (size_t n = 0; n < p.L.size(); ++n)
kv.push_back(p.L[n]);
for (size_t n = 0; n < p.R.size(); ++n)
kv.push_back(p.R[n]);
kv.push_back(p.a);
kv.push_back(p.b);
kv.push_back(p.t);
}
}
else
{
kv.reserve((64*3+1) * rv.p.rangeSigs.size());
for (const auto &r: rv.p.rangeSigs)
{
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.asig.s0[n]);
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.asig.s1[n]);
kv.push_back(r.asig.ee);
for (size_t n = 0; n < 64; ++n)
kv.push_back(r.Ci[n]);
}
}
hashes.push_back(cn_fast_hash(kv));
hwdev.clsag_prehash(blob, inputs, outputs, hashes, rv.outPk, prehash);
return prehash;
}
clsag proveRctCLSAGSimple(const key &message, const ctkeyV &pubs, const ctkey &inSk, const key &a, const key &Cout, const multisig_kLRki *kLRki, key *mscout, key *mspout, unsigned int index, hw::device &hwdev) {
//setup vars
size_t rows = 1;
size_t cols = pubs.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs");
CHECK_AND_ASSERT_THROW_MES((kLRki && mscout) || (!kLRki && !mscout), "Only one of kLRki/mscout is present");
keyV tmp(rows + 1);
keyV sk(rows + 1);
size_t i;
keyM M(cols, tmp);
keyV P, C, C_nonzero;
P.reserve(pubs.size());
C.reserve(pubs.size());
C_nonzero.reserve(pubs.size());
for (const ctkey &k: pubs)
{
P.push_back(k.dest);
C_nonzero.push_back(k.mask);
rct::key tmp;
subKeys(tmp, k.mask, Cout);
C.push_back(tmp);
}
sk[0] = copy(inSk.dest);
sc_sub(sk[1].bytes, inSk.mask.bytes, a.bytes);
clsag result = CLSAG_Gen(message, P, sk[0], C, sk[1], C_nonzero, Cout, index, kLRki, mscout, mspout, hwdev);
memwipe(sk.data(), sk.size() * sizeof(key));
return result;
}
//Ring-ct MG sigs
//Prove:
// c.f. https://eprint.iacr.org/2015/1098 section 4. definition 10.
// This does the MG sig on the "dest" part of the given key matrix, and
// the last row is the sum of input commitments from that column - sum output commitments
// this shows that sum inputs = sum outputs
//Ver:
// verifies the above sig is created corretly
bool verRctMG(const mgSig &mg, const ctkeyM & pubs, const ctkeyV & outPk, const key &txnFeeKey, const key &message) {
PERF_TIMER(verRctMG);
//setup vars
size_t cols = pubs.size();
CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs");
size_t rows = pubs[0].size();
CHECK_AND_ASSERT_MES(rows >= 1, false, "Empty pubs");
for (size_t i = 1; i < cols; ++i) {
CHECK_AND_ASSERT_MES(pubs[i].size() == rows, false, "pubs is not rectangular");
}
keyV tmp(rows + 1);
size_t i = 0, j = 0;
for (i = 0; i < rows + 1; i++) {
identity(tmp[i]);
}
keyM M(cols, tmp);
//create the matrix to mg sig
for (j = 0; j < rows; j++) {
for (i = 0; i < cols; i++) {
M[i][j] = pubs[i][j].dest;
addKeys(M[i][rows], M[i][rows], pubs[i][j].mask); //add Ci in last row
}
}
for (i = 0; i < cols; i++) {
for (j = 0; j < outPk.size(); j++) {
subKeys(M[i][rows], M[i][rows], outPk[j].mask); //subtract output Ci's in last row
}
//subtract txn fee output in last row
subKeys(M[i][rows], M[i][rows], txnFeeKey);
}
return MLSAG_Ver(message, M, mg, rows);
}
//Ring-ct Simple MG sigs
//Ver:
//This does a simplified version, assuming only post Rct
//inputs
bool verRctMGSimple(const key &message, const mgSig &mg, const ctkeyV & pubs, const key & C) {
try
{
PERF_TIMER(verRctMGSimple);
//setup vars
size_t rows = 1;
size_t cols = pubs.size();
CHECK_AND_ASSERT_MES(cols >= 1, false, "Empty pubs");
keyV tmp(rows + 1);
size_t i;
keyM M(cols, tmp);
ge_p3 Cp3;
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&Cp3, C.bytes) == 0, false, "point conv failed");
ge_cached Ccached;
ge_p3_to_cached(&Ccached, &Cp3);
ge_p1p1 p1;
//create the matrix to mg sig
for (i = 0; i < cols; i++) {
M[i][0] = pubs[i].dest;
ge_p3 p3;
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&p3, pubs[i].mask.bytes) == 0, false, "point conv failed");
ge_sub(&p1, &p3, &Ccached);
ge_p1p1_to_p3(&p3, &p1);
ge_p3_tobytes(M[i][1].bytes, &p3);
}
//DP(C);
return MLSAG_Ver(message, M, mg, rows);
}
catch (...) { return false; }
}
bool verRctCLSAGSimple(const key &message, const clsag &sig, const ctkeyV & pubs, const key & C_offset) {
try
{
PERF_TIMER(verRctCLSAGSimple);
const size_t n = pubs.size();
// Check data
CHECK_AND_ASSERT_MES(n >= 1, false, "Empty pubs");
CHECK_AND_ASSERT_MES(n == sig.s.size(), false, "Signature scalar vector is the wrong size!");
for (size_t i = 0; i < n; ++i)
CHECK_AND_ASSERT_MES(sc_check(sig.s[i].bytes) == 0, false, "Bad signature scalar!");
CHECK_AND_ASSERT_MES(sc_check(sig.c1.bytes) == 0, false, "Bad signature commitment!");
CHECK_AND_ASSERT_MES(!(sig.I == rct::identity()), false, "Bad key image!");
// Cache commitment offset for efficient subtraction later
ge_p3 C_offset_p3;
CHECK_AND_ASSERT_MES(ge_frombytes_vartime(&C_offset_p3, C_offset.bytes) == 0, false, "point conv failed");
ge_cached C_offset_cached;
ge_p3_to_cached(&C_offset_cached, &C_offset_p3);
// Prepare key images
key c = copy(sig.c1);
key D_8 = scalarmult8(sig.D);
CHECK_AND_ASSERT_MES(!(D_8 == rct::identity()), false, "Bad auxiliary key image!");
geDsmp I_precomp;
geDsmp D_precomp;
precomp(I_precomp.k,sig.I);
precomp(D_precomp.k,D_8);
// Aggregation hashes
keyV mu_P_to_hash(2*n+4); // domain, I, D, P, C, C_offset
keyV mu_C_to_hash(2*n+4); // domain, I, D, P, C, C_offset
sc_0(mu_P_to_hash[0].bytes);
memcpy(mu_P_to_hash[0].bytes, cryptonote::hashkey::CLSAG_AGG_0.data(), cryptonote::hashkey::CLSAG_AGG_0.size());
sc_0(mu_C_to_hash[0].bytes);
memcpy(mu_C_to_hash[0].bytes, cryptonote::hashkey::CLSAG_AGG_1.data(), cryptonote::hashkey::CLSAG_AGG_1.size());
for (size_t i = 1; i < n+1; ++i) {
mu_P_to_hash[i] = pubs[i-1].dest;
mu_C_to_hash[i] = pubs[i-1].dest;
}
for (size_t i = n+1; i < 2*n+1; ++i) {
mu_P_to_hash[i] = pubs[i-n-1].mask;
mu_C_to_hash[i] = pubs[i-n-1].mask;
}
mu_P_to_hash[2*n+1] = sig.I;
mu_P_to_hash[2*n+2] = sig.D;
mu_P_to_hash[2*n+3] = C_offset;
mu_C_to_hash[2*n+1] = sig.I;
mu_C_to_hash[2*n+2] = sig.D;
mu_C_to_hash[2*n+3] = C_offset;
key mu_P, mu_C;
mu_P = hash_to_scalar(mu_P_to_hash);
mu_C = hash_to_scalar(mu_C_to_hash);
// Set up round hash
keyV c_to_hash(2*n+5); // domain, P, C, C_offset, message, L, R
sc_0(c_to_hash[0].bytes);
memcpy(c_to_hash[0].bytes, cryptonote::hashkey::CLSAG_ROUND.data(), cryptonote::hashkey::CLSAG_ROUND.size());
for (size_t i = 1; i < n+1; ++i)
{
c_to_hash[i] = pubs[i-1].dest;
c_to_hash[i+n] = pubs[i-1].mask;
}
c_to_hash[2*n+1] = C_offset;
c_to_hash[2*n+2] = message;
key c_p; // = c[i]*mu_P
key c_c; // = c[i]*mu_C
key c_new;
key L;
key R;
geDsmp P_precomp;
geDsmp C_precomp;
geDsmp H_precomp;
size_t i = 0;
ge_p3 hash8_p3;
geDsmp hash_precomp;
ge_p3 temp_p3;
ge_p1p1 temp_p1;
while (i < n) {
sc_0(c_new.bytes);
sc_mul(c_p.bytes,mu_P.bytes,c.bytes);
sc_mul(c_c.bytes,mu_C.bytes,c.bytes);
// Precompute points for L/R
precomp(P_precomp.k,pubs[i].dest);
CHECK_AND_ASSERT_MES(ge_frombytes_vartime(&temp_p3, pubs[i].mask.bytes) == 0, false, "point conv failed");
ge_sub(&temp_p1,&temp_p3,&C_offset_cached);
ge_p1p1_to_p3(&temp_p3,&temp_p1);
ge_dsm_precomp(C_precomp.k,&temp_p3);
// Compute L
addKeys_aGbBcC(L,sig.s[i],c_p,P_precomp.k,c_c,C_precomp.k);
// Compute R
hash_to_p3(hash8_p3,pubs[i].dest);
ge_dsm_precomp(hash_precomp.k, &hash8_p3);
addKeys_aAbBcC(R,sig.s[i],hash_precomp.k,c_p,I_precomp.k,c_c,D_precomp.k);
c_to_hash[2*n+3] = L;
c_to_hash[2*n+4] = R;
c_new = hash_to_scalar(c_to_hash);
CHECK_AND_ASSERT_MES(!(c_new == rct::zero()), false, "Bad signature hash");
copy(c,c_new);
i = i + 1;
}
sc_sub(c_new.bytes,c.bytes,sig.c1.bytes);
return sc_isnonzero(c_new.bytes) == 0;
}
catch (...) { return false; }
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
void getKeyFromBlockchain(ctkey & a, size_t reference_index) {
a.mask = pkGen();
a.dest = pkGen();
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" + 1 columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
std::tuple<ctkeyM, xmr_amount> populateFromBlockchain(ctkeyV inPk, int mixin) {
int rows = inPk.size();
ctkeyM rv(mixin + 1, inPk);
int index = randXmrAmount(mixin);
int i = 0, j = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
for (j = 0; j < rows; j++) {
getKeyFromBlockchain(rv[i][j], (size_t)randXmrAmount);
}
}
}
return std::make_tuple(rv, index);
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
xmr_amount populateFromBlockchainSimple(ctkeyV & mixRing, const ctkey & inPk, int mixin) {
int index = randXmrAmount(mixin);
int i = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
getKeyFromBlockchain(mixRing[i], (size_t)randXmrAmount(1000));
} else {
mixRing[i] = inPk;
}
}
return index;
}
//RCT simple
//for post-rct only
rctSig genRctSimple(const key &message, const ctkeyV & inSk, const keyV & destinations, const std::vector<xmr_amount> &inamounts, const std::vector<xmr_amount> &outamounts, xmr_amount txnFee, const ctkeyM & mixRing, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, const std::vector<unsigned int> & index, ctkeyV &outSk, const RCTConfig &rct_config, hw::device &hwdev) {
CHECK_AND_ASSERT_THROW_MES(inamounts.size() > 0, "Empty inamounts");
CHECK_AND_ASSERT_THROW_MES(inamounts.size() == inSk.size(), "Different number of inamounts/inSk");
CHECK_AND_ASSERT_THROW_MES(outamounts.size() == destinations.size(), "Different number of amounts/destinations");
CHECK_AND_ASSERT_THROW_MES(amount_keys.size() == destinations.size(), "Different number of amount_keys/destinations");
CHECK_AND_ASSERT_THROW_MES(index.size() == inSk.size(), "Different number of index/inSk");
CHECK_AND_ASSERT_THROW_MES(mixRing.size() == inSk.size(), "Different number of mixRing/inSk");
for (size_t n = 0; n < mixRing.size(); ++n) {
CHECK_AND_ASSERT_THROW_MES(index[n] < mixRing[n].size(), "Bad index into mixRing");
}
CHECK_AND_ASSERT_THROW_MES((kLRki && msout) || (!kLRki && !msout), "Only one of kLRki/msout is present");
if (kLRki && msout) {
CHECK_AND_ASSERT_THROW_MES(kLRki->size() == inamounts.size(), "Mismatched kLRki/inamounts sizes");
}
CHECK_AND_ASSERT_THROW_MES(
rct_config.range_proof_type != RangeProofType::Borromean &&
(rct_config.bp_version == 3 || rct_config.bp_version == 0), // 0 means latest version
"Unable to generate rct for non-CLSAG-bulletproof");
rctSig rv;
rv.type = RCTType::CLSAG;
rv.message = message;
rv.outPk.resize(destinations.size());
rv.ecdhInfo.resize(destinations.size());
size_t i;
keyV masks(destinations.size()); //sk mask..
outSk.resize(destinations.size());
for (i = 0; i < destinations.size(); i++) {
//add destination to sig
rv.outPk[i].dest = copy(destinations[i]);
}
rv.p.bulletproofs.clear();
size_t n_amounts = outamounts.size();
size_t amounts_proved = 0;
if (rct_config.range_proof_type == RangeProofType::PaddedBulletproof)
{
rct::keyV C, masks;
if (hwdev.get_mode() == hw::device::mode::TRANSACTION_CREATE_FAKE)
{
// use a fake bulletproof for speed
rv.p.bulletproofs.push_back(make_dummy_bulletproof(outamounts, C, masks));
}
else
{
const epee::span<const key> keys{&amount_keys[0], amount_keys.size()};
rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, outamounts, keys, hwdev));
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof");
#endif
}
for (i = 0; i < outamounts.size(); ++i)
{
rv.outPk[i].mask = rct::scalarmult8(C[i]);
outSk[i].mask = masks[i];
}
}
else while (amounts_proved < n_amounts)
{
size_t batch_size = 1;
if (rct_config.range_proof_type == RangeProofType::MultiOutputBulletproof)
while (batch_size * 2 + amounts_proved <= n_amounts && batch_size * 2 <= cryptonote::TX_BULLETPROOF_MAX_OUTPUTS)
batch_size *= 2;
rct::keyV C, masks;
std::vector<uint64_t> batch_amounts(batch_size);
for (i = 0; i < batch_size; ++i)
batch_amounts[i] = outamounts[i + amounts_proved];
if (hwdev.get_mode() == hw::device::mode::TRANSACTION_CREATE_FAKE)
{
// use a fake bulletproof for speed
rv.p.bulletproofs.push_back(make_dummy_bulletproof(batch_amounts, C, masks));
}
else
{
const epee::span<const key> keys{&amount_keys[amounts_proved], batch_size};
rv.p.bulletproofs.push_back(proveRangeBulletproof(C, masks, batch_amounts, keys, hwdev));
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof");
#endif
}
for (i = 0; i < batch_size; ++i)
{
rv.outPk[i + amounts_proved].mask = rct::scalarmult8(C[i]);
outSk[i + amounts_proved].mask = masks[i];
}
amounts_proved += batch_size;
}
key sumout = zero();
for (i = 0; i < outSk.size(); ++i)
{
sc_add(sumout.bytes, outSk[i].mask.bytes, sumout.bytes);
//mask amount and mask
rv.ecdhInfo[i].mask = copy(outSk[i].mask);
rv.ecdhInfo[i].amount = d2h(outamounts[i]);
hwdev.ecdhEncode(rv.ecdhInfo[i], amount_keys[i], true);
}
rv.txnFee = txnFee;
rv.mixRing = mixRing;
keyV &pseudoOuts = rv.p.pseudoOuts;
pseudoOuts.resize(inamounts.size());
rv.p.CLSAGs.resize(inamounts.size());
key sumpouts = zero(); //sum pseudoOut masks
keyV a(inamounts.size());
for (i = 0 ; i < inamounts.size() - 1; i++) {
skGen(a[i]);
sc_add(sumpouts.bytes, a[i].bytes, sumpouts.bytes);
genC(pseudoOuts[i], a[i], inamounts[i]);
}
sc_sub(a[i].bytes, sumout.bytes, sumpouts.bytes);
genC(pseudoOuts[i], a[i], inamounts[i]);
DP(pseudoOuts[i]);
key full_message = get_pre_clsag_hash(rv, hwdev);
if (msout)
{
msout->c.resize(inamounts.size());
msout->mu_p.resize(inamounts.size());
}
for (i = 0 ; i < inamounts.size(); i++)
{
rv.p.CLSAGs[i] = proveRctCLSAGSimple(full_message, rv.mixRing[i], inSk[i], a[i], pseudoOuts[i], kLRki ? &(*kLRki)[i]: NULL, msout ? &msout->c[i] : NULL, msout ? &msout->mu_p[i] : NULL, index[i], hwdev);
}
return rv;
}
rctSig genRctSimple(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const std::vector<xmr_amount> &inamounts, const std::vector<xmr_amount> &outamounts, const keyV &amount_keys, const std::vector<multisig_kLRki> *kLRki, multisig_out *msout, xmr_amount txnFee, unsigned int mixin, const RCTConfig &rct_config, hw::device &hwdev) {
std::vector<unsigned int> index;
index.resize(inPk.size());
ctkeyM mixRing;
ctkeyV outSk;
mixRing.resize(inPk.size());
for (size_t i = 0; i < inPk.size(); ++i) {
mixRing[i].resize(mixin+1);
index[i] = populateFromBlockchainSimple(mixRing[i], inPk[i], mixin);
}
return genRctSimple(message, inSk, destinations, inamounts, outamounts, txnFee, mixRing, amount_keys, kLRki, msout, index, outSk, rct_config, hwdev);
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
bool verRct(const rctSig & rv, bool semantics) {
PERF_TIMER(verRct);
CHECK_AND_ASSERT_MES(rv.type == RCTType::Full, false, "verRct called on non-full rctSig");
if (semantics)
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs");
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo");
CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "full rctSig has not one MG");
}
else
{
// semantics check is early, we don't have the MGs resolved yet
}
// some rct ops can throw
try
{
if (semantics) {
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter;
std::deque<bool> results(rv.outPk.size(), false);
DP("range proofs verified?");
for (size_t i = 0; i < rv.outPk.size(); i++)
tpool.submit(&waiter, [&, i] { results[i] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); });
waiter.wait(&tpool);
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("Range proof verified failed for proof " << i);
return false;
}
}
}
if (!semantics) {
//compute txn fee
key txnFeeKey = scalarmultH(d2h(rv.txnFee));
bool mgVerd = verRctMG(rv.p.MGs[0], rv.mixRing, rv.outPk, txnFeeKey, get_pre_clsag_hash(rv, hw::get_device("default")));
DP("mg sig verified?");
DP(mgVerd);
if (!mgVerd) {
LOG_PRINT_L1("MG signature verification failed");
return false;
}
}
return true;
}
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRct: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRct, but not an actual exception");
return false;
}
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctSemanticsSimple(const std::vector<const rctSig*> & rvv) {
try
{
PERF_TIMER(verRctSemanticsSimple);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter;
std::deque<bool> results;
std::vector<const Bulletproof*> proofs;
size_t max_non_bp_proofs = 0, offset = 0;
for (const rctSig *rvp: rvv)
{
CHECK_AND_ASSERT_MES(rvp, false, "rctSig pointer is NULL");
const rctSig &rv = *rvp;
CHECK_AND_ASSERT_MES(rct::is_rct_simple(rv.type), false, "verRctSemanticsSimple called on non simple rctSig");
const bool bulletproof = is_rct_bulletproof(rv.type);
if (bulletproof)
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == n_bulletproof_amounts(rv.p.bulletproofs), false, "Mismatched sizes of outPk and bulletproofs");
if (rv.type == RCTType::CLSAG)
{
CHECK_AND_ASSERT_MES(rv.p.MGs.empty(), false, "MGs are not empty for CLSAG");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.p.CLSAGs.size(), false, "Mismatched sizes of rv.p.pseudoOuts and rv.p.CLSAGs");
}
else
{
CHECK_AND_ASSERT_MES(rv.p.CLSAGs.empty(), false, "CLSAGs are not empty for MLSAG");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.p.pseudoOuts and rv.p.MGs");
}
CHECK_AND_ASSERT_MES(rv.pseudoOuts.empty(), false, "rv.pseudoOuts is not empty");
}
else
{
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.p.rangeSigs.size(), false, "Mismatched sizes of outPk and rv.p.rangeSigs");
CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.p.MGs.size(), false, "Mismatched sizes of rv.pseudoOuts and rv.p.MGs");
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.empty(), false, "rv.p.pseudoOuts is not empty");
}
CHECK_AND_ASSERT_MES(rv.outPk.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outPk and rv.ecdhInfo");
if (!bulletproof)
max_non_bp_proofs += rv.p.rangeSigs.size();
}
results.resize(max_non_bp_proofs);
for (const rctSig *rvp: rvv)
{
const rctSig &rv = *rvp;
const bool bulletproof = is_rct_bulletproof(rv.type);
const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
rct::keyV masks(rv.outPk.size());
for (size_t i = 0; i < rv.outPk.size(); i++) {
masks[i] = rv.outPk[i].mask;
}
key sumOutpks = addKeys(masks);
DP(sumOutpks);
const key txnFeeKey = scalarmultH(d2h(rv.txnFee));
addKeys(sumOutpks, txnFeeKey, sumOutpks);
key sumPseudoOuts = addKeys(pseudoOuts);
DP(sumPseudoOuts);
//check pseudoOuts vs Outs..
if (!equalKeys(sumPseudoOuts, sumOutpks)) {
LOG_PRINT_L1("Sum check failed");
return false;
}
if (bulletproof)
{
for (size_t i = 0; i < rv.p.bulletproofs.size(); i++)
proofs.push_back(&rv.p.bulletproofs[i]);
}
else
{
for (size_t i = 0; i < rv.p.rangeSigs.size(); i++)
tpool.submit(&waiter, [&, i, offset] { results[i+offset] = verRange(rv.outPk[i].mask, rv.p.rangeSigs[i]); });
offset += rv.p.rangeSigs.size();
}
}
if (!proofs.empty() && !verBulletproof(proofs))
{
LOG_PRINT_L1("Aggregate range proof verified failed");
return false;
}
waiter.wait(&tpool);
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("Range proof verified failed for proof " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRctSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRctSemanticsSimple, but not an actual exception");
return false;
}
}
bool verRctSemanticsSimple(const rctSig & rv)
{
return verRctSemanticsSimple(std::vector<const rctSig*>(1, &rv));
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctNonSemanticsSimple(const rctSig & rv) {
try
{
PERF_TIMER(verRctNonSemanticsSimple);
CHECK_AND_ASSERT_MES(rct::is_rct_simple(rv.type), false, "verRctNonSemanticsSimple called on non simple rctSig");
const bool bulletproof = is_rct_bulletproof(rv.type);
// semantics check is early, and mixRing/MGs aren't resolved yet
if (bulletproof)
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.p.pseudoOuts and mixRing");
else
CHECK_AND_ASSERT_MES(rv.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.pseudoOuts and mixRing");
const size_t threads = std::max(rv.outPk.size(), rv.mixRing.size());
std::deque<bool> results(threads);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter;
const keyV &pseudoOuts = bulletproof ? rv.p.pseudoOuts : rv.pseudoOuts;
const key message = get_pre_clsag_hash(rv, hw::get_device("default"));
results.clear();
results.resize(rv.mixRing.size());
for (size_t i = 0 ; i < rv.mixRing.size() ; i++) {
tpool.submit(&waiter, [&, i] {
if (rv.type == RCTType::CLSAG)
results[i] = verRctCLSAGSimple(message, rv.p.CLSAGs[i], rv.mixRing[i], pseudoOuts[i]);
else
results[i] = verRctMGSimple(message, rv.p.MGs[i], rv.mixRing[i], pseudoOuts[i]);
});
}
waiter.wait(&tpool);
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
LOG_PRINT_L1("verRctMGSimple/verRctCLSAGSimple failed for input " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
LOG_PRINT_L1("Error in verRctNonSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
LOG_PRINT_L1("Error in verRctNonSemanticsSimple, but not an actual exception");
return false;
}
}
//RingCT protocol
//genRct:
// creates an rctSig with all data necessary to verify the rangeProofs and that the signer owns one of the
// columns that are claimed as inputs, and that the sum of inputs = sum of outputs.
// Also contains masked "amount" and "mask" so the receiver can see how much they received
//verRct:
// verifies that all signatures (rangeProogs, MG sig, sum inputs = outputs) are correct
//decodeRct: (c.f. https://eprint.iacr.org/2015/1098 section 5.1.1)
// uses the attached ecdh info to find the amounts represented by each output commitment
// must know the destination private key to find the correct amount, else will return a random number
xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, key & mask, hw::device &hwdev) {
CHECK_AND_ASSERT_MES(rv.type == RCTType::Full, false, "decodeRct called on non-full rctSig");
CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index");
CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo");
//mask amount and mask
ecdhTuple ecdh_info = rv.ecdhInfo[i];
hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTType::Bulletproof2 || rv.type == RCTType::CLSAG);
mask = ecdh_info.mask;
key amount = ecdh_info.amount;
key C = rv.outPk[i].mask;
DP("C");
DP(C);
key Ctmp;
CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask");
CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount");
addKeys2(Ctmp, mask, amount, H);
DP("Ctmp");
DP(Ctmp);
if (equalKeys(C, Ctmp) == false) {
CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend");
}
return h2d(amount);
}
xmr_amount decodeRct(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) {
key mask;
return decodeRct(rv, sk, i, mask, hwdev);
}
xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, key &mask, hw::device &hwdev) {
CHECK_AND_ASSERT_MES(rct::is_rct_simple(rv.type), false, "decodeRct called on non simple rctSig");
CHECK_AND_ASSERT_THROW_MES(i < rv.ecdhInfo.size(), "Bad index");
CHECK_AND_ASSERT_THROW_MES(rv.outPk.size() == rv.ecdhInfo.size(), "Mismatched sizes of rv.outPk and rv.ecdhInfo");
//mask amount and mask
ecdhTuple ecdh_info = rv.ecdhInfo[i];
hwdev.ecdhDecode(ecdh_info, sk, rv.type == RCTType::Bulletproof2 || rv.type == RCTType::CLSAG);
mask = ecdh_info.mask;
key amount = ecdh_info.amount;
key C = rv.outPk[i].mask;
DP("C");
DP(C);
key Ctmp;
CHECK_AND_ASSERT_THROW_MES(sc_check(mask.bytes) == 0, "warning, bad ECDH mask");
CHECK_AND_ASSERT_THROW_MES(sc_check(amount.bytes) == 0, "warning, bad ECDH amount");
addKeys2(Ctmp, mask, amount, H);
DP("Ctmp");
DP(Ctmp);
if (equalKeys(C, Ctmp) == false) {
CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend");
}
return h2d(amount);
}
xmr_amount decodeRctSimple(const rctSig & rv, const key & sk, unsigned int i, hw::device &hwdev) {
key mask;
return decodeRctSimple(rv, sk, i, mask, hwdev);
}
bool signMultisigMLSAG(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) {
CHECK_AND_ASSERT_MES(tools::equals_any(rv.type, RCTType::Full, RCTType::Simple, RCTType::Bulletproof, RCTType::Bulletproof2),
false, "unsupported rct type");
CHECK_AND_ASSERT_MES(indices.size() == k.size(), false, "Mismatched k/indices sizes");
CHECK_AND_ASSERT_MES(k.size() == rv.p.MGs.size(), false, "Mismatched k/MGs size");
CHECK_AND_ASSERT_MES(k.size() == msout.c.size(), false, "Mismatched k/msout.c size");
CHECK_AND_ASSERT_MES(rv.p.CLSAGs.empty(), false, "CLSAGs not empty for MLSAGs");
if (rv.type == RCTType::Full)
{
CHECK_AND_ASSERT_MES(rv.p.MGs.size() == 1, false, "MGs not a single element");
}
for (size_t n = 0; n < indices.size(); ++n) {
CHECK_AND_ASSERT_MES(indices[n] < rv.p.MGs[n].ss.size(), false, "Index out of range");
CHECK_AND_ASSERT_MES(!rv.p.MGs[n].ss[indices[n]].empty(), false, "empty ss line");
}
// MLSAG: each player contributes a share to the secret-index ss: k - cc*secret_key_share
// cc: msout.c[n], secret_key_share: secret_key
for (size_t n = 0; n < indices.size(); ++n) {
rct::key diff;
sc_mulsub(diff.bytes, msout.c[n].bytes, secret_key.bytes, k[n].bytes);
sc_add(rv.p.MGs[n].ss[indices[n]][0].bytes, rv.p.MGs[n].ss[indices[n]][0].bytes, diff.bytes);
}
return true;
}
bool signMultisigCLSAG(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) {
CHECK_AND_ASSERT_MES(rv.type == RCTType::CLSAG, false, "unsupported rct type");
CHECK_AND_ASSERT_MES(indices.size() == k.size(), false, "Mismatched k/indices sizes");
CHECK_AND_ASSERT_MES(k.size() == rv.p.CLSAGs.size(), false, "Mismatched k/CLSAGs size");
CHECK_AND_ASSERT_MES(k.size() == msout.c.size(), false, "Mismatched k/msout.c size");
CHECK_AND_ASSERT_MES(rv.p.MGs.empty(), false, "MGs not empty for CLSAGs");
CHECK_AND_ASSERT_MES(msout.c.size() == msout.mu_p.size(), false, "Bad mu_p size");
for (size_t n = 0; n < indices.size(); ++n) {
CHECK_AND_ASSERT_MES(indices[n] < rv.p.CLSAGs[n].s.size(), false, "Index out of range");
}
// CLSAG: each player contributes a share to the secret-index ss: k - cc*mu_p*secret_key_share
// cc: msout.c[n], mu_p, msout.mu_p[n], secret_key_share: secret_key
for (size_t n = 0; n < indices.size(); ++n) {
rct::key diff, sk;
sc_mul(sk.bytes, msout.mu_p[n].bytes, secret_key.bytes);
sc_mulsub(diff.bytes, msout.c[n].bytes, sk.bytes, k[n].bytes);
sc_add(rv.p.CLSAGs[n].s[indices[n]].bytes, rv.p.CLSAGs[n].s[indices[n]].bytes, diff.bytes);
}
return true;
}
bool signMultisig(rctSig &rv, const std::vector<unsigned int> &indices, const keyV &k, const multisig_out &msout, const key &secret_key) {
if (rv.type == RCTType::CLSAG)
return signMultisigCLSAG(rv, indices, k, msout, secret_key);
else
return signMultisigMLSAG(rv, indices, k, msout, secret_key);
}
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLVertexBufferObjectCache.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOpenGLVertexBufferObjectCache.h"
#include "vtkDataArray.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLVertexBufferObject.h"
// ----------------------------------------------------------------------------
vtkStandardNewMacro(vtkOpenGLVertexBufferObjectCache);
// ----------------------------------------------------------------------------
vtkOpenGLVertexBufferObjectCache::vtkOpenGLVertexBufferObjectCache() = default;
// ----------------------------------------------------------------------------
vtkOpenGLVertexBufferObjectCache::~vtkOpenGLVertexBufferObjectCache() = default;
void vtkOpenGLVertexBufferObjectCache::RemoveVBO(vtkOpenGLVertexBufferObject* vbo)
{
vtkOpenGLVertexBufferObjectCache::VBOMap::iterator iter = this->MappedVBOs.begin();
while (iter != this->MappedVBOs.end())
{
if (iter->second == vbo)
{
iter->first->UnRegister(this);
this->MappedVBOs.erase(iter++);
}
else
{
++iter;
}
}
}
// ----------------------------------------------------------------------------
vtkOpenGLVertexBufferObject* vtkOpenGLVertexBufferObjectCache::GetVBO(
vtkDataArray* array, int destType)
{
// Check array is valid
if (array == nullptr || array->GetNumberOfTuples() == 0)
{
vtkErrorMacro(<< "Cannot get VBO for empty array.");
return nullptr;
}
// Look for VBO in map
VBOMap::const_iterator iter = this->MappedVBOs.find(array);
if (iter != this->MappedVBOs.end())
{
vtkOpenGLVertexBufferObject* vbo = iter->second;
vbo->SetDataType(destType);
vbo->Register(this);
return vbo;
}
// If vbo not found, create new one
// Initialize new vbo
vtkOpenGLVertexBufferObject* vbo = vtkOpenGLVertexBufferObject::New();
vbo->SetCache(this);
vbo->SetDataType(destType);
array->Register(this);
// Add vbo to map
this->MappedVBOs[array] = vbo;
return vbo;
}
// ----------------------------------------------------------------------------
void vtkOpenGLVertexBufferObjectCache::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
|
//
// Created by jbs on 21. 6. 3..
//
#include <zed2_client/Client.h>
using namespace zed_client;
using namespace std;
cv::Vec3b DetectedObject::getHsvColor() const {
cv::Mat bgr = cv::Mat(1, 1, CV_8UC3, bgrColor);
cv::Mat hsv;
cv::cvtColor(bgr,hsv,cv::COLOR_BGR2HSV);
return hsv.at<cv::Vec3b>(0, 0);
}
bool DetectedObject::isPointWithinBB(const Point &pnt_w, bool entireZ, float padding) const {
float xmax = zedRawData.dimensions_3d[0]/2.0f;
float ymax = zedRawData.dimensions_3d[1]/2.0f;
float zmax = zedRawData.dimensions_3d[2]/2.0f;
Point pnt_b = bbPose_w.poseMat.inverse() * pnt_w.toEigen();
float x = pnt_b.x;
float y = pnt_b.y;
float z = pnt_b.z;
if (not entireZ) {
if (x < (xmax + padding) and x > ( -xmax - padding) and y < (ymax + padding) and y > (-ymax-padding)
and z < (zmax+padding) and (z > -zmax -padding)) {
return true;
} else
return false;
}else{
if (x < (xmax + padding) and x > ( -xmax - padding) and z < (zmax + padding) and z > (-zmax-padding) ) {
return true;
} else
return false;
}
}
cv::Vec3b TrackedObject::getHsvColor() const {
cv::Mat bgr = cv::Mat(1, 1, CV_8UC3,filteredColorQueue.back());
cv::Mat hsv;
cv::cvtColor(bgr,hsv,cv::COLOR_BGR2HSV);
return hsv.at<cv::Vec3b>(0, 0);
}
TrackedObject::TrackedObject(DetectedObject obj, int targetIdx,
float heightOffSetForFilterPose, float smoothing,
int queueSize,int minPntForPoseInference) {
clientLastUpdateStamp = ros::Time::now();
beingTrackedAs = targetIdx;
bbPose_w = obj.bbPose_w;
bgrColor = obj.bgrColor;
zedRawData = obj.zedRawData;
p_heightOffset = heightOffSetForFilterPose;
p_smoothingWeight = smoothing;
p_queueSize = queueSize;
p_minPntForPoseInference = minPntForPoseInference;
Pose pose = bbPose_w;
pose.poseMat.translate(Eigen::Vector3f(0, -p_heightOffset, 0));
filteredPointQueue.push_back(pose.getTranslation());
filteredColorQueue.push_back(bgrColor);
}
void TrackedObject::update(const DetectedObject & newObj) {
float dt = (newObj.zedStamp - zedStamp).toSec();
zedStamp = newObj.zedStamp;
clientLastUpdateStamp = ros::Time::now();
zedRawData = newObj.zedRawData;
bbPose_w= newObj.bbPose_w;
bgrColor= newObj.bgrColor;
Pose pose = newObj.bbPose_w;
pose.poseMat.translate(Eigen::Vector3f(0, -p_heightOffset, 0));
Point updatePnt;
if( not filteredPointQueue.empty() ) {
updatePnt = (1 - p_smoothingWeight) * pose.getTranslation() + p_smoothingWeight * filteredPointQueue.back();
}
else
updatePnt = pose.getTranslation();
if (dt > 0) {
Point curVel = (updatePnt - filteredPointQueue.back()) * (1.0f / dt);
Point updateVel = (1 - p_smoothingWeight) * curVel + p_smoothingWeight * velocityFiltered_w;
velocityFiltered_w = updateVel;
velocityComputed = true;
}
filteredPointQueue.push_back(updatePnt);
if (filteredPointQueue.size() > p_queueSize)
filteredPointQueue.pop_front();
cv::Vec3f color = newObj.bgrColor;
cv::Vec3f updateColorf;
if (not filteredColorQueue.empty())
updateColorf = (1 - p_smoothingWeight) * color + p_smoothingWeight * cv::Vec3f(filteredColorQueue.back()) ;
else
updateColorf = color;
filteredColorQueue.push_back(cv::Vec3i(updateColorf));
if (filteredColorQueue.size() > p_queueSize)
filteredColorQueue.pop_front();
}
pcl::PointCloud<pcl::PointXYZRGB> TrackedObject::getObservationQueuePCL(string worldFrameId) {
int currentQueueSize = filteredPointQueue.size();
pcl::PointCloud<pcl::PointXYZRGB> points;
points.header.frame_id = worldFrameId;
points.header.stamp = pcl_conversions::toPCL(zedStamp);
for (int n = 0 ; n < currentQueueSize ; n++) {
pcl::PointXYZRGB pnt;
pnt.x = filteredPointQueue[n].x;
pnt.y = filteredPointQueue[n].y;
pnt.z = filteredPointQueue[n].z;
pnt.r = filteredColorQueue[n](2);
pnt.g = filteredColorQueue[n](1);
pnt.b = filteredColorQueue[n](0);
points.push_back(pnt);
}
return points;
}
bool TrackedObject::getFilteredPoseFromQueue(Pose &pose) const {
if (filteredPointQueue.size() < p_minPntForPoseInference) {
ROS_WARN("Too few points for x-direction inference < %d. "
"target filtered tf will not be broadcast",
p_minPntForPoseInference);
return false;
}
int nUseKF = int(filteredPointQueue.size()/ 3.0f) ;
int nUse = 0;
vector<Eigen::Quaternionf> quatStack;
for (auto it =filteredPointQueue.rbegin() ; nUse < nUseKF-1 ; it++ ){
Point p2 = *it;
Point p1 = *(it+1);
Pose dir(p1,p2);
quatStack.push_back(dir.getQuaternion());
nUse++;
}
Eigen::Quaternionf quatAvg = averageQuaternions(quatStack);
pose.setTranslation(filteredPointQueue.back());
pose.setRotation(quatAvg);
return true;
}
// todo prediction result
bool TrackedObject::isPointWithinBB(const Point &pnt_w, bool entireZ, float padding) const {
if (velocityComputed && (ros::Time::now()-clientLastUpdateStamp).toSec() > 0.1){
// do not care much about exact shape of 2d section shape
float boxWidth = (zedRawData.dimensions_3d[0] + zedRawData.dimensions_3d[2])/2.0 + 2*padding;
float boxHeight = (entireZ) ? numeric_limits<float>::max() : zedRawData.dimensions_3d[1] + 2*padding;
Point trackedCenter = getLinearPredictionPoint();
return
abs(pnt_w.x - trackedCenter.x) < boxWidth/2.0 and
abs(pnt_w.y - trackedCenter.y) < boxWidth/2.0 and
abs(pnt_w.z - trackedCenter.z) < boxHeight/2.0;
}else{
return DetectedObject::isPointWithinBB(pnt_w,entireZ,padding);
}
}
geometry_msgs::PointStamped TrackedObject::getLinearPredictionPoint(string worldFrame) {
geometry_msgs::PointStamped point;
if (velocityComputed) {
ros::Time requestTime = ros::Time::now();
point.header.frame_id = worldFrame;
Point prediction =
filteredPointQueue.back() + velocityFiltered_w * (requestTime - clientLastUpdateStamp).toSec();
point.point = prediction.toGeometry();
}
return point;
}
Point TrackedObject::getLinearPredictionPoint() const {
Point vel_w;
if (velocityComputed){
ros::Time requestTime = ros::Time::now();
vel_w = filteredPointQueue.back() + velocityFiltered_w * (requestTime - clientLastUpdateStamp).toSec();
}
return vel_w;
}
Client::Client() :nh("~"), it (nh) {
// parameter parsing
nh.param<string>("target_filter_frame_prefix", param.targetFramePrefix, "target_");
nh.param<string>("object_frame_prefix", param.objectFramePrefix, "object_");
nh.param<string>("world_frame_id",param.worldFrame,"map");
nh.param<bool>("mask_object",param.filterObject,true);
nh.param<bool>("additional_pcl",param.additionalPcl,true);
nh.param<bool>("additional_depth",param.additionalDepth,true);
nh.param("target_tracking/n_target",param.nTarget,2);
nh.param("target_tracking/height_offset_from_box_center",param.heightOffsetFromBbCenter,0.5f);
nh.param("target_tracking/callback_interval",param.targetIdInterval,0.08f);
nh.param("target_tracking/smoothing_weight",param.smoothingWeight,0.8f);
nh.param("target_tracking/queue",param.queueSize,50);
nh.param("target_tracking/min_pts_for_pose_inference",param.minimumPointsForPoseInference,10);
nh.param("target_detection/matching_weight/color",param.MW_color,1.0f);
nh.param("target_detection/matching_weight/location",param.MW_location,1.0f);
nh.param("target_detection/matching_weight/velocity",param.MW_velocity,1.0f);
nh.param("target_detection/assumption/dist_accept",param.M_distAcceptThreshold,0.7f);
nh.param("target_detection/assumption/color_accept",param.M_colorAcceptThreshold,100.0f);
nh.param("target_detection/assumption/color_reject",param.M_colorRejectThreshold,255.0f);
nh.param("target_detection/assumption/dist_reject",param.M_distRejectionThreshold,1.5f);
nh.param("pointcloud/mask_padding_x",param.maskThicknessX,10);
nh.param("pointcloud/mask_padding_y",param.maskThicknessY,20);
nh.param("pointcloud/bounding_box_padding",param.bbPadding,0.3f);
nh.param("pointcloud/publish_after_targets_fixed",param.publishPclAfterTargetLocked,true);
nh.param("pointcloud/stride",param.pclStride,5);
nh.param("pointcloud/filter_speckle",param.filterSpeckle,true);
nh.param("pointcloud/speckle_search_rad",param.speckleSearchRadius,0.5f);
nh.param("pointcloud/speckle_search_neighbors",param.speckleNeighbors,5);
subDepthComp = new message_filters::Subscriber<sensor_msgs::CompressedImage>(nh,"/zed2/zed_node/depth/depth_registered/compressedDepth",1);
subDepthCompAdd = new message_filters::Subscriber<sensor_msgs::CompressedImage>(nh,"/zed_add/zed_node/depth/depth_registered/compressedDepth",1);
subRgbComp = new message_filters::Subscriber<sensor_msgs::CompressedImage>(nh,"/zed2/zed_node/rgb/image_rect_color/compressed",1);
subZedOd = new message_filters::Subscriber<zed_interfaces::ObjectsStamped>(nh,"/zed2/zed_node/obj_det/objects",1);
subCamInfo = new message_filters::Subscriber<sensor_msgs::CameraInfo>(nh,"/zed2/zed_node/rgb/camera_info",1);
subCamInfoAdd = new message_filters::Subscriber<sensor_msgs::CameraInfo>(nh,"/zed_add/zed_node/rgb/camera_info",1);
subAdditionalPcl = new message_filters::Subscriber<sensor_msgs::PointCloud2>(nh,"/d435/depth/color/points",5);
if (param.filterObject) {
if (param.additionalPcl){
subSyncPcl = new message_filters::Synchronizer<CompressedImageMaskBbPclSync>(CompressedImageMaskBbPclSync(param.syncQueueSize),
*this->subRgbComp, *this->subDepthComp,
*this->subCamInfo, *this->subZedOd,
*this->subAdditionalPcl);
subSyncPcl->registerCallback(boost::bind(&Client::zedPclSyncCallback, this, _1, _2, _3, _4, _5));
}else if (param.additionalDepth){
subSyncDepth = new message_filters::Synchronizer<CompressedImageMaskBbAddSync>(CompressedImageMaskBbAddSync(param.syncQueueSize ),
*this->subRgbComp, *this->subDepthComp,
*this->subCamInfo, *this->subZedOd,
*this->subDepthCompAdd, *this->subCamInfoAdd);
subSyncDepth->registerCallback(boost::bind(&Client::zedSyncDepthCallback,this,_1,_2,_3,_4,_5,_6));
}else{
subSync = new message_filters::Synchronizer<CompressedImageMaskBbSync>(CompressedImageMaskBbSync(10),
*this->subRgbComp, *this->subDepthComp,
*this->subCamInfo, *this->subZedOd
);
subSync->registerCallback(boost::bind(&Client::zedSyncCallback, this, _1, _2, _3, _4));
}
}else{
subSyncSimple = new message_filters::Synchronizer<CompressedImageSync>(CompressedImageSync(10),
*this->subRgbComp, *this->subDepthComp,
*this->subCamInfo);
subSyncSimple->registerCallback(boost::bind(&Client::zedSyncCallback, this, _1, _2, _3));
}
pubRgbMaskImg = it.advertise("image_rect_color_masked",1);
pubDepthMaskImg = it.advertise("depth_masked",1);
pubPointsMasked = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("points_masked",1);
pubPointRemoved = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("points_removed",1);
pubCurTargetColors = nh.advertise<visualization_msgs::MarkerArray>("target_colors",1);
for(int n = 0 ; n < param.nTarget ; n++) {
pubObservationFiltered.push_back(
nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("observation_filtered/target_" + to_string(n), 1));
pubTargetLinearPrediction.push_back(
nh.advertise<geometry_msgs::PointStamped>("simple_prediction/target_" + to_string(n),1));
}
tfListenerPtr = new tf::TransformListener;
tfBroadcasterPtr = new tf::TransformBroadcaster;
nhGlobal.setCallbackQueue(&observationCallbackQueue);
timerCaller =nhGlobal.createTimer(ros::Duration(param.targetIdInterval),
&Client::targetIdCallback, this);
targetIdSpinnerPtr = new ros::AsyncSpinner(1, &observationCallbackQueue); // this spinner is dedicated to timer callback only. intended not to invoke updating mesh
targetIdSpinnerPtr->start();
}
float Client::matchingCost(const TrackedObject &priorObj, const DetectedObject &newObj) const {
float distDiff = (priorObj.bbPose_w.getTranslation() - newObj.bbPose_w.getTranslation()).norm();
float velDiff = sqrt(pow (priorObj.zedRawData.velocity[0] - newObj.zedRawData.velocity[0] , 2) +
pow (priorObj.zedRawData.velocity[1] - newObj.zedRawData.velocity[1] , 2) +
pow (priorObj.zedRawData.velocity[2] - newObj.zedRawData.velocity[2] , 2));
cv::Vec3b colorPrior = priorObj.getHsvColor();
cv::Vec3b colorNew = newObj.getHsvColor();
float colorDiff = sqrt(pow(colorPrior(0) - colorNew(0),2) +
pow(colorPrior(1) - colorNew(1),2)); // using H and S only
// accept assumption 1
if ( (priorObj.zedRawData.label_id == newObj.zedRawData.label_id) ) {
ROS_DEBUG("Accept: only one received obj and same label %d. accepting!", newObj.zedRawData.label_id);
return 0.0;
}
// accept assumption 2
if (colorDiff < param.M_colorAcceptThreshold and distDiff < param.M_distAcceptThreshold) {
ROS_DEBUG("Accept: comparing label %d and %d. Color diff = %f and dist diff = %f. accepting!",
priorObj.zedRawData.label_id, newObj.zedRawData.label_id,
colorDiff,distDiff);
return param.MW_velocity * velDiff;
}
// reject assumption 1
if (colorDiff > param.M_colorRejectThreshold) {
ROS_DEBUG("Reject: comparing label %d with prior hsv (%d,%d,%d) of %d th target. Color diff = %f too big.",
newObj.zedRawData.label_id,
colorPrior(0), colorPrior(1), colorPrior(2),
priorObj.beingTrackedAs, colorDiff);
return MATCHING_COST_INF;
}
// rejection assumption 2
if (distDiff > param.M_distRejectionThreshold){
ROS_DEBUG("Reject: target [%d] and tested obj [%d]= dist diff = %f too big.",
priorObj.beingTrackedAs, newObj.zedRawData.label_id,distDiff);
return MATCHING_COST_INF;
}
return param.MW_location * distDiff + param.MW_velocity * velDiff + param.MW_color * colorDiff;
}
void Client::zedSyncCallback(const sensor_msgs::CompressedImageConstPtr & rgbCompPtr, const sensor_msgs::CompressedImageConstPtr & depthCompPtr,
const sensor_msgs::CameraInfoConstPtr & camInfoPtr ) {
// time recording
ros::Time curSensorTime = depthCompPtr->header.stamp;
state.clientLastCallTime = ros::Time::now();
double fps = 1.0 / (curSensorTime - state.zedLastCallTime).toSec();
ROS_DEBUG("sync callback fps = %f " , fps);
state.zedLastCallTime = curSensorTime;
// find tf from map to cam
tf::StampedTransform transform;
try {
// time 0 in lookup was intended
tfListenerPtr->lookupTransform(param.worldFrame, depthCompPtr->header.frame_id,
curSensorTime, transform);
state.T_wc = Pose(transform);
state.T_cw = state.T_wc; state.T_cw.inverse();
}catch (tf::TransformException& ex) {
ROS_ERROR_STREAM(ex.what());
ROS_ERROR("[ZedClient] no transform between map and object header. Cannot process further.");
return;
}
// decompress and parse cam model
cv::Mat depthImg,rgbImg;
bool isCompressionSuccess = pngDecompressDepth(depthCompPtr, depthImg) and
jpegDecompressRgb(rgbCompPtr,rgbImg);
if (not isCompressionSuccess) {
ROS_ERROR("image decompression error");
return;
}
Timer pclTimer;
image_geometry::PinholeCameraModel model_;
model_.fromCameraInfo(*camInfoPtr);
double camera_cx = model_.cx();
double camera_cy = model_.cy();
double camera_fx = model_.fx();
double camera_fy = model_.fy();
double camera_factor = 1;
state.pclObjectsRemoved.clear();
state.pclObjectsRemoved.header.frame_id = depthCompPtr->header.frame_id;
state.pclObjectsRemoved.header.stamp = pcl_conversions::toPCL(curSensorTime);
state.pclFurtherRemoved.clear();
state.pclFurtherRemoved.header = state.pclObjectsRemoved.header;
for (int r = 0; r < depthImg.rows; r += param.pclStride) {
for (int c = 0; c < depthImg.cols; c += param.pclStride) {
float d = depthImg.ptr<float>(r)[c];
auto ptr_r = rgbImg.ptr<uchar>(r);
if (d != d) // nan
continue;
pcl::PointXYZRGB p;
p.z = double(d) / camera_factor;
p.x = (c - camera_cx) * p.z / camera_fx;
p.y = (r - camera_cy) * p.z / camera_fy;
p.r = ptr_r[3 * c + 2];
p.g = ptr_r[3 * c + 1];
p.b = ptr_r[3 * c + 0];
state.pclObjectsRemoved.points.push_back(p);
}
}
// speckle removal
if (param.filterSpeckle) {
int originalPoints = state.pclObjectsRemoved.points.size();
pcl::RadiusOutlierRemoval<pcl::PointXYZRGB> outrem;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>(state.pclObjectsRemoved));
outrem.setInputCloud(cloud);
outrem.setRadiusSearch(param.speckleSearchRadius);
outrem.setMinNeighborsInRadius(param.speckleNeighbors);
vector<int> survivalIndex;
outrem.filter(survivalIndex);
state.pclObjectsRemoved.points.clear();
int j = 0;
for (int i = 0; i < originalPoints; i++) {
if (i == survivalIndex[j]) {
state.pclObjectsRemoved.points.push_back(cloud->points[i]);
j++;
} else
state.pclFurtherRemoved.push_back(cloud->points[i]);
}
ROS_DEBUG("speckle removed: %d", originalPoints - state.pclObjectsRemoved.size());
}
state.pclObjectsRemoved.header.frame_id = depthCompPtr->header.frame_id;
state.pclObjectsRemoved.header.stamp = pcl_conversions::toPCL(curSensorTime);
double pclElapse = pclTimer.stop();
ROS_DEBUG("pcl generation took %f ms", pclElapse);
pubRgbMaskImg.publish(imageToROSmsg(rgbImg, enc::BGR8, rgbCompPtr->header.frame_id, curSensorTime));
pubDepthMaskImg.publish(imageToROSmsg(depthImg, enc::TYPE_32FC1, rgbCompPtr->header.frame_id, curSensorTime));
pubPointsMasked.publish(state.pclObjectsRemoved);
pubPointRemoved.publish(state.pclFurtherRemoved);
}
void Client::syncSubRoutine(const sensor_msgs::CompressedImageConstPtr & rgbCompPtr, const sensor_msgs::CompressedImageConstPtr & depthCompPtr,
const sensor_msgs::CameraInfoConstPtr & camInfoPtr, const zed_interfaces::ObjectsStampedConstPtr & objPtr ,
const sensor_msgs::PointCloud2ConstPtr & pclPtr) {
// time recording
ros::Time curSensorTime = depthCompPtr->header.stamp;
double fps = 1.0 / (curSensorTime - state.zedLastCallTime).toSec();
ROS_DEBUG("sync callback fps = %f " , fps);
state.zedLastCallTime = curSensorTime;
state.clientLastCallTime = ros::Time::now();
// find tf from map to cam
tf::StampedTransform transform;
// find tf from map to cam
try {
// time 0 in lookup was intended
tfListenerPtr->lookupTransform(param.worldFrame, depthCompPtr->header.frame_id,
curSensorTime, transform);
state.T_wc = Pose(transform);
state.T_cw = state.T_wc; state.T_cw.inverse();
}catch (tf::TransformException& ex) {
ROS_ERROR_STREAM(ex.what());
ROS_ERROR("[ZedClient] no transform between map and object header. Cannot process further.");
return;
}
if (pclPtr != nullptr) {
// find tf from map to zed cam to d435
try {
// time 0 in lookup was intended
tfListenerPtr->lookupTransform(depthCompPtr->header.frame_id,
pclPtr->header.frame_id,
curSensorTime, transform);
state.T_cd = Pose(transform);
} catch (tf::TransformException &ex) {
ROS_ERROR_STREAM(ex.what());
ROS_ERROR("[ZedClient] no transform between zed and d435. Cannot process further.");
return;
}
}
// find tf from map to object incoming frame
try {
// time 0 in lookup was intended
tfListenerPtr->lookupTransform(param.worldFrame, objPtr->header.frame_id,
curSensorTime, transform);
state.T_wo = Pose(transform);
}catch (tf::TransformException& ex) {
ROS_ERROR_STREAM(ex.what());
ROS_ERROR("[ZedClient] no transform between map and object header. Cannot process further.");
return;
}
// decompress and parse cam model
cv::Mat depthImg,rgbImg;
bool isDecompressionSuccess = pngDecompressDepth(depthCompPtr, depthImg) and
jpegDecompressRgb(rgbCompPtr,rgbImg);
if (not isDecompressionSuccess) {
ROS_ERROR("image decompression error");
return;
}
// masking and color id
int rGlobalMin = 0;
int cGlobalMin = 0;
int rGlobalMax = rgbImg.rows - 1;
int cGlobalMax = rgbImg.cols - 1;
const float NaN = std::numeric_limits<float>::quiet_NaN() ;
vector<DetectedObject> newObjects;
for (const auto &obj :objPtr->objects) {
ROS_DEBUG("number of detected obj: %d ", objPtr->objects.size());
Eigen::Vector3i objColor;
insertSkeletonPoint(obj,rgbImg,objColor);
int rMin = max(int(obj.bounding_box_2d.corners[0].kp[1]) - param.maskThicknessY, rGlobalMin);
int cMin = max(int(obj.bounding_box_2d.corners[0].kp[0]) - param.maskThicknessX, cGlobalMin);
int rMax = min(int(obj.bounding_box_2d.corners[2].kp[1]) + param.maskThicknessY, rGlobalMax);
int cMax = min(int(obj.bounding_box_2d.corners[2].kp[0]) + param.maskThicknessX, cGlobalMax);
float alpha = 0.5;
// masking for depth (set nan) and rgb (coloring with average color)
// NOTE: even the targets are lost for a short moment, we keep removing the bounding box from the last bounding box
for (int r = rMin; r < rMax; r++) {
auto ptr_r =rgbImg.ptr<uchar>(r);
auto ptr_depth =depthImg.ptr<float>(r);
for (int c = cMin; c < cMax; c++) {
ptr_r[3 * c + 0] = (int) (alpha * ptr_r[3 * c + 0] + (1 - alpha) * objColor.z());
ptr_r[3 * c + 1] = (int) (alpha * ptr_r[3 * c + 1] + (1 - alpha) * objColor.y());
ptr_r[3 * c + 2] = (int) (alpha * ptr_r[3 * c + 2] + (1 - alpha) * objColor.x());
ptr_depth[c] = NaN;
}
}
if (obj.tracking_state == 2) { // if state is SEARCHING, this is in occlusion or tracking lost
ROS_ERROR("object %d occluded or interrupted..", obj.label_id);
continue;
}
Pose T_ob; // pose from to box (box = optical frame, z-forwarding)
DetectedObject newObj;
newObj.zedStamp = depthCompPtr->header.stamp;
newObj.zedRawData = obj;
newObj.bgrColor = cv::Vec3i(objColor.z(), objColor.y(), objColor.x());
T_ob = extractBbPoseFromSensor(obj);
Point v_o = Point(newObj.zedRawData.velocity[0],
newObj.zedRawData.velocity[1],
newObj.zedRawData.velocity[2]);
Eigen::Matrix3f R_bo = T_ob.poseMat.rotation().matrix().inverse();
newObj.bbPose_w = T_ob;
newObj.bbPose_w.applyTransform(state.T_wo);
tfBroadcasterPtr->sendTransform(newObj.bbPose_w.toTf(param.worldFrame, param.objectFramePrefix + to_string(obj.label_id), curSensorTime));
newObjects.push_back(newObj);
}
// update object info
if(mutex_.try_lock()) {
state.receivedObjects = newObjects;
mutex_.unlock();
}else{
ROS_DEBUG("object cannot be updated due to lock from timer callback thread");
}
// create pcl
bool createPcl = false;
if(param.publishPclAfterTargetLocked ){
createPcl = state.isAllTargetsTracked;
if(not createPcl)
ROS_WARN("not making pcl from decompressed depth until targets are locked. (publishPclAfterTargetLocked = true was set)");
}else
createPcl = true;
if(createPcl) {
Timer pclTimer;
image_geometry::PinholeCameraModel model_;
model_.fromCameraInfo(*camInfoPtr);
double camera_cx = model_.cx();
double camera_cy = model_.cy();
double camera_fx = model_.fx();
double camera_fy = model_.fy();
double camera_factor = 1;
state.pclObjectsRemoved.clear();
state.pclObjectsRemoved.header.frame_id = depthCompPtr->header.frame_id;
state.pclObjectsRemoved.header.stamp = pcl_conversions::toPCL(curSensorTime);
state.pclFurtherRemoved.clear();
state.pclFurtherRemoved.header = state.pclObjectsRemoved.header;
for (int r = 0; r < depthImg.rows; r += param.pclStride) {
for (int c = 0; c < depthImg.cols; c += param.pclStride) {
float d = depthImg.ptr<float>(r)[c];
auto ptr_r = rgbImg.ptr<uchar>(r);
if (d != d) // nan
continue;
pcl::PointXYZRGB p;
p.z = double(d) / camera_factor;
p.x = (c - camera_cx) * p.z / camera_fx;
p.y = (r - camera_cy) * p.z / camera_fy;
p.r = ptr_r[3 * c + 2];
p.g = ptr_r[3 * c + 1];
p.b = ptr_r[3 * c + 0];
// double check for masking with 3d if targets are locked
if (state.isAllTargetsTracked){
bool isPointInTarget = false;
for (const auto & target : state.targetObjects){
Point p_w = state.T_wc.poseMat * Point(p.x,p.y,p.z).toEigen();
if (target.isPointWithinBB(p_w,true,param.bbPadding)) {
isPointInTarget = true;
break;
}
}
if (isPointInTarget) {
state.pclFurtherRemoved.push_back(p);
continue;
}
}
state.pclObjectsRemoved.points.push_back(p);
}
}
if (pclPtr != nullptr) {
// additional pointcloud (assume no objects filtering required for them)
pcl::PointCloud<pcl::PointXYZ> pclCloud;
pcl::fromROSMsg(*pclPtr, pclCloud);
for (int n = 0; n < pclCloud.size(); n += pow(param.pclStride, 2)) {
auto point = pclCloud.points[n];
Point p_c = state.T_cd.poseMat * Point(point.x, point.y, point.z).toEigen();
pcl::PointXYZRGB pclPnt;
pclPnt.x = p_c.x;
pclPnt.y = p_c.y;
pclPnt.z = p_c.z;
state.pclObjectsRemoved.points.push_back(pclPnt);
}
ROS_DEBUG("addition pcl added: %d", pclCloud.size());
}
// speckle removal
if (param.filterSpeckle) {
int originalPoints = state.pclObjectsRemoved.points.size();
pcl::RadiusOutlierRemoval<pcl::PointXYZRGB> outrem;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>(state.pclObjectsRemoved));
outrem.setInputCloud(cloud);
outrem.setRadiusSearch(param.speckleSearchRadius);
outrem.setMinNeighborsInRadius(param.speckleNeighbors);
vector<int> survivalIndex;
outrem.filter(survivalIndex);
state.pclObjectsRemoved.points.clear();
int j = 0;
for (int i = 0; i < originalPoints; i++) {
if (i == survivalIndex[j]) {
state.pclObjectsRemoved.points.push_back(cloud->points[i]);
j++;
} else
state.pclFurtherRemoved.push_back(cloud->points[i]);
}
ROS_DEBUG("speckle removed: %d", originalPoints - state.pclObjectsRemoved.size());
}
state.pclObjectsRemoved.header.frame_id = depthCompPtr->header.frame_id;
state.pclObjectsRemoved.header.stamp = pcl_conversions::toPCL(curSensorTime);
double pclElapse = pclTimer.stop();
ROS_DEBUG("pcl generation took %f ms", pclElapse);
}
// publish
pubRgbMaskImg.publish(imageToROSmsg(rgbImg, enc::BGR8, rgbCompPtr->header.frame_id, curSensorTime));
pubDepthMaskImg.publish(imageToROSmsg(depthImg, enc::TYPE_32FC1, rgbCompPtr->header.frame_id, curSensorTime));
pubPointsMasked.publish(state.pclObjectsRemoved);
pubPointRemoved.publish(state.pclFurtherRemoved);
}
void Client::zedPclSyncCallback(const sensor_msgs::CompressedImageConstPtr & compImgPtr,
const sensor_msgs::CompressedImageConstPtr & depthImgPtr,
const sensor_msgs::CameraInfoConstPtr & camPtr,
const zed_interfaces::ObjectsStampedConstPtr & objPtr,
const sensor_msgs::PointCloud2ConstPtr & pclPtr) {
syncSubRoutine(compImgPtr,depthImgPtr,camPtr,objPtr,pclPtr);
}
void Client::zedSyncDepthCallback(const sensor_msgs::CompressedImageConstPtr &rgbCompPtr,
const sensor_msgs::CompressedImageConstPtr &depthCompPtr,
const sensor_msgs::CameraInfoConstPtr &camInfoPtr,
const zed_interfaces::ObjectsStampedConstPtr &objPtr,
const sensor_msgs::CompressedImageConstPtr &depthCompAddPtr,
const sensor_msgs::CameraInfoConstPtr &camInfoAddPtr) {
// decompress additional depth and make pcl
cv::Mat depthImg;
bool isDecompressionSuccess = pngDecompressDepth(depthCompAddPtr, depthImg);
if (not isDecompressionSuccess) {
ROS_ERROR("image decompression error");
return;
}
Timer pclTimer;
image_geometry::PinholeCameraModel model_;
model_.fromCameraInfo(*camInfoAddPtr);
double camera_cx = model_.cx();
double camera_cy = model_.cy();
double camera_fx = model_.fx();
double camera_fy = model_.fy();
double camera_factor = 1;
sensor_msgs::PointCloud2 pclAdd;
pclAdd.header = depthCompAddPtr->header;
sensor_msgs::PointCloud2Modifier modifier(pclAdd);
modifier.resize(depthImg.cols * depthImg.rows);
modifier.setPointCloud2FieldsByString(1,"xyz");
sensor_msgs::PointCloud2Iterator<float> iter_x(pclAdd, "x");
sensor_msgs::PointCloud2Iterator<float> iter_y(pclAdd, "y");
sensor_msgs::PointCloud2Iterator<float> iter_z(pclAdd, "z");
int nPnt = 0;
for (int r = 0; r < depthImg.rows; r += param.pclStride)
for (int c = 0; c < depthImg.cols; c += param.pclStride) {
float d = depthImg.ptr<float>(r)[c];
if (d != d) // nan
continue;
float z = double (d) / camera_factor;
float x = (c - camera_cx) * z / camera_fx;
float y = (r - camera_cy) * z / camera_fy;
*(iter_x) = x;
*(iter_y) = y;
*(iter_z) = z;
iter_x+=1; iter_y+=1; iter_z+=1;
nPnt ++;
}
modifier.resize(nPnt);
sensor_msgs::PointCloud2ConstPtr pclPtr = boost::make_shared<const sensor_msgs::PointCloud2>(pclAdd);
ROS_DEBUG("additional pcl constructed with %f ms ",pclTimer.stop());
syncSubRoutine(rgbCompPtr, depthCompPtr, camInfoPtr,objPtr,pclPtr);
}
void Client::zedSyncCallback(const sensor_msgs::CompressedImageConstPtr & compImgPtr,
const sensor_msgs::CompressedImageConstPtr & depthImgPtr,
const sensor_msgs::CameraInfoConstPtr & camPtr,
const zed_interfaces::ObjectsStampedConstPtr & objPtr
) {
syncSubRoutine(compImgPtr,depthImgPtr,camPtr,objPtr, nullptr);
}
void Client::targetIdCallback(const ros::TimerEvent &event) {
mutex_.lock();
auto newObjects = state.receivedObjects;
mutex_.unlock();
// update tracked objects
if (not newObjects.empty()) {
// if no targets locked, find the closest ones;
if (not state.isAllTargetsTracked) {
if (newObjects.size() >= param.nTarget) {
std::vector<float> distToCam;
for (const auto &object: newObjects) {
float x = object.zedRawData.position[0];
float y = object.zedRawData.position[1];
float z = object.zedRawData.position[2];
float dist = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
distToCam.push_back(dist);
}
std::vector<size_t> idx(distToCam.size());
iota(idx.begin(), idx.end(), 0);
stable_sort(idx.begin(), idx.end(),
[& distToCam](size_t i1, size_t i2) { return distToCam[i1] < distToCam[i2]; });
for (int n = 0; n < param.nTarget; n++) {
DetectedObject newObj = newObjects[idx[n]];
TrackedObject trackedObj(newObj, n,
param.heightOffsetFromBbCenter,
param.smoothingWeight,
param.queueSize,param.minimumPointsForPoseInference );
state.targetObjects.push_back(trackedObj);
}
state.isAllTargetsTracked = true;
}
} else { // if targets were locked, match tracked Obj ~ detected obj
int nNewObjects = newObjects.size();
// priority of each tracked objects. But they are just wishlist in case of dual-target case.
std::vector<std::vector<int>> selectionPriority(param.nTarget);
std::vector<std::vector<float>> matchingCosts(param.nTarget);
for (int idxOld = 0; idxOld < param.nTarget; idxOld++) {
for (int idxNew = 0; idxNew < nNewObjects; idxNew++) {
matchingCosts[idxOld].push_back(matchingCost(state.targetObjects[idxOld],
newObjects[idxNew]));
selectionPriority[idxOld].push_back(idxNew); // before sorting
}
std::vector<float> matchingCostString = matchingCosts[idxOld];
std::sort(selectionPriority[idxOld].begin(), selectionPriority[idxOld].end(),
[& matchingCostString](size_t i1, size_t i2) {
return matchingCostString[i1] < matchingCostString[i2];
});
}
// Single target case, just pick the best one as the updated target (if certain conditions are met)
if (param.nTarget == 1) {
if (matchingCosts[0][selectionPriority[0][0]] < MATCHING_COST_INF)
state.targetObjects[0].update(newObjects[selectionPriority[0][0]]);
} else { // In dual target case, winner take priority if there is conviction
int bestPicks[2] = {selectionPriority[0][0], selectionPriority[1][0]};
float bestCost[2] = {matchingCosts[0][bestPicks[0]], matchingCosts[1][bestPicks[1]]};
// This case can occur either one of the two.
// 1) only one object was received. The target having larger matching will take that guy.
// 2) multiple objects were received, however, competing case for the two targets.
if (bestPicks[0] == bestPicks[1]) {
// 1) update only dominant object if it is make-sense matching
if (nNewObjects == 1) {
int winner = (bestCost[0] < bestCost[1]) ? 0 : 1;
if (bestCost[winner] < MATCHING_COST_INF)
state.targetObjects[winner].update(newObjects[bestPicks[winner]]);
// 2) in multiple object case, only give the winner the priority while other will take secondary priority
} else {
(bestCost[0] < bestCost[1]) ?
bestPicks[1] = selectionPriority[1][1] : bestPicks[0] = selectionPriority[0][1];
for (int m = 0; m < 2; m++) {
bestCost[m] = matchingCosts[m][bestPicks[m]];
if (bestCost[m] < MATCHING_COST_INF)
state.targetObjects[m].update(newObjects[bestPicks[m]]);
}
}
// In this case, there were at least more than two new objects
} else
for (int m = 0; m < 2; m++)
if (bestCost[m] < MATCHING_COST_INF)
state.targetObjects[m].update(newObjects[bestPicks[m]]);
}
}
}
// publish
if (state.isAllTargetsTracked) {
state.targetColors.markers.clear();
for (int n = 0; n < param.nTarget; n++) {
pubObservationFiltered[n].publish(
state.targetObjects[n].getObservationQueuePCL(param.worldFrame));
pubTargetLinearPrediction[n].publish(state.targetObjects[n].getLinearPredictionPoint(param.worldFrame));
Pose targetPose;
if (state.targetObjects[n].getFilteredPoseFromQueue(targetPose)) {
tfBroadcasterPtr->sendTransform(targetPose.toTf(param.worldFrame,
param.targetFramePrefix+ to_string(n) + "_filtered", state.targetObjects[n].clientLastUpdateStamp));
}
visualization_msgs::Marker marker;
marker.color.r = state.targetObjects[n].filteredColorQueue.back()[2];
marker.color.g = state.targetObjects[n].filteredColorQueue.back()[1];
marker.color.b = state.targetObjects[n].filteredColorQueue.back()[0];
state.targetColors.markers.push_back(marker);
}
pubCurTargetColors.publish(state.targetColors);
}
}
|
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "smt/ctx.h"
#include "smt/smt.h"
#include "util/config.h"
#include <cstdlib>
#include <iostream>
#include <string_view>
#include <z3.h>
using namespace std;
using util::config::dbg;
static void z3_error_handler(Z3_context ctx, Z3_error_code err) {
string_view str = Z3_get_error_msg(ctx, err);
// harmless timeout
if (str == "canceled")
return;
dbg() << "Severe Z3 error: " << str << " [code=" << err << "]\n";
_Exit(-1);
}
namespace smt {
context ctx;
void context::init() {
Z3_global_param_set("model.partial", "true");
Z3_global_param_set("smt.ematching", "false");
Z3_global_param_set("smt.mbqi.max_iterations", "1000000");
Z3_global_param_set("smt.random_seed", get_random_seed());
Z3_global_param_set("timeout", get_query_timeout());
Z3_global_param_set("memory_high_watermark", "2147483648"); // 2 GBs
// Disable Z3's use of UFs for NaNs when converting FPs to BVs
// They generate incorrect formulas when quantifiers are involved
Z3_global_param_set("rewriter.hi_fp_unspecified", "true");
ctx = Z3_mk_context_rc(nullptr);
Z3_set_error_handler(ctx, z3_error_handler);
no_timeout_param = Z3_mk_params(ctx);
Z3_params_inc_ref(ctx, no_timeout_param);
Z3_params_set_uint(ctx, no_timeout_param,
Z3_mk_string_symbol(ctx, "timeout"), 0);
}
void context::destroy() {
Z3_params_dec_ref(ctx, no_timeout_param);
Z3_close_log();
Z3_del_context(ctx);
}
}
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int n ;
cin>> n ;
int a[n] ;
int max = 0 ;
int t = 0 ;
for(int i=0 ; i<n ; i++){
cin>>a[i] ;
if(a[i]>max){
max = a[i] ;
}
}
for(int i=0 ; i<n ; i++){
if(max==a[i]){
t++ ;
}
}
cout<<t ;
}
|
///
#include "zipinternal.hpp"
#include <bela/endian.hpp>
namespace hazel::zip {
bool Reader::Decompress(const File &file, const Writer &w, bela::error_code &ec) const {
auto realPosition = file.position + baseOffset;
uint8_t buf[fileHeaderLen];
if (!fd.ReadAt(buf, realPosition, ec)) {
return false;
}
bela::endian::LittenEndian b(buf);
if (auto sig = b.Read<uint32_t>(); sig != fileHeaderSignature) {
ec = bela::make_error_code(L"zip: not a valid zip file");
return false;
}
b.Discard(22);
auto filenameLen = static_cast<int>(b.Read<uint16_t>());
auto extraLen = static_cast<int>(b.Read<uint16_t>());
auto position = realPosition + fileHeaderLen + filenameLen + extraLen;
if (!fd.Seek(position, ec)) {
return false;
}
switch (file.method) {
case ZIP_STORE: {
uint8_t buffer[4096];
auto cSize = file.compressedSize;
while (cSize != 0) {
auto minsize = (std::min)(cSize, static_cast<uint64_t>(sizeof(buffer)));
if (!fd.ReadFull({buffer, static_cast<size_t>(minsize)}, ec)) {
return false;
}
if (!w(buffer, static_cast<size_t>(minsize))) {
return false;
}
cSize -= minsize;
}
} break;
case ZIP_DEFLATE:
break;
case ZIP_DEFLATE64:
break;
case ZIP_ZSTD:
break;
case ZIP_LZMA2:
break;
case ZIP_PPMD:
break;
case ZIP_XZ:
break;
case ZIP_BZIP2:
break;
default:
ec = bela::make_error_code(ErrGeneral, L"support zip method ", file.method);
return false;
}
return true;
}
} // namespace hazel::zip
|
#include <stdio.h>
#include <stdlib.h>
#include "TestRunner.h"
#include "Clock.h"
#include <algorithm>
#include <cstring>
#include <stdexcept>
#include "TestData.h"
#include "JSONReport.h"
#include "myassert.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
LCG rng(Clock::TickU32());
std::vector<Test> &Tests()
{
static std::vector<Test> tests;
return tests;
}
static int numTestsPassed = 0;
static int numTestsFailed = 0;
static int numTestsWarnings = 0;
static int numTestsRun = 0;
volatile int globalPokedData = 0;
// If true, the currently running test should fail, and succeeding is an error.
// 0 - not expected to fail
// 1 - expected to fail, issue LOGI diagnostics.
// 2 - expected to fail, issue LOGW diagnostics.
int globalTestExpectedToFail = 0;
std::string globalTestFailureDescription = ""; // A custom optional message describing why this test is expected to fail.
void AddTest(std::string name, TestFunctionPtr function, std::string file, std::string description, bool runOnlyOnce)
{
Test t;
t.name = name;
t.description = description;
t.function = function;
t.isRandomized = false;
t.runOnlyOnce = runOnlyOnce;
t.isBenchmark = false;
t.file = file;
Tests().push_back(t);
}
void AddRandomizedTest(std::string name, TestFunctionPtr function, std::string file, std::string description)
{
Test t;
t.name = name;
t.description = description;
t.function = function;
t.isRandomized = true;
t.runOnlyOnce = false;
t.isBenchmark = false;
t.file = file;
Tests().push_back(t);
}
void AddBenchmark(std::string name, TestFunctionPtr function, std::string file, std::string description)
{
Test t;
t.name = name;
t.description = description;
t.function = function;
t.isRandomized = false;
t.runOnlyOnce = true;
t.isBenchmark = true;
t.file = file;
Tests().push_back(t);
}
std::string FormatTime(double ticks)
{
double msecs = ticks * 1000.0 / Clock::TicksPerSec();
double secs = msecs / 1000.0;
double usecs = msecs * 1000.0;
char str[256];
if (secs >= 1.0)
sprintf(str, "%.3f secs", (float)secs);
else if (msecs >= 1.0)
sprintf(str, "%.3f msecs", (float)msecs);
else if(usecs >= 1.0)
sprintf(str, "%.3f usecs", (float)usecs);
else
sprintf(str, "%.3f nsecs", (float)(usecs*1000.0));
return str;
}
// Print text to log without appending a newline to the end, if possible.
#if !defined(LOGI_NL)
#if defined(ANDROID) || defined(NPAPI) || defined(__native_client__)
#define LOGI_NL LOGI
#elif defined(WIN8RT)
void LOGI_NL(const char *format, ...)
{
const int capacity = 2048;
char str[capacity];
va_list args;
va_start(args, format);
vsnprintf((char *)str, capacity, format, args);
str[capacity-1] = 0; // We only support logging a fixed-length string so don't care if we fail/truncate, just make sure we zero-terminate so there won't be any issues.
OutputDebugStringA(str);
}
#else
#define LOGI_NL printf
#endif
#endif
/// Returns 0: passed, 1: passed with warnings, -1: failed.
int RunTest(Test &t, int numTimesToRun, int numTrialsPerRun, JSONReport &jsonReport)
{
if (t.runOnlyOnce)
numTimesToRun = numTrialsPerRun = 1;
if (!t.isRandomized)
numTimesToRun = 1;
if (t.isBenchmark)
{
numTimesToRun = numTrialsPerRun = 1;
LOGI_NL("Benchmark '%s': %s", t.name.c_str(), t.description.c_str());
}
else
LOGI_NL("Testing '%s': ", t.name.c_str());
std::vector<tick_t> times;
times.reserve(numTimesToRun);
t.numFails = 0;
t.numPasses = 0;
std::string failReason; // Stores the failure reason of the first failure.
std::vector<std::string> failReasons;
globalTestExpectedToFail = 0;
globalTestFailureDescription = std::string();
for(int j = 0; j < numTimesToRun; ++j)
{
tick_t start = Clock::Tick();
for(int k = 0; k < numTrialsPerRun; ++k)
// for(int k = 0; k < (t.isRandomized ? numTrials : 1); ++k)
{
#ifdef FAIL_USING_EXCEPTIONS
try
{
#endif
t.function(t);
if (globalTestExpectedToFail)
{
globalTestExpectedToFail = 0; // Signal that the following exception reports a failure of this test, and not an expected failure.
throw std::runtime_error(std::string("This test should have failed due to reason '") + globalTestFailureDescription + "', but it didn't fail!");
}
#ifdef FAIL_USING_EXCEPTIONS
}
catch(const TestSkippedException &e)
{
if (failReason.empty())
{
failReason = std::string("SKIPPED: ") + e.what();
LOGW("%s", failReason.c_str());
}
}
catch(const std::exception &e)
{
if (globalTestExpectedToFail)
{
if (globalTestExpectedToFail == 2)
LOGE("This test failed as expected. Caught an exception '%s', failure is due to reason '%s'.", e.what(), globalTestFailureDescription.c_str());
else
LOGI("This test failed as expected. Caught an exception '%s', failure is due to reason '%s'.", e.what(), globalTestFailureDescription.c_str());
}
else
{
if (failReason.empty())
failReason = e.what();
++t.numFails;
}
}
catch(...)
{
++t.numFails;
LOGE("Error: Received an unknown exception type that is _not_ derived from std::exception! This should not happen!");
}
#endif
}
tick_t end = Clock::Tick();
times.push_back(end - start);
}
t.numPasses = numTimesToRun*numTrialsPerRun - t.numFails;
std::sort(times.begin(), times.end());
// Erase outliers. (x% slowest)
const float rateSlowestToDiscard = 0.05f;
int numSlowestToDiscard = (int)(times.size() * rateSlowestToDiscard);
times.erase(times.end() - numSlowestToDiscard, times.end());
tick_t total = 0;
for(size_t j = 0; j < times.size(); ++j)
total += times[j];
if (!t.isBenchmark)
{
if (!times.empty())
{
t.fastestTime = (double)times[0] / numTrialsPerRun;
t.averageTime = (double)total / times.size() / numTrialsPerRun;
t.worstTime = (double)times.back() / numTrialsPerRun;
t.numTimesRun = numTimesToRun;
t.numTrialsPerRun = numTrialsPerRun;
}
else
{
t.fastestTime = t.averageTime = t.worstTime = -1.0;
t.numTimesRun = t.numTrialsPerRun = 0;
}
}
float successRate = (t.numPasses + t.numFails > 0) ? (float)t.numPasses * 100.f / (t.numPasses + t.numFails) : 0.f;
jsonReport.Report(t);
if (t.isBenchmark && t.numFails == 0) // Benchmarks print themselves.
return 0; // 0: Success
int ret = 0; // 0: Success
if (t.numFails == 0)
{
if (t.isRandomized)
LOGI(" ok (%d passes, 100%%)", t.numPasses);
else
LOGI(" ok ");
// ++numTestsPassed;
t.result = TestPassed;
}
else if (successRate >= 95.0f)
{
LOGI_NL(" ok ");
LOGW("Some failures with '%s' (%d passes, %.2f%% of all tries)", failReason.c_str(), t.numPasses, successRate);
// ++numTestsPassed;
// ++numWarnings;
ret = 1; // Success with warnings
t.result = TestPassedWithWarnings;
}
else
{
if (t.isRandomized)
LOGE("FAILED: '%s' (%d passes, %.2f%% of all tries)", failReason.c_str(), t.numPasses, successRate);
else
LOGE("FAILED: '%s'", failReason.c_str());
ret = -1; // Failed
t.result = TestFailed;
}
if (!times.empty())
{
if (t.runOnlyOnce)
LOGI(" Elapsed: %s", FormatTime((double)times[0]).c_str());
else
LOGI(" Fastest: %s, Average: %s, Slowest: %s", FormatTime(t.fastestTime).c_str(), FormatTime(t.averageTime).c_str(), FormatTime(t.worstTime).c_str());
}
return ret;
}
static int nextTestToRun = 0;
bool StringBeginsWithOneOf(const char *str, const char * const *prefixes)
{
for(const char * const *prefix = prefixes; *prefix; ++prefix)
if (!strncmp(str, *prefix, strlen(*prefix)))
return true;
return false;
}
bool StringContainsOneOf(const char *str, const char * const *prefixes)
{
for(const char * const *prefix = prefixes; *prefix; ++prefix)
if (strstr(str, *prefix) != 0)
return true;
return false;
}
int RunOneTest(int numTimes, int numTrials, const char * const *prefixes, JSONReport &jsonReport)
{
std::vector<Test> &tests = Tests();
while(nextTestToRun < (int)tests.size())
{
if (StringBeginsWithOneOf(tests[nextTestToRun].name.c_str(), prefixes) || StringContainsOneOf(tests[nextTestToRun].description.c_str(), prefixes)
|| StringContainsOneOf(tests[nextTestToRun].file.c_str(), prefixes))
{
int ret = RunTest(tests[nextTestToRun], numTimes, numTrials, jsonReport);
if (ret == 0 || ret == 1)
++numTestsPassed;
if (ret == 1)
++numTestsWarnings;
if (ret == -1)
++numTestsFailed;
++nextTestToRun;
++numTestsRun;
return ret;
}
++nextTestToRun;
}
return -2; // No tests left to run
}
void PrintTestRunSummary()
{
LOGI("Done. %d tests run. %d passed, of which %d succeeded with warnings. %d failed.", numTestsRun, numTestsPassed, numTestsWarnings, numTestsFailed);
if (numTestsFailed > 0)
{
LOGE_NS("The following tests failed:");
std::vector<Test> &tests = Tests();
for (size_t i = 0; i < tests.size(); ++i)
{
if (tests[i].result == TestFailed)
LOGE_NS(" %s", tests[i].name.c_str());
}
}
if (numTestsWarnings > 0)
{
LOGW_NS("The following tests had some failures:");
std::vector<Test> &tests = Tests();
int totalFailureCount = 0;
int totalPassCount = 0;
for (size_t i = 0; i < tests.size(); ++i)
{
Test &t = tests[i];
if (t.numFails > 0 && tests[i].result != TestFailed)
{
float successRate = (t.numPasses + t.numFails > 0) ? (float)t.numPasses * 100.f / (t.numPasses + t.numFails) : 0.f;
LOGW_NS(" %s: %d failures, %d passes (%.2f%% success rate).", tests[i].name.c_str(), tests[i].numFails, tests[i].numPasses, successRate);
totalFailureCount += t.numFails;
}
totalPassCount += t.numPasses;
}
LOGW_NS("Total failure count: %d/%d (%f%% of all iterations)", totalFailureCount, totalFailureCount + totalPassCount, totalFailureCount * 100.0 / (totalFailureCount+totalPassCount));
}
}
int argc_;
char **argv_;
void TestsFinished()
{
PrintTestRunSummary();
LOGI("%d", globalPokedData);
// When --exit0 is passed, we forcibly return 0 and not the number of failed tests.
// Used by buildbot in valgrind runs to ignore any failures - the failures are detected
// in a "real" run instead that carry more randomized trial runs.
for(int i = 1; i < argc_; ++i)
if (!strcmp(argv_[i], "--exit0"))
exit(0);
}
int numTotalRuns = 0;
int numTrialsPerTimedBlock = 0;
// A list of test prefixes to include in the run.
std::vector<const char *> prefixes;
JSONReport jsonReport;
void RunNextTest()
{
RunOneTest(numTotalRuns, numTrialsPerTimedBlock, &prefixes[0], jsonReport);
#ifdef __EMSCRIPTEN__
if (nextTestToRun >= (int)Tests().size())
{
emscripten_cancel_main_loop();
TestsFinished();
exit(numTestsFailed);
}
#endif
}
#ifdef MATH_TESTS_EXECUTABLE
int main(int argc, char **argv)
{
argc_ = argc;
argv_ = argv;
try
{
TestData::InitTestData();
} catch(const std::exception &e)
{
LOGE("std::exception was thrown during initialization of test runner data! Unable to launch tests!\n%s", e.what());
return 99999;
} catch(...)
{
LOGE("Unknown exception was thrown during initialization of test runner data! Unable to launch tests!");
return 99999;
}
numTotalRuns = (argc >= 2) ? atoi(argv[1]) : 100;
numTrialsPerTimedBlock = (argc >= 3) ? atoi(argv[2]) : 100;
#ifdef __EMSCRIPTEN__
numTotalRuns = numTrialsPerTimedBlock = 10;
#endif
for(int i = 3; i < argc; ++i)
{
if (argv[i][0] != '-' && argv[i][0] != '/')
prefixes.push_back(argv[i]);
}
if (prefixes.empty())
prefixes.push_back(""); // Empty prefix runs all tests.
prefixes.push_back(0); // Sentinel to terminate prefix string list.
if (numTotalRuns == 0 || numTrialsPerTimedBlock == 0)
{
LOGI("Usage: %s <numTotalRuns> <numTrialsPerTimedBlock>", argv[0]);
LOGI(" Runs all tests.");
LOGI(" %s <numTotalRuns> <numTrialsPerTimedBlock> prefix1 prefix2 prefix3...", argv[0]);
LOGI(" Runs all tests starting with one of the given prefixes, or residing in one of the named code files.");
return 0;
}
{
std::string jsonFilename = "test_results.json";
for(int i = 1; i+1 < argc; ++i)
if (!strcmp(argv[i], "--json"))
jsonFilename = argv[i+1]; // Allow overriding the output file name from command line.
jsonReport.Create(jsonFilename.c_str());
}
numTestsRun = numTestsPassed = numTestsWarnings = numTestsFailed = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(&RunNextTest, 0, 0);
#else
while(nextTestToRun < (int)Tests().size())
RunNextTest();
TestsFinished();
return numTestsFailed; // exit code of 0 denotes a successful run.
#endif
}
#endif
|
// $Id: event_server.cpp 91673 2010-09-08 18:49:47Z johnnyw $
// Main driver program for the event server example.
#include "ace/OS_main.h"
#include "ace/Service_Config.h"
#include "ace/OS_NS_unistd.h"
#include "Options.h"
#include "Consumer_Router.h"
#include "Event_Analyzer.h"
#include "Supplier_Router.h"
#include "ace/Sig_Adapter.h"
#include "ace/Stream.h"
// Typedef these components to handle multi-threading correctly.
typedef ACE_Stream<ACE_SYNCH> MT_Stream;
typedef ACE_Module<ACE_SYNCH> MT_Module;
class Event_Server : public ACE_Sig_Adapter
{
// = TITLE
// Run the logic for the <Event_Server>.
//
// = DESCRIPTION
// In addition to packaging the <Event_Server> components, this
// class also handles SIGINT and terminate the entire
// application process. There are several ways to terminate
// this application process:
//
// 1. Send a SIGINT signal (e.g., via ^C)
// 2. Type any character on the STDIN.
//
// Note that by inheriting from the <ACE_Sig_Adapter> we can
// shutdown the <ACE_Reactor> cleanly when a SIGINT is
// generated.
public:
Event_Server (void);
// Constructor.
int svc (void);
// Run the event-loop for the event server.
private:
virtual int handle_input (ACE_HANDLE handle);
// Hook method called back when a user types something into the
// STDIN in order to shut down the program.
int configure_stream (void);
// Setup the plumbing in the stream.
int set_watermarks (void);
// Set the high and low queue watermarks.
int run_event_loop (void);
// Run the event-loop for the <Event_Server>.
MT_Stream event_server_;
// The <ACE_Stream> that contains the <Event_Server> application
// <Modules>.
};
Event_Server::Event_Server (void)
: ACE_Sig_Adapter (ACE_Sig_Handler_Ex (ACE_Reactor::end_event_loop))
// Shutdown the <ACE_Reactor>'s event loop when a SIGINT is
// received.
{
// Register to trap STDIN from the user.
if (ACE_Event_Handler::register_stdin_handler (this,
ACE_Reactor::instance (),
ACE_Thread_Manager::instance ()) == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("register_stdin_handler")));
// Register to trap the SIGINT signal.
else if (ACE_Reactor::instance ()->register_handler
(SIGINT, this) == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("register_handler")));
}
int
Event_Server::handle_input (ACE_HANDLE)
{
// This code here will make sure we actually wait for the user to
// type something. On platforms like Win32, <handle_input> is called
// prematurely (even when there is no data).
char temp_buffer [BUFSIZ];
ssize_t n = ACE_OS::read (ACE_STDIN,
temp_buffer,
sizeof (temp_buffer));
// This ought to be > 0, otherwise something very strange has
// happened!!
ACE_ASSERT (n > 0);
ACE_UNUSED_ARG (n); // To avoid compile warning with ACE_NDEBUG.
Options::instance ()->stop_timer ();
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%t) closing down the test\n")));
Options::instance ()->print_results ();
ACE_Reactor::instance ()->end_reactor_event_loop ();
return -1;
}
int
Event_Server::configure_stream (void)
{
Peer_Router_Context *src;
// Create the <Supplier_Router>'s routing context. This contains a
// context shared by both the write-side and read-side of the
// <Supplier_Router> Module.
ACE_NEW_RETURN (src,
Peer_Router_Context (Options::instance ()->supplier_port ()),
-1);
MT_Module *srm = 0;
// Create the <Supplier_Router> module.
ACE_NEW_RETURN (srm,
MT_Module
(ACE_TEXT ("Supplier_Router"),
new Supplier_Router (src),
new Supplier_Router (src)),
-1);
MT_Module *eam = 0;
// Create the <Event_Analyzer> module.
ACE_NEW_RETURN (eam,
MT_Module
(ACE_TEXT ("Event_Analyzer"),
new Event_Analyzer,
new Event_Analyzer),
-1);
Peer_Router_Context *crc;
// Create the <Consumer_Router>'s routing context. This contains a
// context shared by both the write-side and read-side of the
// <Consumer_Router> Module.
ACE_NEW_RETURN (crc,
Peer_Router_Context (Options::instance ()->consumer_port ()),
-1);
MT_Module *crm = 0;
// Create the <Consumer_Router> module.
ACE_NEW_RETURN (crm,
MT_Module
(ACE_TEXT ("Consumer_Router"),
new Consumer_Router (crc),
new Consumer_Router (crc)),
-1);
// Push the Modules onto the event_server stream.
if (this->event_server_.push (srm) == -1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("push (Supplier_Router)")),
-1);
else if (this->event_server_.push (eam) == -1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("push (Event_Analyzer)")),
-1);
else if (this->event_server_.push (crm) == -1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("push (Consumer_Router)")),
-1);
return 0;
}
int
Event_Server::set_watermarks (void)
{
// Set the high and low water marks appropriately. The water marks
// control how much data can be buffered before the queues are
// considered "full."
size_t wm = Options::instance ()->low_water_mark ();
if (this->event_server_.control (ACE_IO_Cntl_Msg::SET_LWM,
&wm) == -1)
ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
ACE_TEXT ("push (setting low watermark)")),
-1);
wm = Options::instance ()->high_water_mark ();
if (this->event_server_.control (ACE_IO_Cntl_Msg::SET_HWM,
&wm) == -1)
ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
ACE_TEXT ("push (setting high watermark)")),
-1);
return 0;
}
int
Event_Server::run_event_loop (void)
{
// Begin the timer.
Options::instance ()->start_timer ();
// Perform the main event loop waiting for the user to type ^C or to
// enter a line on the ACE_STDIN.
ACE_Reactor::instance ()->run_reactor_event_loop ();
// Close down the stream and call the <close> hooks on all the
// <ACE_Task>s in the various Modules in the Stream.
this->event_server_.close ();
// Wait for the threads in the <Consumer_Router> and
// <Supplier_Router> to exit.
return ACE_Thread_Manager::instance ()->wait ();
}
int
Event_Server::svc (void)
{
if (this->configure_stream () == -1)
return -1;
else if (this->set_watermarks () == -1)
return -1;
else if (this->run_event_loop () == -1)
return -1;
else
return 0;
}
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
#if defined (ACE_HAS_THREADS)
Options::instance ()->parse_args (argc, argv);
// Initialize the <Event_Server>.
Event_Server event_server;
// Run the event server's event-loop.
int result = event_server.svc ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("exiting main\n")));
return result;
#else
ACE_UNUSED_ARG (argc);
ACE_UNUSED_ARG (argv);
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("threads not supported on this platform\n")),
1);
#endif /* ACE_HAS_THREADS */
}
|
/*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DOM_ProcessingInstruction.cpp 176026 2004-09-08 13:57:07Z peiyongz $
*/
#include "DOM_ProcessingInstruction.hpp"
#include "ProcessingInstructionImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
DOM_ProcessingInstruction::DOM_ProcessingInstruction()
: DOM_Node(null)
{
};
DOM_ProcessingInstruction::DOM_ProcessingInstruction(
const DOM_ProcessingInstruction & other)
: DOM_Node(other)
{
};
DOM_ProcessingInstruction::DOM_ProcessingInstruction(
ProcessingInstructionImpl *impl)
: DOM_Node(impl)
{
};
DOM_ProcessingInstruction::~DOM_ProcessingInstruction()
{
};
DOM_ProcessingInstruction & DOM_ProcessingInstruction::operator = (
const DOM_ProcessingInstruction & other)
{
return (DOM_ProcessingInstruction &) DOM_Node::operator = (other);
};
DOM_ProcessingInstruction & DOM_ProcessingInstruction::operator = (const DOM_NullPtr *other)
{
return (DOM_ProcessingInstruction &) DOM_Node::operator = (other);
};
DOMString DOM_ProcessingInstruction::getTarget() const
{
return ((ProcessingInstructionImpl *)fImpl)->getTarget().clone();
};
DOMString DOM_ProcessingInstruction::getData() const
{
return ((ProcessingInstructionImpl *)fImpl)->getData().clone();
};
void DOM_ProcessingInstruction::setData(const DOMString &data)
{
((ProcessingInstructionImpl *)fImpl)->setData(data.clone());
};
XERCES_CPP_NAMESPACE_END
|
//
// Copyright (c) 2015-2021 CNRS INRIA
//
#ifndef __pinocchio_compute_all_terms_hxx__
#define __pinocchio_compute_all_terms_hxx__
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/spatial/act-on-set.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"
#include "pinocchio/algorithm/energy.hpp"
#include "pinocchio/algorithm/check.hpp"
namespace pinocchio
{
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename ConfigVectorType, typename TangentVectorType>
struct CATForwardStep
: public fusion::JointUnaryVisitorBase< CATForwardStep<Scalar,Options,JointCollectionTpl,ConfigVectorType,TangentVectorType> >
{
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;
typedef boost::fusion::vector<const Model &,
Data &,
const ConfigVectorType &,
const TangentVectorType &
> ArgsType;
template<typename JointModel>
static void algo(const JointModelBase<JointModel> & jmodel,
JointDataBase<typename JointModel::JointDataDerived> & jdata,
const Model & model,
Data & data,
const Eigen::MatrixBase<ConfigVectorType> & q,
const Eigen::MatrixBase<TangentVectorType> & v)
{
typedef typename Model::JointIndex JointIndex;
typedef typename SizeDepType<JointModel::NV>::template ColsReturn<typename Data::Matrix6x>::Type ColsBlock;
const JointIndex i = jmodel.id();
const JointIndex parent = model.parents[i];
jmodel.calc(jdata.derived(),q.derived(),v.derived());
// CRBA
data.liMi[i] = model.jointPlacements[i]*jdata.M();
// Jacobian + NLE
data.v[i] = jdata.v();
if(parent>0)
{
data.oMi[i] = data.oMi[parent]*data.liMi[i];
data.v[i] += data.liMi[i].actInv(data.v[parent]);
}
else
data.oMi[i] = data.liMi[i];
data.ov[i] = data.oMi[i].act(data.v[i]);
data.oYcrb[i] = data.oMi[i].act(model.inertias[i]);
data.doYcrb[i] = data.oYcrb[i].variation(data.ov[i]);
ColsBlock J_cols = jmodel.jointCols(data.J);
J_cols = data.oMi[i].act(jdata.S());
ColsBlock dJ_cols = jmodel.jointCols(data.dJ);
motionSet::motionAction(data.ov[i],J_cols,dJ_cols);
data.a_gf[i] = data.a[i] = jdata.c() + (data.v[i] ^ jdata.v());
if (parent > 0)
data.a[i] += data.liMi[i].actInv(data.a[parent]);
data.a_gf[i] += data.liMi[i].actInv(data.a_gf[parent]);
data.h[i] = model.inertias[i]*data.v[i];
data.f[i] = model.inertias[i]*data.a_gf[i] + data.v[i].cross(data.h[i]); // -f_ext
}
};
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
struct CATBackwardStep
: public fusion::JointUnaryVisitorBase <CATBackwardStep<Scalar,Options,JointCollectionTpl> >
{
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;
typedef boost::fusion::vector<const Model &,
Data &
> ArgsType;
template<typename JointModel>
static void algo(const JointModelBase<JointModel> & jmodel,
JointDataBase<typename JointModel::JointDataDerived> & jdata,
const Model & model,
Data & data)
{
typedef typename Model::JointIndex JointIndex;
typedef typename SizeDepType<JointModel::NV>::template ColsReturn<typename Data::Matrix6x>::Type ColsBlock;
const JointIndex i = jmodel.id();
const JointIndex parent = model.parents[i];
ColsBlock J_cols = data.J.template middleCols<JointModel::NV>(jmodel.idx_v());
ColsBlock dJ_cols = data.dJ.template middleCols<JointModel::NV>(jmodel.idx_v());
ColsBlock Ag_cols = data.Ag.template middleCols<JointModel::NV>(jmodel.idx_v());
ColsBlock dAg_cols = data.dAg.template middleCols<JointModel::NV>(jmodel.idx_v());
// Calc Ag = Y * S
motionSet::inertiaAction(data.oYcrb[i],J_cols,Ag_cols);
// Calc dAg = Ivx + vxI
dAg_cols.noalias() = data.doYcrb[i] * J_cols;
motionSet::inertiaAction<ADDTO>(data.oYcrb[i],dJ_cols,dAg_cols);
/* M[i,SUBTREE] = S'*F[1:6,SUBTREE] */
data.M.block(jmodel.idx_v(),jmodel.idx_v(),jmodel.nv(),data.nvSubtree[i])
= J_cols.transpose()*data.Ag.middleCols(jmodel.idx_v(),data.nvSubtree[i]);
jmodel.jointVelocitySelector(data.nle) = jdata.S().transpose()*data.f[i];
data.oYcrb[parent] += data.oYcrb[i];
data.doYcrb[parent] += data.doYcrb[i];
data.h[parent] += data.liMi[i].act(data.h[i]);
data.f[parent] += data.liMi[i].act(data.f[i]);
// CoM
data.mass[i] = data.oYcrb[i].mass();
data.com[i] = data.oMi[i].actInv(data.oYcrb[i].lever());
data.vcom[i] = data.h[i].linear() / data.mass[i];
}
};
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename ConfigVectorType, typename TangentVectorType>
inline void computeAllTerms(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
DataTpl<Scalar,Options,JointCollectionTpl> & data,
const Eigen::MatrixBase<ConfigVectorType> & q,
const Eigen::MatrixBase<TangentVectorType> & v)
{
assert(model.check(data) && "data is not consistent with model.");
PINOCCHIO_CHECK_ARGUMENT_SIZE(q.size(), model.nq, "The configuration vector is not of right size");
PINOCCHIO_CHECK_ARGUMENT_SIZE(v.size(), model.nv, "The velocity vector is not of right size");
typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;
data.v[0].setZero();
data.a[0].setZero();
data.h[0].setZero();
data.a_gf[0] = -model.gravity;
data.oYcrb[0].setZero();
typedef CATForwardStep<Scalar,Options,JointCollectionTpl,ConfigVectorType,TangentVectorType> Pass1;
for(JointIndex i=1;i<(JointIndex) model.njoints;++i)
{
Pass1::run(model.joints[i],data.joints[i],
typename Pass1::ArgsType(model,data,q.derived(),v.derived()));
}
typedef CATBackwardStep<Scalar,Options,JointCollectionTpl> Pass2;
for(JointIndex i=(JointIndex)(model.njoints-1);i>0;--i)
{
Pass2::run(model.joints[i],data.joints[i],
typename Pass2::ArgsType(model,data));
}
// CoM
data.mass[0] = data.oYcrb[0].mass();
data.com[0] = data.oYcrb[0].lever();
data.vcom[0] = data.h[0].linear() / data.mass[0];
// Centroidal
typedef Eigen::Block<typename Data::Matrix6x,3,-1> Block3x;
const Block3x Ag_lin = data.Ag.template middleRows<3>(Force::LINEAR);
Block3x Ag_ang = data.Ag.template middleRows<3>(Force::ANGULAR);
for(long i = 0; i<model.nv; ++i)
Ag_ang.col(i) += Ag_lin.col(i).cross(data.com[0]);
const Block3x dAg_lin = data.dAg.template middleRows<3>(Force::LINEAR);
Block3x dAg_ang = data.dAg.template middleRows<3>(Force::ANGULAR);
for(Eigen::DenseIndex i = 0; i<model.nv; ++i)
dAg_ang.col(i) += dAg_lin.col(i).cross(data.com[0]);
data.hg = data.h[0];
data.hg.angular() += data.hg.linear().cross(data.com[0]);
data.dhg = data.f[0];
data.dhg.angular() += data.dhg.linear().cross(data.com[0]);
// JCoM
data.Jcom = data.Ag.template middleRows<3>(Force::LINEAR)/data.mass[0];
data.Ig.mass() = data.oYcrb[0].mass();
data.Ig.lever().setZero();
data.Ig.inertia() = data.oYcrb[0].inertia();
// Gravity
data.g.noalias() = -data.Ag.template middleRows<3>(Force::LINEAR).transpose() * model.gravity.linear();
// Energy
computeKineticEnergy(model, data);
computePotentialEnergy(model, data);
}
} // namespace pinocchio
/// \endinternal
#endif // ifndef __pinocchio_compute_all_terms_hxx__
|
#include "cl_data.h"
#include "cl_helper.h"
#include "cl_exception.h"
CL::data::data():data_(nullptr),size_(0){
}
CL::data::data(const cl_mem &data,size_t size):data_(data),size_(size){
CL_ERROR(clRetainMemObject(data_));
}
CL::data::data(const CL::data &data):data_(data.handle()),size_(data.size_){
CL_ERROR(clRetainMemObject(data_));
}
CL::data::data(const CL::context &context,
cl_mem_flags flags,
size_t size):data_(nullptr),size_(size){
cl_int error;
data_ = clCreateBuffer(context.handle(),
flags,
size_,
nullptr,
&error);
try{
CL_ERROR(error);
}
catch (CL::exception &e){
if (e.error_code() == CL_INVALID_BUFFER_SIZE){
std::stringstream ss;
ss << size_;
e.addAdditionalInfo(ss.str(), "BufferSize: ");
}
throw e;
}
}
CL::data::~data(){
//std::cout << "referenceCount()" << referenceCount() << std::endl;
if (data_ != nullptr) CL_ERROR(clReleaseMemObject(data_));
}
void CL::data::operator=(const CL::data &k){
if (data_) CL_ERROR(clReleaseMemObject(data_));
data_ = k.data_;
size_ = k.size_;
if (data_) CL_ERROR(clRetainMemObject(data_));
}
size_t CL::data::size() const{
return size_;
}
cl_mem CL::data::handle() const{
return data_;
}
cl_mem& CL::data::handle(){
return data_;
}
//
template<class T>
T CL::data::info(cl_mem_info info) const{
T t;
CL_ERROR(clGetMemObjectInfo(data_,
info,
sizeof(T),
&t, NULL));
return t;
}
size_t CL::data::mem_size() const{
return info<size_t>(CL_MEM_SIZE);
}
// Read
template<class T>
CL::event CL::data::read(const CL::command_queue &queue, T *host) const{
cl_event event;
CL_ERROR(clEnqueueReadBuffer(queue.handle(),
data_,
CL_FALSE,
0,
size_,
host,
0,
nullptr,
&event));
return event;
}
template<class T>
void CL::data::read(const CL::command_queue &queue, T *host,cl_bool blocking) const{
CL_ERROR(clEnqueueReadBuffer(queue.handle(),
data_,
blocking,
0,
size_,
host,
0,
nullptr,
nullptr));
}
//Explicit Instantiation read
template CL::event CL::data::read<cl_uint>(const CL::command_queue &queue,cl_uint *host) const;
template CL::event CL::data::read<cl_int>(const CL::command_queue &queue,cl_int *host) const;
template CL::event CL::data::read<cl_float>(const CL::command_queue &queue,cl_float *host) const;
template CL::event CL::data::read<cl_float2>(const CL::command_queue &queue,cl_float2 *host) const;
//Explicit Instantiation read
template void CL::data::read<cl_uint>(const CL::command_queue &queue,cl_uint *host,cl_bool blocking) const;
template void CL::data::read<cl_int>(const CL::command_queue &queue,cl_int *host,cl_bool blocking) const;
template void CL::data::read<cl_float>(const CL::command_queue &queue,cl_float *host,cl_bool blocking) const;
template void CL::data::read<cl_float2>(const CL::command_queue &queue,cl_float2 *host,cl_bool blocking) const;
// Write
template<class T>
CL::event CL::data::write(const CL::command_queue &queue, const T *host){
cl_event event;
CL_ERROR(clEnqueueWriteBuffer(queue.handle(),
data_,
CL_FALSE,
0,
size_,
host,
0,
nullptr,
&event));
return event;
}
template<class T>
void CL::data::write(const CL::command_queue &queue, const T *host,cl_bool blocking){
CL_ERROR(clEnqueueWriteBuffer(queue.handle(),
data_,
blocking,
0,
size_,
host,
0,
nullptr,
nullptr));
}
//Explicit Instantiation write
template CL::event CL::data::write<cl_uint>(const CL::command_queue &queue,const cl_uint *host);
template CL::event CL::data::write<cl_int>(const CL::command_queue &queue,const cl_int *host);
template CL::event CL::data::write<cl_float>(const CL::command_queue &queue,const cl_float *host);
template CL::event CL::data::write<cl_float2>(const CL::command_queue &queue,const cl_float2 *host);
template void CL::data::write<cl_uint>(const CL::command_queue &queue,const cl_uint *host,cl_bool blocking);
template void CL::data::write<cl_int>(const CL::command_queue &queue,const cl_int *host,cl_bool blocking);
template void CL::data::write<cl_float>(const CL::command_queue &queue,const cl_float *host,cl_bool blocking);
template void CL::data::write<cl_float2>(const CL::command_queue &queue,const cl_float2 *host,cl_bool blocking);
|
/**
* @file
* @brief Definition of object with set of particles at pixel
* @copyright Copyright (c) 2017-2020 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#ifndef ALLPIX_PIXEL_CHARGE_H
#define ALLPIX_PIXEL_CHARGE_H
#include <Math/DisplacementVector2D.h>
#include <TRef.h>
#include <algorithm>
#include "MCParticle.hpp"
#include "Object.hpp"
#include "Pixel.hpp"
#include "PropagatedCharge.hpp"
#include "Pulse.hpp"
namespace allpix {
/**
* @ingroup Objects
* @brief Set of charges at a pixel
*/
class PixelCharge : public Object {
friend class PixelHit;
public:
/**
* @brief Construct a set of charges at a pixel
* @param pixel Object holding the information of the pixel
* @param charge Amount of charge stored at this pixel
* @param propagated_charges Optional pointer to the related propagated charges
*/
PixelCharge(Pixel pixel,
long charge,
const std::vector<const PropagatedCharge*>& propagated_charges = std::vector<const PropagatedCharge*>());
/**
* @brief Construct a set of charges at a pixel
* @param pixel Object holding the information of the pixel
* @param pulse Pulse of induced or collected charges
* @param propagated_charges Optional pointer to the related propagated charges
*/
PixelCharge(Pixel pixel,
Pulse pulse,
const std::vector<const PropagatedCharge*>& propagated_charges = std::vector<const PropagatedCharge*>());
/**
* @brief Get the pixel containing the charges
* @return Pixel indices in the grid
*/
const Pixel& getPixel() const;
/**
* @brief Shortcut to retrieve the pixel indices
* @return Index of the pixel
*/
Pixel::Index getIndex() const;
/**
* @brief Get the charge at the pixel
* @return Total charge stored
*/
long getCharge() const;
/**
* @brief Get the absolute charge value at the pixel
* @return Absolute total charge stored
*/
unsigned long getAbsoluteCharge() const;
/**
* @brief Get related propagated charges
* @return Possible set of pointers to propagated charges
*/
std::vector<const PropagatedCharge*> getPropagatedCharges() const;
/**
* @brief Get the Monte-Carlo particles resulting in this pixel hit
* @return List of all related Monte-Carlo particles
*/
std::vector<const MCParticle*> getMCParticles() const;
/**
* @brief Get recoded charge pulse
* @return Constatnt reference to the full charge pulse
*/
const Pulse& getPulse() const;
/**
* @brief Get time after start of event in global reference frame
* @return Time from start event
*/
double getGlobalTime() const;
/**
* @brief Get local time in the sensor
* @return Time with respect to local sensor
*/
double getLocalTime() const;
/**
* @brief Print an ASCII representation of PixelCharge to the given stream
* @param out Stream to print to
*/
void print(std::ostream& out) const override;
/**
* @brief ROOT class definition
*/
ClassDefOverride(PixelCharge, 7); // NOLINT
/**
* @brief Default constructor for ROOT I/O
*/
PixelCharge() = default;
private:
Pixel pixel_;
long charge_{};
Pulse pulse_{};
double local_time_{};
double global_time_{};
std::vector<TRef> propagated_charges_;
std::vector<TRef> mc_particles_;
};
/**
* @brief Typedef for message carrying pixel charges
*/
using PixelChargeMessage = Message<PixelCharge>;
} // namespace allpix
#endif /* ALLPIX_PIXEL_CHARGE_H */
|
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018
Vladimír Vondruš <mosra@centrum.cz>
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 <sstream>
#include <Corrade/TestSuite/Tester.h>
#include <Corrade/Utility/Configuration.h>
#include "Magnum/Math/Vector3.h"
struct Vec3 {
float x, y, z;
};
namespace Magnum { namespace Math {
namespace Implementation {
template<> struct VectorConverter<3, float, Vec3> {
constexpr static Vector<3, Float> from(const Vec3& other) {
return {other.x, other.y, other.z};
}
constexpr static Vec3 to(const Vector<3, Float>& other) {
return {other[0], other[1], other[2]};
}
};
}
namespace Test {
struct Vector3Test: Corrade::TestSuite::Tester {
explicit Vector3Test();
void construct();
void constructDefault();
void constructNoInit();
void constructOneValue();
void constructParts();
void constructConversion();
void constructCopy();
void convert();
void access();
void cross();
void axes();
void scales();
void twoComponent();
void swizzleType();
void debug();
void configuration();
};
typedef Math::Vector3<Float> Vector3;
typedef Math::Vector3<Int> Vector3i;
typedef Math::Vector2<Float> Vector2;
Vector3Test::Vector3Test() {
addTests({&Vector3Test::construct,
&Vector3Test::constructDefault,
&Vector3Test::constructNoInit,
&Vector3Test::constructOneValue,
&Vector3Test::constructParts,
&Vector3Test::constructConversion,
&Vector3Test::constructCopy,
&Vector3Test::convert,
&Vector3Test::access,
&Vector3Test::cross,
&Vector3Test::axes,
&Vector3Test::scales,
&Vector3Test::twoComponent,
&Vector3Test::swizzleType,
&Vector3Test::debug,
&Vector3Test::configuration});
}
void Vector3Test::construct() {
constexpr Vector3 a = {1.0f, 2.5f, -3.0f};
CORRADE_COMPARE(a, (Vector<3, Float>(1.0f, 2.5f, -3.0f)));
CORRADE_VERIFY((std::is_nothrow_constructible<Vector3, Float, Float, Float>::value));
}
void Vector3Test::constructDefault() {
constexpr Vector3 a;
constexpr Vector3 b{ZeroInit};
CORRADE_COMPARE(a, Vector3(0.0f, 0.0f, 0.0f));
CORRADE_COMPARE(b, Vector3(0.0f, 0.0f, 0.0f));
CORRADE_VERIFY(std::is_nothrow_default_constructible<Vector3>::value);
CORRADE_VERIFY((std::is_nothrow_constructible<Vector3, ZeroInitT>::value));
}
void Vector3Test::constructNoInit() {
Vector3 a{1.0f, 2.5f, -3.0f};
new(&a) Vector3{NoInit};
{
#if defined(__GNUC__) && __GNUC__*100 + __GNUC_MINOR__ >= 601 && __OPTIMIZE__
CORRADE_EXPECT_FAIL("GCC 6.1+ misoptimizes and overwrites the value.");
#endif
CORRADE_COMPARE(a, (Vector3{1.0f, 2.5f, -3.0f}));
}
CORRADE_VERIFY((std::is_nothrow_constructible<Vector3, NoInitT>::value));
/* Implicit construction is not allowed */
CORRADE_VERIFY(!(std::is_convertible<NoInitT, Vector3>::value));
}
void Vector3Test::constructOneValue() {
constexpr Vector3 a(-3.0f);
CORRADE_COMPARE(a, Vector3(-3.0f, -3.0f, -3.0f));
/* Implicit conversion is not allowed */
CORRADE_VERIFY(!(std::is_convertible<Float, Vector3>::value));
CORRADE_VERIFY((std::is_nothrow_constructible<Vector3, Float>::value));
}
void Vector3Test::constructParts() {
constexpr Vector2 a(1.0f, 2.0f);
constexpr Vector3 b = {a, 3.0f};
CORRADE_COMPARE(b, Vector3(1.0f, 2.0f, 3.0f));
CORRADE_VERIFY((std::is_nothrow_constructible<Vector3, Vector2, Float>::value));
}
void Vector3Test::constructConversion() {
constexpr Vector3 a(1.0f, 2.5f, -3.0f);
constexpr Vector3i b(a);
CORRADE_COMPARE(b, Vector3i(1, 2, -3));
/* Implicit conversion is not allowed */
CORRADE_VERIFY(!(std::is_convertible<Vector3, Vector3i>::value));
CORRADE_VERIFY((std::is_nothrow_constructible<Vector3, Vector3i>::value));
}
void Vector3Test::constructCopy() {
constexpr Vector<3, Float> a(1.0f, 2.5f, -3.0f);
#ifndef CORRADE_MSVC2015_COMPATIBILITY /* Why can't be copy constexpr? */
constexpr
#endif
Vector3 b(a);
CORRADE_COMPARE(b, Vector3(1.0f, 2.5f, -3.0f));
CORRADE_VERIFY(std::is_nothrow_copy_constructible<Vector3>::value);
CORRADE_VERIFY(std::is_nothrow_copy_assignable<Vector3>::value);
}
void Vector3Test::convert() {
constexpr Vec3 a{1.5f, 2.0f, -3.5f};
constexpr Vector3 b(1.5f, 2.0f, -3.5f);
constexpr Vector3 c(a);
CORRADE_COMPARE(c, b);
constexpr Vec3 d(b);
CORRADE_COMPARE(d.x, a.x);
CORRADE_COMPARE(d.y, a.y);
CORRADE_COMPARE(d.z, a.z);
/* Implicit conversion is not allowed */
CORRADE_VERIFY(!(std::is_convertible<Vec3, Vector3>::value));
CORRADE_VERIFY(!(std::is_convertible<Vector3, Vec3>::value));
}
void Vector3Test::access() {
Vector3 vec(1.0f, -2.0f, 5.0f);
CORRADE_COMPARE(vec.x(), 1.0f);
CORRADE_COMPARE(vec.r(), 1.0f);
CORRADE_COMPARE(vec.y(), -2.0f);
CORRADE_COMPARE(vec.g(), -2.0f);
CORRADE_COMPARE(vec.z(), 5.0f);
CORRADE_COMPARE(vec.b(), 5.0f);
constexpr Vector3 cvec(1.0f, -2.0f, 5.0f);
constexpr Float x = cvec.x();
constexpr Float r = cvec.r();
constexpr Float y = cvec.y();
constexpr Float g = cvec.g();
constexpr Float z = cvec.z();
constexpr Float b = cvec.b();
CORRADE_COMPARE(x, 1.0f);
CORRADE_COMPARE(r, 1.0f);
CORRADE_COMPARE(y, -2.0f);
CORRADE_COMPARE(g, -2.0f);
CORRADE_COMPARE(z, 5.0f);
CORRADE_COMPARE(b, 5.0f);
}
void Vector3Test::cross() {
Vector3i a(1, -1, 1);
Vector3i b(4, 3, 7);
CORRADE_COMPARE(Math::cross(a, b), Vector3i(-10, -3, 7));
}
void Vector3Test::axes() {
constexpr Vector3 x = Vector3::xAxis(5.0f);
constexpr Vector3 y = Vector3::yAxis(6.0f);
constexpr Vector3 z = Vector3::zAxis(7.0f);
CORRADE_COMPARE(x, Vector3(5.0f, 0.0f, 0.0f));
CORRADE_COMPARE(y, Vector3(0.0f, 6.0f, 0.0f));
CORRADE_COMPARE(z, Vector3(0.0f, 0.0f, 7.0f));
}
void Vector3Test::scales() {
constexpr Vector3 x = Vector3::xScale(-5.0f);
constexpr Vector3 y = Vector3::yScale(-0.2f);
constexpr Vector3 z = Vector3::zScale(71.0f);
CORRADE_COMPARE(x, Vector3(-5.0f, 1.0f, 1.0f));
CORRADE_COMPARE(y, Vector3(1.0f, -0.2f, 1.0f));
CORRADE_COMPARE(z, Vector3(1.0f, 1.0f, 71.0f));
}
void Vector3Test::twoComponent() {
Vector3 a(1.0f, 2.0f, 3.0f);
CORRADE_COMPARE(a.xy(), Vector2(1.0f, 2.0f));
constexpr Vector3 b(1.0f, 2.0f, 3.0f);
constexpr Vector2 c = b.xy();
constexpr Float d = b.xy().y();
CORRADE_COMPARE(c, Vector2(1.0f, 2.0f));
CORRADE_COMPARE(d, 2.0f);
}
void Vector3Test::swizzleType() {
constexpr Vector<4, Int> orig;
constexpr auto b = swizzle<'y', 'z', 'a'>(orig);
CORRADE_VERIFY((std::is_same<decltype(b), const Vector3i>::value));
}
void Vector3Test::debug() {
std::ostringstream o;
Debug(&o) << Vector3(0.5f, 15.0f, 1.0f);
CORRADE_COMPARE(o.str(), "Vector(0.5, 15, 1)\n");
}
void Vector3Test::configuration() {
Corrade::Utility::Configuration c;
Vector3 vec(3.0f, 3.125f, 9.55f);
std::string value("3 3.125 9.55");
c.setValue("vector", vec);
CORRADE_COMPARE(c.value("vector"), value);
CORRADE_COMPARE(c.value<Vector3>("vector"), vec);
}
}}}
CORRADE_TEST_MAIN(Magnum::Math::Test::Vector3Test)
|
//=================================================================================================
/*!
// \file src/mathtest/operations/dmatsmatkron/MDbHCb.cpp
// \brief Source file for the MDbHCb dense matrix/sparse matrix Kronecker product math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/HermitianMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/dmatsmatkron/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MDbHCb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using MDb = blaze::DynamicMatrix<TypeB>;
using HCb = blaze::HermitianMatrix< blaze::CompressedMatrix<TypeB> >;
// Creator type definitions
using CMDb = blazetest::Creator<MDb>;
using CHCb = blazetest::Creator<HCb>;
// Running tests with small matrices
for( size_t i=0UL; i<=4UL; ++i ) {
for( size_t j=0UL; j<=4UL; ++j ) {
for( size_t k=0UL; k<=4UL; ++k ) {
for( size_t l=0UL; l<=k*k; ++l ) {
RUN_DMATSMATKRON_OPERATION_TEST( CMDb( i, j ), CHCb( k, l ) );
}
}
}
}
// Running tests with large matrices
RUN_DMATSMATKRON_OPERATION_TEST( CMDb( 9UL, 15UL ), CHCb( 8UL, 7UL ) );
RUN_DMATSMATKRON_OPERATION_TEST( CMDb( 16UL, 8UL ), CHCb( 15UL, 7UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix Kronecker product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <init.h>
#include <addrman.h>
#include <amount.h>
#include <banman.h>
#include <blockfilter.h>
#include <chain.h>
#include <chainparams.h>
#include <compat/sanity.h>
#include <consensus/validation.h>
#include <fs.h>
#include <httprpc.h>
#include <httpserver.h>
#include <index/blockfilterindex.h>
#include <index/txindex.h>
#include <interfaces/chain.h>
#include <key.h>
#include <logging.h>
#include <miner.h>
#include <net.h>
#include <net_permissions.h>
#include <net_processing.h>
#include <netbase.h>
#include <node/context.h>
#include <policy/feerate.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <rpc/blockchain.h>
#include <rpc/register.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <scheduler.h>
#include <script/sigcache.h>
#include <script/standard.h>
#include <shutdown.h>
#include <timedata.h>
#include <torcontrol.h>
#include <txdb.h>
#include <txmempool.h>
#include <ui_interface.h>
#include <util/asmap.h>
#include <util/convert.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <util/threadnames.h>
#include <util/translation.h>
#include <validation.h>
#include <hash.h>
#include <validationinterface.h>
#ifdef ENABLE_WALLET
#include <wallet/wallet.h>
#endif
#include <walletinitinterface.h>
#include <key_io.h>
#include <stdint.h>
#include <stdio.h>
#include <set>
#ifndef WIN32
#include <attributes.h>
#include <cerrno>
#include <signal.h>
#include <sys/stat.h>
#endif
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/thread.hpp>
#if ENABLE_ZMQ
#include <zmq/zmqabstractnotifier.h>
#include <zmq/zmqnotificationinterface.h>
#include <zmq/zmqrpc.h>
#endif
static bool fFeeEstimatesInitialized = false;
static const bool DEFAULT_PROXYRANDOMIZE = true;
static const bool DEFAULT_REST_ENABLE = false;
static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files don't count towards the fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map";
/**
* The PID file facilities.
*/
static const char* BITCOIN_PID_FILENAME = "yupostd.pid";
static fs::path GetPidFile()
{
return AbsPathForConfigVal(fs::path(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME)));
}
NODISCARD static bool CreatePidFile()
{
fsbridge::ofstream file{GetPidFile()};
if (file) {
#ifdef WIN32
tfm::format(file, "%d\n", GetCurrentProcessId());
#else
tfm::format(file, "%d\n", getpid());
#endif
return true;
} else {
return InitError(strprintf(_("Unable to create the PID file '%s': %s").translated, GetPidFile().string(), std::strerror(errno)));
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets ShutdownRequested(), which makes main thread's
// WaitForShutdown() interrupts the thread group.
// And then, WaitForShutdown() makes all other on-going threads
// in the thread group join the main thread.
// Shutdown() is then called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// ShutdownRequested() getting set, and then does the normal Qt
// shutdown thing.
//
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
static boost::thread_group threadGroup;
void Interrupt(NodeContext& node)
{
InterruptHTTPServer();
InterruptHTTPRPC();
InterruptRPC();
InterruptREST();
InterruptTorControl();
InterruptMapPort();
if (node.connman)
node.connman->Interrupt();
if (g_txindex) {
g_txindex->Interrupt();
}
ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Interrupt(); });
}
void Shutdown(NodeContext& node)
{
StartShutdown();
LogPrintf("%s: In progress...\n", __func__);
static RecursiveMutex cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown)
return;
/// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
/// for example if the data directory was found to be locked.
/// Be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized.
util::ThreadRename("yupost-shutoff");
#ifdef ENABLE_WALLET
// Force stop the stakers before any other components
for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
pwallet->StopStake();
}
#endif
mempool.AddTransactionsUpdated(1);
StopHTTPRPC();
StopREST();
StopRPC();
StopHTTPServer();
for (const auto& client : node.chain_clients) {
client->flush();
}
StopMapPort();
// Because these depend on each-other, we make sure that neither can be
// using the other before destroying them.
if (node.peer_logic) UnregisterValidationInterface(node.peer_logic.get());
// Follow the lock order requirements:
// * CheckForStaleTipAndEvictPeers locks cs_main before indirectly calling GetExtraOutboundCount
// which locks cs_vNodes.
// * ProcessMessage locks cs_main and g_cs_orphans before indirectly calling ForEachNode which
// locks cs_vNodes.
// * CConnman::Stop calls DeleteNode, which calls FinalizeNode, which locks cs_main and calls
// EraseOrphansFor, which locks g_cs_orphans.
//
// Thus the implicit locking order requirement is: (1) cs_main, (2) g_cs_orphans, (3) cs_vNodes.
if (node.connman) {
node.connman->StopThreads();
LOCK2(::cs_main, ::g_cs_orphans);
node.connman->StopNodes();
}
StopTorControl();
// After everything has been shut down, but before things get flushed, stop the
// CScheduler/checkqueue threadGroup
if (node.scheduler) node.scheduler->stop();
threadGroup.interrupt_all();
threadGroup.join_all();
// After the threads that potentially access these pointers have been stopped,
// destruct and reset all to nullptr.
node.peer_logic.reset();
node.connman.reset();
node.banman.reset();
if (::mempool.IsLoaded() && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
DumpMempool(::mempool);
}
if (fFeeEstimatesInitialized)
{
::feeEstimator.FlushUnconfirmed();
fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
if (!est_fileout.IsNull())
::feeEstimator.Write(est_fileout);
else
LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
fFeeEstimatesInitialized = false;
}
// FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
//
// g_chainstate is referenced here directly (instead of ::ChainstateActive()) because it
// may not have been initialized yet.
{
LOCK(cs_main);
if (g_chainstate && g_chainstate->CanFlushToDisk()) {
g_chainstate->ForceFlushStateToDisk();
}
}
// After there are no more peers/RPC left to give us new data which may generate
// CValidationInterface callbacks, flush them...
GetMainSignals().FlushBackgroundCallbacks();
// Stop and delete all indexes only after flushing background callbacks.
if (g_txindex) {
g_txindex->Stop();
g_txindex.reset();
}
ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Stop(); });
DestroyAllBlockFilterIndexes();
// Any future callbacks will be dropped. This should absolutely be safe - if
// missing a callback results in an unrecoverable situation, unclean shutdown
// would too. The only reason to do the above flushes is to let the wallet catch
// up with our current chain to avoid any strange pruning edge cases and make
// next startup faster by avoiding rescan.
{
LOCK(cs_main);
if (g_chainstate && g_chainstate->CanFlushToDisk()) {
g_chainstate->ForceFlushStateToDisk();
g_chainstate->ResetCoinsViews();
}
pblocktree.reset();
pstorageresult.reset();
globalState.reset();
globalSealEngine.reset();
}
for (const auto& client : node.chain_clients) {
client->stop();
}
#if ENABLE_ZMQ
if (g_zmq_notification_interface) {
UnregisterValidationInterface(g_zmq_notification_interface);
delete g_zmq_notification_interface;
g_zmq_notification_interface = nullptr;
}
#endif
node.chain_clients.clear();
UnregisterAllValidationInterfaces();
GetMainSignals().UnregisterBackgroundSignalScheduler();
globalVerifyHandle.reset();
ECC_Stop();
if (node.mempool) node.mempool = nullptr;
node.scheduler.reset();
try {
if (!fs::remove(GetPidFile())) {
LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__);
}
} catch (const fs::filesystem_error& e) {
LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
}
LogPrintf("%s: done\n", __func__);
}
/**
* Signal handlers are very limited in what they are allowed to do.
* The execution context the handler is invoked in is not guaranteed,
* so we restrict handler operations to just touching variables:
*/
#ifndef WIN32
static void HandleSIGTERM(int)
{
StartShutdown();
}
static void HandleSIGHUP(int)
{
LogInstance().m_reopen_file = true;
}
#else
static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
{
StartShutdown();
Sleep(INFINITE);
return true;
}
#endif
#ifndef WIN32
static void registerSignalHandler(int signal, void(*handler)(int))
{
struct sigaction sa;
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(signal, &sa, nullptr);
}
#endif
static boost::signals2::connection rpc_notify_block_change_connection;
static void OnRPCStarted()
{
rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(&RPCNotifyBlockChange);
}
static void OnRPCStopped()
{
rpc_notify_block_change_connection.disconnect();
RPCNotifyBlockChange(false, nullptr);
g_best_block_cv.notify_all();
LogPrint(BCLog::RPC, "RPC stopped.\n");
}
void SetupServerArgs()
{
SetupHelpOptions(gArgs);
gArgs.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
const auto regtestChainParams = CreateChainParams(CBaseChainParams::REGTEST);
// Hidden Options
std::vector<std::string> hidden_args = {
"-dbcrashratio", "-forcecompactdb",
// GUI args. These will be overwritten by SetupUIArgs for the GUI
"-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"};
gArgs.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#if HAVE_SYSTEM
gArgs.AddArg("-alertnotify=<cmd>", "Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#endif
gArgs.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#if HAVE_SYSTEM
gArgs.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#endif
gArgs.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Automatic broadcast and rebroadcast of any transactions from inbound peers is disabled, unless '-whitelistforcerelay' is '1', in which case whitelisted peers' transactions will be relayed. RPC transactions are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-conf=<file>", strprintf("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-par=<n>", strprintf("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)",
-GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. "
"Warning: Reverting this setting requires re-downloading the entire blockchain. "
"(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-record-log-opcodes", "Logs all EVM LOG opcode operations to the file vmExecLogs.json", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#ifndef WIN32
gArgs.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#else
hidden_args.emplace_back("-sysperms");
#endif
gArgs.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-blockfilterindex=<type>",
strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +
" If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-logevents", strprintf("Maintain a full EVM log index, used by searchlogs and gettransactionreceipt rpc calls (default: %u)", DEFAULT_LOGEVENTS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-addrindex", strprintf("Maintain a full address index (default: %u)", DEFAULT_ADDRINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-deleteblockchaindata", "Delete the local copy of the block chain data", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-forceinitialblocksdownloadmode", strprintf("Force initial blocks download mode for the node (default: %u)", DEFAULT_FORCE_INITIAL_BLOCKS_DOWNLOAD_MODE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-addnode=<ip>", "Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-asmap=<file>", strprintf("Specify asn mapping used for bucketing of the peers (default: %s). Relative paths will be prefixed by the net-specific datadir location.", DEFAULT_ASMAP_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-banscore=<n>", strprintf("Threshold for disconnecting and discouraging misbehaving peers (default: %u)", DEFAULT_BANSCORE_THRESHOLD), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-bind=<addr>", "Bind to given address and always listen on it. Use [host]:port notation for IPv6", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-dnsseed", "Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-listenonion", strprintf("Automatically create Tor hidden service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u)", DEFAULT_MAX_PEER_CONNECTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxtimeadjustment", strprintf("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)", DEFAULT_MAX_TIME_ADJUSTMENT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor hidden services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-timeout=<n>", strprintf("Specify connection timeout in milliseconds (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-peertimeout=<n>", strprintf("Specify p2p connection timeout in seconds. This option determines the amount of time a peer may be inactive before the connection to it is dropped. (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION);
gArgs.AddArg("-dgpstorage", "Receiving data from DGP via storage (default: -dgpevm)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-dgpevm", "Receiving data from DGP via a contract call (default: -dgpevm)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-hwitoolpath=<path>", "Specify HWI tool path", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#ifdef USE_UPNP
#if USE_UPNP
gArgs.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#else
gArgs.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#endif
#else
hidden_args.emplace_back("-upnp");
#endif
gArgs.AddArg("-whitebind=<[permissions@]addr>", "Bind to given address and whitelist peers connecting to it. "
"Use [host]:port notation for IPv6. Allowed permissions are bloomfilter (allow requesting BIP37 filtered blocks and transactions), "
"noban (do not ban for misbehavior), "
"forcerelay (relay transactions that are already in the mempool; implies relay), "
"relay (relay even in -blocksonly mode), "
"and mempool (allow requesting BIP35 mempool contents). "
"Specify multiple permissions separated by commas (default: noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-whitelist=<[permissions@]IP address or network>", "Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or "
"CIDR notated network(e.g. 1.2.3.0/24). Uses same permissions as "
"-whitebind. Can be specified multiple times." , ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
g_wallet_init_interface.AddWalletOptions();
#if ENABLE_ZMQ
gArgs.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#else
hidden_args.emplace_back("-zmqpubhashblock=<address>");
hidden_args.emplace_back("-zmqpubhashtx=<address>");
hidden_args.emplace_back("-zmqpubrawblock=<address>");
hidden_args.emplace_back("-zmqpubrawtx=<address>");
hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
#endif
gArgs.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: "
"level 0 reads the blocks from disk, "
"level 1 verifies block validity, "
"level 2 verifies undo data, "
"level 3 checks disconnection of tip blocks, "
"and level 4 tries to reconnect the blocks, "
"each level includes the checks of the previous levels "
"(0-4, default: %u)", DEFAULT_CHECKLEVEL), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checkpoints", strprintf("Enable rejection of any forks from the known historical chain until block 295000 (default: %u)", DEFAULT_CHECKPOINTS_ENABLED), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-addrmantest", "Allows to test address relay on localhost", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). "
"If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + ListLogCategories() + ".", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-debugexclude=<category>", strprintf("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories."), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
#ifdef HAVE_THREAD_LOCAL
gArgs.AddArg("-logthreadnames", strprintf("Prepend debug output with name of the originating thread (only available on platforms supporting thread_local) (default: %u)", DEFAULT_LOGTHREADNAMES), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
#else
hidden_args.emplace_back("-logthreadnames");
#endif
gArgs.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-showevmlogs", strprintf("Print evm logs to console (default: %u)", DEFAULT_SHOWEVMLOGS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-minmempoolgaslimit=<limit>", strprintf("The minimum transaction gas limit we are willing to accept into the mempool (default: %s)",MEMPOOL_MIN_GAS_LIMIT), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-opsenderheight=<n>", "Use given block height to check opsender fork (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-btcecrecoverheight=<n>", "Use given block height to check btc_ecrecover fork (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-constantinopleheight=<n>", "Use given block height to check constantinople fork (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-difficultychangeheight=<n>", "Use given block height to check difficulty change fork (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-offlinestakingheight=<n>", "Use given block height to check offline staking fork (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-delegationsaddress=<adr>", "Use given contract delegations address for offline staking fork (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-lastmposheight=<n>", "Use given block height to check remove mpos fork (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-reduceblocktimeheight=<n>", "Use given block height to check blocks with reduced target spacing (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-powallowmindifficultyblocks", "Use given value for pow allow min difficulty blocks parameter (regtest-only, default: 1)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-pownoretargeting", "Use given value for pow no retargeting parameter (regtest-only, default: 1)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-posnoretargeting", "Use given value for pos no retargeting parameter (regtest-only, default: 1)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-muirglacierheight=<n>", "Use given block height to check contracts with EVM Muir Glacier (regtest-only)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
SetupChainParamsBaseOptions();
gArgs.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted inbound peers with default permissions. This will relay transactions even if the transactions were already in the mempool. (default: %d)", DEFAULT_WHITELISTFORCERELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted inbound peers with default permissions. This will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-staker-min-tx-gas-price=<amt>", "Any contract execution with a gas price below this will not be included in a block (defaults to the value specified by the DGP)", ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-staker-max-tx-gas-limit=<n>", "Any contract execution with a gas limit over this amount will not be included in a block (defaults to soft block gas limit)", ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-staker-soft-block-gas-limit=<n>", "After this amount of gas is surpassed in a block, no more contract executions will be added to the block (defaults to consensus-critical maximum block gas limit)", ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-aggressive-staking", "Check more often to publish immediately when valid block is found.", ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-emergencystaking", "Emergency staking without blockchain synchronization.", ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
gArgs.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
gArgs.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
gArgs.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-rpcserialversion", strprintf("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
gArgs.AddArg("-rpcwhitelist=<whitelist>", "Set a whitelist to filter incoming RPC calls for a specific user. The field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc 2>,...,<rpc n>. If multiple whitelists are set for a given user, they are set-intersected. See -rpcwhitelistdefault documentation for information on default whitelist behavior.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcwhitelistdefault", "Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.", ArgsManager::ALLOW_BOOL, OptionsCategory::RPC);
gArgs.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#if HAVE_DECL_DAEMON
gArgs.AddArg("-daemon", "Run in the background as a daemon and accept commands", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#else
hidden_args.emplace_back("-daemon");
#endif
gArgs.AddArg("-headerspamfilter=<n>", strprintf("Use header spam filter (default: %u)", DEFAULT_HEADER_SPAM_FILTER), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-headerspamfiltermaxsize=<n>", strprintf("Maximum size of the list of indexes in the header spam filter (default: %u)", DEFAULT_HEADER_SPAM_FILTER_MAX_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-headerspamfiltermaxavg=<n>", strprintf("Maximum average size of an index occurrence in the header spam filter (default: %u)", DEFAULT_HEADER_SPAM_FILTER_MAX_AVG), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-headerspamfilterignoreport=<n>", strprintf("Ignore the port in the ip address when looking for header spam, determine whether or not multiple nodes can be on the same IP (default: %u)", DEFAULT_HEADER_SPAM_FILTER_IGNORE_PORT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-cleanblockindex=<true/false>", "Clean block index (enabled by default)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-cleanblockindextimeout=<n>", "Clean block index periodically after some time (default 600 seconds)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-stakingallowlist=<address>", "Allow list delegate address. Can be specified multiple times to add multiple addresses.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-stakingexcludelist=<address>", "Exclude list delegate address. Can be specified multiple times to add multiple addresses.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
// Add the hidden options
gArgs.AddHiddenArgs(hidden_args);
}
std::string LicenseInfo()
{
const std::string URL_SOURCE_CODE = "<https://github.com/YuPostX/yupost>";
return CopyrightHolders(strprintf(_("Copyright (C) %i").translated, COPYRIGHT_YEAR) + " ") + "\n" +
"\n" +
strprintf(_("Please contribute if you find %s useful. "
"Visit %s for further information about the software.").translated,
PACKAGE_NAME, "<" PACKAGE_URL ">") +
"\n" +
strprintf(_("The source code is available from %s.").translated,
URL_SOURCE_CODE) +
"\n" +
"\n" +
_("This is experimental software.").translated + "\n" +
strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s").translated, "COPYING", "<https://opensource.org/licenses/MIT>") +
"\n";
}
#if HAVE_SYSTEM
static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
{
if (initialSync || !pBlockIndex)
return;
std::string strCmd = gArgs.GetArg("-blocknotify", "");
if (!strCmd.empty()) {
boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
std::thread t(runCommand, strCmd);
t.detach(); // thread runs free
}
}
#endif
static bool fHaveGenesis = false;
static Mutex g_genesis_wait_mutex;
static std::condition_variable g_genesis_wait_cv;
static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
{
if (pBlockIndex != nullptr) {
{
LOCK(g_genesis_wait_mutex);
fHaveGenesis = true;
}
g_genesis_wait_cv.notify_all();
}
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
// If we're using -prune with -reindex, then delete block files that will be ignored by the
// reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
// is missing, do the same here to delete any later block files after a gap. Also delete all
// rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
// is in sync with what's actually on disk by the time we start downloading, so that pruning
// works correctly.
static void CleanupBlockRevFiles()
{
std::map<std::string, fs::path> mapBlockFiles;
// Glob all blk?????.dat and rev?????.dat files from the blocks directory.
// Remove the rev files immediately and insert the blk file paths into an
// ordered map keyed by block file index.
LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
fs::path blocksdir = GetBlocksDir();
for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
if (fs::is_regular_file(*it) &&
it->path().filename().string().length() == 12 &&
it->path().filename().string().substr(8,4) == ".dat")
{
if (it->path().filename().string().substr(0,3) == "blk")
mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
else if (it->path().filename().string().substr(0,3) == "rev")
remove(it->path());
}
}
// Remove all block files that aren't part of a contiguous set starting at
// zero by walking the ordered map (keys are block file indices) by
// keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
// start removing block files.
int nContigCounter = 0;
for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
if (atoi(item.first) == nContigCounter) {
nContigCounter++;
continue;
}
remove(item.second);
}
}
// Delete local blockchain data
void DeleteBlockChainData()
{
// Delete block chain data paths
fs::remove_all(GetDataDir() / "chainstate");
fs::remove_all(GetBlocksDir());
fs::remove_all(GetDataDir() / "stateYuPost");
fs::remove(GetDataDir() / "banlist.dat");
fs::remove(GetDataDir() / FEE_ESTIMATES_FILENAME);
fs::remove(GetDataDir() / "mempool.dat");
}
static void ThreadImport(std::vector<fs::path> vImportFiles)
{
const CChainParams& chainparams = Params();
util::ThreadRename("loadblk");
ScheduleBatchPriority();
{
CImportingNow imp;
// -reindex
if (fReindex) {
int nFile = 0;
while (true) {
FlatFilePos pos(nFile, 0);
if (!fs::exists(GetBlockPosFilename(pos)))
break; // No block files left to reindex
FILE *file = OpenBlockFile(pos, true);
if (!file)
break; // This error is logged in OpenBlockFile
LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(chainparams, file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
LogPrintf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
LoadGenesisBlock(chainparams);
#ifdef ENABLE_WALLET
// Clean not reverted coinstake transactions
for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
pwallet->CleanCoinStake();
}
#endif
}
// -loadblock=
for (const fs::path& path : vImportFiles) {
FILE *file = fsbridge::fopen(path, "rb");
if (file) {
LogPrintf("Importing blocks file %s...\n", path.string());
LoadExternalBlockFile(chainparams, file);
} else {
LogPrintf("Warning: Could not open blocks file %s\n", path.string());
}
}
// scan for better chains in the block chain database, that are not yet connected in the active best chain
BlockValidationState state;
if (!ActivateBestChain(state, chainparams)) {
LogPrintf("Failed to connect best block (%s)\n", state.ToString());
StartShutdown();
return;
}
if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
LogPrintf("Stopping after block import\n");
StartShutdown();
return;
}
} // End scope of CImportingNow
if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
LoadMempool(::mempool);
}
::mempool.SetIsLoaded(!ShutdownRequested());
}
/** Sanity checks
* Ensure that Bitcoin is running in a usable environment with all
* necessary library support.
*/
static bool InitSanityCheck()
{
if(!ECC_InitSanityCheck()) {
InitError("Elliptic curve cryptography sanity check failure. Aborting.");
return false;
}
if (!glibc_sanity_test() || !glibcxx_sanity_test())
return false;
if (!Random_SanityCheck()) {
InitError("OS cryptographic RNG sanity check failure. Aborting.");
return false;
}
return true;
}
static bool AppInitServers()
{
RPCServer::OnStarted(&OnRPCStarted);
RPCServer::OnStopped(&OnRPCStopped);
if (!InitHTTPServer())
return false;
StartRPC();
if (!StartHTTPRPC())
return false;
if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST();
StartHTTPServer();
return true;
}
// Parameter interaction based on rules
void InitParameterInteraction()
{
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
if (gArgs.IsArgSet("-bind")) {
if (gArgs.SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
}
if (gArgs.IsArgSet("-whitebind")) {
if (gArgs.SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
}
if (gArgs.IsArgSet("-connect")) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
if (gArgs.SoftSetBoolArg("-dnsseed", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
if (gArgs.SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
}
if (gArgs.IsArgSet("-proxy")) {
// to protect privacy, do not listen by default if a default proxy server is specified
if (gArgs.SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
// to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
// to listen locally, so don't rely on this happening through -listen below.
if (gArgs.SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
// to protect privacy, do not discover addresses by default
if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
}
if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
if (gArgs.SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
if (gArgs.SoftSetBoolArg("-listenonion", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
}
if (gArgs.IsArgSet("-externalip")) {
// if an explicit public IP is specified, do not try to find others
if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
}
// disable whitelistrelay in blocksonly mode
if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
}
// Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
}
#ifdef ENABLE_WALLET
// Set the required parameters for super staking
if(gArgs.GetBoolArg("-superstaking", DEFAULT_SUPER_STAKE))
{
if (gArgs.SoftSetBoolArg("-staking", true))
LogPrintf("%s: parameter interaction: -superstaking=1 -> setting -staking=1\n", __func__);
if (gArgs.SoftSetBoolArg("-logevents", true))
LogPrintf("%s: parameter interaction: -superstaking=1 -> setting -logevents=1\n", __func__);
if (gArgs.SoftSetBoolArg("-addrindex", true))
LogPrintf("%s: parameter interaction: -superstaking=1 -> setting -addrindex=1\n", __func__);
}
#endif
}
/**
* Initialize global loggers.
*
* Note that this is called very early in the process lifetime, so you should be
* careful about what global state you rely on here.
*/
void InitLogging()
{
LogInstance().m_print_to_file = !gArgs.IsArgNegated("-debuglogfile");
LogInstance().m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
LogInstance().m_file_pathVM = AbsPathForConfigVal(gArgs.GetArg("-debugvmlogfile", DEFAULT_DEBUGVMLOGFILE));
LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", !gArgs.GetBoolArg("-daemon", false));
LogInstance().m_log_timestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
LogInstance().m_log_time_micros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
#ifdef HAVE_THREAD_LOCAL
LogInstance().m_log_threadnames = gArgs.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
#endif
LogInstance().m_show_evm_logs = gArgs.GetBoolArg("-showevmlogs", DEFAULT_SHOWEVMLOGS);
dev::g_logPost = [&](std::string const& s, char const* c){ LogInstance().LogPrintStr(s + '\n', true); };
fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
std::string version_string = FormatFullVersion();
#ifdef DEBUG
version_string += " (debug build)";
#else
version_string += " (release build)";
#endif
LogPrintf(PACKAGE_NAME " version %s\n", version_string);
}
namespace { // Variables internal to initialization process only
int nMaxConnections;
int nUserMaxConnections;
int nFD;
ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK | NODE_NETWORK_LIMITED);
int64_t peer_connect_timeout;
std::set<BlockFilterType> g_enabled_filter_types;
} // namespace
[[noreturn]] static void new_handler_terminate()
{
// Rather than throwing std::bad-alloc if allocation fails, terminate
// immediately to (try to) avoid chain corruption.
// Since LogPrintf may itself allocate memory, set the handler directly
// to terminate first.
std::set_new_handler(std::terminate);
LogPrintf("Error: Out of memory. Terminating.\n");
// The log was successful, terminate now.
std::terminate();
};
bool AppInitBasicSetup()
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable heap terminate-on-corruption
HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
#endif
if (!SetupNetworking())
return InitError("Initializing networking failed");
#ifndef WIN32
if (!gArgs.GetBoolArg("-sysperms", false)) {
umask(077);
}
// Clean shutdown on SIGTERM
registerSignalHandler(SIGTERM, HandleSIGTERM);
registerSignalHandler(SIGINT, HandleSIGTERM);
// Reopen debug.log on SIGHUP
registerSignalHandler(SIGHUP, HandleSIGHUP);
// Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
signal(SIGPIPE, SIG_IGN);
#else
SetConsoleCtrlHandler(consoleCtrlHandler, true);
#endif
std::set_new_handler(new_handler_terminate);
return true;
}
bool AppInitParameterInteraction()
{
const CChainParams& chainparams = Params();
// ********************************************************* Step 2: parameter interactions
// also see: InitParameterInteraction()
// Warn if network-specific options (-addnode, -connect, etc) are
// specified in default section of config file, but not overridden
// on the command line or in this network's section of the config file.
std::string network = gArgs.GetChainName();
for (const auto& arg : gArgs.GetUnsuitableSectionOnlyArgs()) {
return InitError(strprintf(_("Config setting for %s only applied on %s network when in [%s] section.").translated, arg, network, network));
}
// Warn if unrecognized section name are present in the config file.
for (const auto& section : gArgs.GetUnrecognizedSections()) {
InitWarning(strprintf("%s:%i " + _("Section [%s] is not recognized.").translated, section.m_file, section.m_line, section.m_name));
}
if (!fs::is_directory(GetBlocksDir())) {
return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist.").translated, gArgs.GetArg("-blocksdir", "")));
}
// parse and validate enabled filter types
std::string blockfilterindex_value = gArgs.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
g_enabled_filter_types = AllBlockFilterTypes();
} else if (blockfilterindex_value != "0") {
const std::vector<std::string> names = gArgs.GetArgs("-blockfilterindex");
for (const auto& name : names) {
BlockFilterType filter_type;
if (!BlockFilterTypeByName(name, filter_type)) {
return InitError(strprintf(_("Unknown -blockfilterindex value %s.").translated, name));
}
g_enabled_filter_types.insert(filter_type);
}
}
// if using block pruning, then disallow txindex
if (gArgs.GetArg("-prune", 0)) {
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
return InitError(_("Prune mode is incompatible with -txindex.").translated);
if (!g_enabled_filter_types.empty()) {
return InitError(_("Prune mode is incompatible with -blockfilterindex.").translated);
}
}
// -bind and -whitebind can't be set when not listening
size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
return InitError("Cannot set -bind or -whitebind together with -listen=0");
}
// Make sure enough file descriptors are available
int nBind = std::max(nUserBind, size_t(1));
nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
nMaxConnections = std::max(nUserMaxConnections, 0);
// Trim requested connection counts, to fit into system limitations
// <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
#ifdef USE_POLL
int fd_max = nFD;
#else
int fd_max = FD_SETSIZE;
#endif
nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available.").translated);
nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
if (nMaxConnections < nUserMaxConnections)
InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations.").translated, nUserMaxConnections, nMaxConnections));
// ********************************************************* Step 3: parameter-to-internal-flags
if (gArgs.IsArgSet("-debug")) {
// Special-case: if -debug=0/-nodebug is set, turn off debugging messages
const std::vector<std::string> categories = gArgs.GetArgs("-debug");
if (std::none_of(categories.begin(), categories.end(),
[](std::string cat){return cat == "0" || cat == "none";})) {
for (const auto& cat : categories) {
if (!LogInstance().EnableCategory(cat)) {
InitWarning(strprintf(_("Unsupported logging category %s=%s.").translated, "-debug", cat));
}
}
}
}
// Now remove the logging categories which were explicitly excluded
for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
if (!LogInstance().DisableCategory(cat)) {
InitWarning(strprintf(_("Unsupported logging category %s=%s.").translated, "-debugexclude", cat));
}
}
// Checkmempool and checkblockindex default to true in regtest mode
int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
if (ratio != 0) {
mempool.setSanityCheck(1.0 / ratio);
}
fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
if (!hashAssumeValid.IsNull())
LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
else
LogPrintf("Validating signatures for all blocks.\n");
if (gArgs.IsArgSet("-minimumchainwork")) {
const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", "");
if (!IsHexNumber(minChainWorkStr)) {
return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
}
nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
} else {
nMinimumChainWork = UintToArith256(chainparams.GetConsensus().nMinimumChainWork);
}
LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
if (nMinimumChainWork < UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
}
// mempool limits
int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
return InitError(strprintf(_("-maxmempool must be at least %d MB").translated, std::ceil(nMempoolSizeMin / 1000000.0)));
// incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
// and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
if (gArgs.IsArgSet("-incrementalrelayfee"))
{
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")).translated);
incrementalRelayFee = CFeeRate(n);
}
// block pruning; get the amount of disk space (in MiB) to allot for block & undo files
int64_t nPruneArg = gArgs.GetArg("-prune", 0);
if (nPruneArg < 0) {
return InitError(_("Prune cannot be configured with a negative value.").translated);
}
nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
if (nPruneArg == 1) { // manual pruning: -prune=1
LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
nPruneTarget = std::numeric_limits<uint64_t>::max();
fPruneMode = true;
} else if (nPruneTarget) {
if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number.").translated, MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
}
LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
fPruneMode = true;
}
nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
if (nConnectTimeout <= 0) {
nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
}
peer_connect_timeout = gArgs.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
if (peer_connect_timeout <= 0) {
return InitError("peertimeout cannot be configured with a negative value.");
}
if (gArgs.IsArgSet("-minrelaytxfee")) {
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")).translated);
}
// High fee check is done afterward in CWallet::CreateWalletFromFile()
::minRelayTxFee = CFeeRate(n);
} else if (incrementalRelayFee > ::minRelayTxFee) {
// Allow only setting incrementalRelayFee to control both
::minRelayTxFee = incrementalRelayFee;
LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
}
// Sanity check argument for min fee for including tx in block
// TODO: Harmonize which arguments need sanity checking and where that happens
if (gArgs.IsArgSet("-blockmintxfee"))
{
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")).translated);
}
// Feerate used to define dust. Shouldn't be changed lightly as old
// implementations may inadvertently create non-standard transactions
if (gArgs.IsArgSet("-dustrelayfee"))
{
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n))
return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")).translated);
dustRelayFee = CFeeRate(n);
}
fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
if (!chainparams.IsTestChain() && !fRequireStandard) {
return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
}
nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
if (!g_wallet_init_interface.ParameterInteraction()) return false;
fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
// Option to startup with mocktime set (used for regression testing):
SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
return InitError("rpcserialversion must be non-negative.");
if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
return InitError("unknown rpcserialversion requested.");
nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
if (gArgs.IsArgSet("-opsenderheight")) {
// Allow overriding opsender block for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Op Sender block height may only be overridden on regtest.");
}
int opsenderBlock = gArgs.GetArg("-opsenderheight", 0);
if(opsenderBlock >= 0)
{
UpdateOpSenderBlockHeight(opsenderBlock);
LogPrintf("Activate Op Sender at block height %d\n.", opsenderBlock);
}
}
if (gArgs.IsArgSet("-btcecrecoverheight")) {
// Allow overriding btc_ecrecover block for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Btc_ecrecover block height may only be overridden on regtest.");
}
int btcEcrecoverBlock = gArgs.GetArg("-btcecrecoverheight", 0);
if(btcEcrecoverBlock >= 0)
{
UpdateBtcEcrecoverBlockHeight(btcEcrecoverBlock);
LogPrintf("Activate btc_ecrecover at block height %d\n.", btcEcrecoverBlock);
}
}
if (gArgs.IsArgSet("-constantinopleheight")) {
// Allow overriding constantinople block for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Constantinople block height may only be overridden on regtest.");
}
int constantinopleBlock = gArgs.GetArg("-constantinopleheight", 0);
if(constantinopleBlock >= 0)
{
UpdateConstantinopleBlockHeight(constantinopleBlock);
LogPrintf("Activate constantinople at block height %d\n.", constantinopleBlock);
}
}
if (gArgs.IsArgSet("-difficultychangeheight")) {
// Allow overriding difficulty change block for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Difficulty change block height may only be overridden on regtest.");
}
int difficultyChangeBlock = gArgs.GetArg("-difficultychangeheight", 0);
if(difficultyChangeBlock >= 0)
{
UpdateDifficultyChangeBlockHeight(difficultyChangeBlock);
LogPrintf("Activate difficulty change at block height %d\n.", difficultyChangeBlock);
}
}
if (gArgs.IsArgSet("-offlinestakingheight")) {
// Allow overriding offline staking block for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Offline staking block height may only be overridden on regtest.");
}
int offlineStakingBlock = gArgs.GetArg("-offlinestakingheight", 0);
if(offlineStakingBlock >= 0)
{
UpdateOfflineStakingBlockHeight(offlineStakingBlock);
LogPrintf("Activate offline staking at block height %d\n.", offlineStakingBlock);
}
}
if (gArgs.IsArgSet("-delegationsaddress")) {
// Allow overriding delegations address for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("delegations address may only be overridden on regtest.");
}
std::string delegationsAddress = gArgs.GetArg("-delegationsaddress", std::string());
if(IsHex(delegationsAddress))
{
UpdateDelegationsAddress(uint160(ParseHex(delegationsAddress)));
LogPrintf("Activate delegations address %s\n.", delegationsAddress);
}
}
if (gArgs.IsArgSet("-lastmposheight")) {
// Allow overriding last MPoS block for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Last MPoS block height may only be overridden on regtest.");
}
int lastMPosBlockHeight = gArgs.GetArg("-lastmposheight", 0);
if(lastMPosBlockHeight >= 0)
{
UpdateLastMPoSBlockHeight(lastMPosBlockHeight);
LogPrintf("Set last MPoS block height %d\n.", lastMPosBlockHeight);
}
}
if (gArgs.IsArgSet("-reduceblocktimeheight")) {
// Allow overriding short block time block height for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Short block time height may only be overridden on regtest.");
}
int reduceblocktimeheight = gArgs.GetArg("-reduceblocktimeheight", 0);
if(reduceblocktimeheight >= 0)
{
UpdateReduceBlocktimeHeight(reduceblocktimeheight);
LogPrintf("Activate short block time at block height %d\n.", reduceblocktimeheight);
}
}
if (gArgs.IsArgSet("-powallowmindifficultyblocks")) {
// Allow overriding pow allow min difficulty blocks parameter for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Pow allow min difficulty blocks parameter may only be overridden on regtest.");
}
bool powallowmindifficultyblocks = gArgs.GetBoolArg("-powallowmindifficultyblocks", 1);
UpdatePowAllowMinDifficultyBlocks(powallowmindifficultyblocks);
LogPrintf("Use given value for pow allow min difficulty blocks parameter %d\n.", powallowmindifficultyblocks);
}
if (gArgs.IsArgSet("-pownoretargeting")) {
// Allow overriding pow no retargeting parameter for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Pow no retargeting parameter may only be overridden on regtest.");
}
bool pownoretargeting = gArgs.GetBoolArg("-pownoretargeting", 1);
UpdatePowNoRetargeting(pownoretargeting);
LogPrintf("Use given value for pow no retargeting parameter %d\n.", pownoretargeting);
}
if (gArgs.IsArgSet("-posnoretargeting")) {
// Allow overriding pos no retargeting parameter for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("PoS no retargeting parameter may only be overridden on regtest.");
}
bool posnoretargeting = gArgs.GetBoolArg("-posnoretargeting", 1);
UpdatePoSNoRetargeting(posnoretargeting);
LogPrintf("Use given value for pos no retargeting parameter %d\n.", posnoretargeting);
}
if (gArgs.IsArgSet("-muirglacierheight")) {
// Allow overriding EVM Muir Glacier block height for testing
if (!chainparams.MineBlocksOnDemand()) {
return InitError("Short EVM Muir Glacier height may only be overridden on regtest.");
}
int muirglacierheight = gArgs.GetArg("-muirglacierheight", 0);
if(muirglacierheight >= 0)
{
UpdateMuirGlacierHeight(muirglacierheight);
LogPrintf("Activate EVM Muir Glacier at block height %d\n.", muirglacierheight);
}
}
if(gArgs.IsArgSet("-stakingallowlist") && gArgs.IsArgSet("-stakingexcludelist"))
{
return InitError("Either -stakingallowlist or -stakingexcludelist parameter can be specified to the staker, not both.");
}
// Check allow list
for (const std::string& strAddress : gArgs.GetArgs("-stakingallowlist"))
{
CTxDestination dest = DecodeDestination(strAddress);
if(!boost::get<PKHash>(&dest))
return InitError(strprintf("-stakingallowlist, address %s does not refer to public key hash", strAddress));
}
// Check exclude list
for (const std::string& strAddress : gArgs.GetArgs("-stakingexcludelist"))
{
CTxDestination dest = DecodeDestination(strAddress);
if(!boost::get<PKHash>(&dest))
return InitError(strprintf("-stakingexcludelist, address %s does not refer to public key hash", strAddress));
}
return true;
}
static bool LockDataDirectory(bool probeOnly, bool try_lock = true)
{
// Make sure only a single Bitcoin process is using the data directory.
fs::path datadir = GetDataDir();
if (!DirIsWritable(datadir)) {
return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions.").translated, datadir.string()));
}
if (!LockDirectory(datadir, ".lock", probeOnly, try_lock)) {
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.").translated, datadir.string(), PACKAGE_NAME));
}
return true;
}
bool AppInitSanityChecks()
{
// ********************************************************* Step 4: sanity checks
// Initialize elliptic curve code
std::string sha256_algo = SHA256AutoDetect();
LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
RandomInit();
ECC_Start();
globalVerifyHandle.reset(new ECCVerifyHandle());
// Sanity check
if (!InitSanityCheck())
return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down.").translated, PACKAGE_NAME));
// Probe the data directory lock to give an early error message, if possible
// We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
// and a fork will cause weird behavior to it.
return LockDataDirectory(true);
}
bool AppInitLockDataDirectory()
{
// After daemonization get the data directory lock again and hold on to it until exit
// This creates a slight window for a race condition to happen, however this condition is harmless: it
// will at most make us exit without printing a message to console.
if (!LockDataDirectory(false)) {
// Detailed error printed inside LockDataDirectory
return false;
}
return true;
}
bool AppInitMain(NodeContext& node)
{
const CChainParams& chainparams = Params();
// ********************************************************* Step 4a: application initialization
if (!CreatePidFile()) {
// Detailed error printed inside CreatePidFile().
return false;
}
if (LogInstance().m_print_to_file) {
if (gArgs.GetBoolArg("-shrinkdebugfile", LogInstance().DefaultShrinkDebugFile())) {
// Do this first since it both loads a bunch of debug.log into memory,
// and because this needs to happen before any other debug.log printing
LogInstance().ShrinkDebugFile();
}
}
if (!LogInstance().StartLogging()) {
return InitError(strprintf("Could not open debug log file %s",
LogInstance().m_file_path.string()));
}
////////////////////////////////////////////////////////////////////// // yupost
dev::g_logPost(std::string("\n\n\n\n\n\n\n\n\n\n"), NULL);
//////////////////////////////////////////////////////////////////////
if (!LogInstance().m_log_timestamps)
LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
LogPrintf("Using data directory %s\n", GetDataDir().string());
// Only log conf file usage message if conf file actually exists.
fs::path config_file_path = GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
if (fs::exists(config_file_path)) {
LogPrintf("Config file: %s\n", config_file_path.string());
} else if (gArgs.IsArgSet("-conf")) {
// Warn if no conf file exists at path provided by user
InitWarning(strprintf(_("The specified config file %s does not exist\n").translated, config_file_path.string()));
} else {
// Not categorizing as "Warning" because it's the default behavior
LogPrintf("Config file: %s (not found, skipping)\n", config_file_path.string());
}
// Log the config arguments to debug.log
gArgs.LogArgs();
LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
// Warn about relative -datadir path.
if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) {
LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
"current working directory '%s'. This is fragile, because if bitcoin is started in the future "
"from a different location, it will be unable to locate the current data files. There could "
"also be data loss if bitcoin is started while in a temporary directory.\n",
gArgs.GetArg("-datadir", ""), fs::current_path().string());
}
if(gArgs.GetBoolArg("-deleteblockchaindata", false))
{
DeleteBlockChainData();
}
InitSignatureCache();
InitScriptExecutionCache();
int script_threads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
if (script_threads <= 0) {
// -par=0 means autodetect (number of cores - 1 script threads)
// -par=-n means "leave n cores free" (number of cores - n - 1 script threads)
script_threads += GetNumCores();
}
// Subtract 1 because the main thread counts towards the par threads
script_threads = std::max(script_threads - 1, 0);
// Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
LogPrintf("Script verification uses %d additional threads\n", script_threads);
if (script_threads >= 1) {
g_parallel_script_checks = true;
for (int i = 0; i < script_threads; ++i) {
threadGroup.create_thread([i]() { return ThreadScriptCheck(i); });
}
}
assert(!node.scheduler);
node.scheduler = MakeUnique<CScheduler>();
// Start the lightweight task scheduler thread
CScheduler::Function serviceLoop = [&node]{ node.scheduler->serviceQueue(); };
threadGroup.create_thread(std::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
// Gather some entropy once per minute.
node.scheduler->scheduleEvery([]{
RandAddPeriodic();
}, std::chrono::minutes{1});
GetMainSignals().RegisterBackgroundSignalScheduler(*node.scheduler);
// Create client interfaces for wallets that are supposed to be loaded
// according to -wallet and -disablewallet options. This only constructs
// the interfaces, it doesn't load wallet data. Wallets actually get loaded
// when load() and start() interface methods are called below.
g_wallet_init_interface.Construct(node);
/* Register RPC commands regardless of -server setting so they will be
* available in the GUI RPC console even if external calls are disabled.
*/
RegisterAllCoreRPCCommands(tableRPC);
for (const auto& client : node.chain_clients) {
client->registerRpcs();
}
g_rpc_node = &node;
#if ENABLE_ZMQ
RegisterZMQRPCCommands(tableRPC);
#endif
/* Start the RPC server already. It will be started in "warmup" mode
* and not really process calls already (but it will signify connections
* that the server is there and will be ready later). Warmup mode will
* be disabled when initialisation is finished.
*/
if (gArgs.GetBoolArg("-server", false))
{
uiInterface.InitMessage_connect(SetRPCWarmupStatus);
if (!AppInitServers())
return InitError(_("Unable to start HTTP server. See debug log for details.").translated);
}
// ********************************************************* Step 5: verify wallet database integrity
for (const auto& client : node.chain_clients) {
if (!client->verify()) {
return false;
}
}
// ********************************************************* Step 6: network initialization
// Note that we absolutely cannot open any actual connections
// until the very end ("start node") as the UTXO/block state
// is not yet setup and may end up being set up twice if we
// need to reindex later.
assert(!node.banman);
node.banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", &uiInterface, gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
assert(!node.connman);
node.connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
// Make mempool generally available in the node context. For example the connection manager, wallet, or RPC threads,
// which are all started after this, may use it from the node context.
assert(!node.mempool);
node.mempool = &::mempool;
node.peer_logic.reset(new PeerLogicValidation(node.connman.get(), node.banman.get(), *node.scheduler, *node.mempool));
RegisterValidationInterface(node.peer_logic.get());
#ifdef ENABLE_WALLET
CWallet::defaultConnman = node.connman.get();
#endif
// sanitize comments per BIP-0014, format user agent and check total size
std::vector<std::string> uacomments;
for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters.").translated, cmt));
uacomments.push_back(cmt);
}
strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.").translated,
strSubVersion.size(), MAX_SUBVERSION_LENGTH));
}
if (gArgs.IsArgSet("-onlynet")) {
std::set<enum Network> nets;
for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'").translated, snet));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetReachable(net, false);
}
}
// Check for host lookup allowed before parsing any network related parameters
fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
// -proxy sets a proxy for all outgoing network traffic
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
std::string proxyArg = gArgs.GetArg("-proxy", "");
SetReachable(NET_ONION, false);
if (proxyArg != "" && proxyArg != "0") {
CService proxyAddr;
if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'").translated, proxyArg));
}
proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'").translated, proxyArg));
SetProxy(NET_IPV4, addrProxy);
SetProxy(NET_IPV6, addrProxy);
SetProxy(NET_ONION, addrProxy);
SetNameProxy(addrProxy);
SetReachable(NET_ONION, true); // by default, -proxy sets onion as reachable, unless -noonion later
}
// -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
// -noonion (or -onion=0) disables connecting to .onion entirely
// An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
std::string onionArg = gArgs.GetArg("-onion", "");
if (onionArg != "") {
if (onionArg == "0") { // Handle -noonion/-onion=0
SetReachable(NET_ONION, false);
} else {
CService onionProxy;
if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'").translated, onionArg));
}
proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'").translated, onionArg));
SetProxy(NET_ONION, addrOnion);
SetReachable(NET_ONION, true);
}
}
// see Step 2: parameter interactions for more information about these
fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
fDiscover = gArgs.GetBoolArg("-discover", true);
g_relay_txes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
CService addrLocal;
if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
AddLocal(addrLocal, LOCAL_MANUAL);
else
return InitError(ResolveErrMsg("externalip", strAddr));
}
// Read asmap file if configured
if (gArgs.IsArgSet("-asmap")) {
fs::path asmap_path = fs::path(gArgs.GetArg("-asmap", ""));
if (asmap_path.empty()) {
asmap_path = DEFAULT_ASMAP_FILENAME;
}
if (!asmap_path.is_absolute()) {
asmap_path = GetDataDir() / asmap_path;
}
if (!fs::exists(asmap_path)) {
InitError(strprintf(_("Could not find asmap file %s").translated, asmap_path));
return false;
}
std::vector<bool> asmap = CAddrMan::DecodeAsmap(asmap_path);
if (asmap.size() == 0) {
InitError(strprintf(_("Could not parse asmap file %s").translated, asmap_path));
return false;
}
const uint256 asmap_version = SerializeHash(asmap);
node.connman->SetAsmap(std::move(asmap));
LogPrintf("Using asmap version %s for IP bucketing\n", asmap_version.ToString());
} else {
LogPrintf("Using /16 prefix for IP bucketing\n");
}
#if ENABLE_ZMQ
g_zmq_notification_interface = CZMQNotificationInterface::Create();
if (g_zmq_notification_interface) {
RegisterValidationInterface(g_zmq_notification_interface);
}
#endif
uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
if (gArgs.IsArgSet("-maxuploadtarget")) {
nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
}
// ********************************************************* Step 7: load block chain
fReindex = gArgs.GetBoolArg("-reindex", false);
bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
// cache size calculations
int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
if (gArgs.GetBoolArg("-addrindex", DEFAULT_ADDRINDEX)) {
// enable 3/4 of the cache if addressindex and/or spentindex is enabled
nBlockTreeDBCache = nTotalCache * 3 / 4;
}
nTotalCache -= nBlockTreeDBCache;
int64_t nTxIndexCache = std::min(nTotalCache / 8, gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
nTotalCache -= nTxIndexCache;
int64_t filter_index_cache = 0;
if (!g_enabled_filter_types.empty()) {
size_t n_indexes = g_enabled_filter_types.size();
int64_t max_cache = std::min(nTotalCache / 8, max_filter_index_cache << 20);
filter_index_cache = max_cache / n_indexes;
nTotalCache -= filter_index_cache * n_indexes;
}
int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
nTotalCache -= nCoinDBCache;
nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
LogPrintf("Cache configuration:\n");
LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
LogPrintf("* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
}
for (BlockFilterType filter_type : g_enabled_filter_types) {
LogPrintf("* Using %.1f MiB for %s block filter index database\n",
filter_index_cache * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type));
}
LogPrintf("* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
bool fLoaded = false;
while (!fLoaded && !ShutdownRequested()) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index...").translated);
do {
const int64_t load_block_index_start_time = GetTimeMillis();
bool is_coinsview_empty;
try {
LOCK(cs_main);
// This statement makes ::ChainstateActive() usable.
g_chainstate = MakeUnique<CChainState>();
UnloadBlockIndex();
// new CBlockTreeDB tries to delete the existing file, which
// fails if it's still open from the previous loop. Close it first:
pblocktree.reset();
pstorageresult.reset();
globalState.reset();
globalSealEngine.reset();
pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
if (fReset) {
pblocktree->WriteReindexing(true);
//If we're reindexing in prune mode, wipe away unusable block files and all undo data files
if (fPruneMode)
CleanupBlockRevFiles();
}
if (ShutdownRequested()) break;
// LoadBlockIndex will load fHavePruned if we've ever removed a
// block file from disk.
// Note that it also sets fReindex based on the disk flag!
// From here on out fReindex and fReset mean something different!
if (!LoadBlockIndex(chainparams)) {
if (ShutdownRequested()) break;
strLoadError = _("Error loading block database").translated;
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!::BlockIndex().empty() &&
!LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?").translated);
}
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
// in the past, but is now trying to run unpruned.
if (fHavePruned && !fPruneMode) {
strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain").translated;
break;
}
// At this point blocktree args are consistent with what's on disk.
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
// (otherwise we use the one already on disk).
// This is called again in ThreadImport after the reindex completes.
if (!fReindex && !LoadGenesisBlock(chainparams)) {
strLoadError = _("Error initializing block database").translated;
break;
}
// At this point we're either in reindex or we've loaded a useful
// block tree into BlockIndex()!
::ChainstateActive().InitCoinsDB(
/* cache_size_bytes */ nCoinDBCache,
/* in_memory */ false,
/* should_wipe */ fReset || fReindexChainState);
::ChainstateActive().CoinsErrorCatcher().AddReadErrCallback([]() {
uiInterface.ThreadSafeMessageBox(
_("Error reading from database, shutting down.").translated,
"", CClientUIInterface::MSG_ERROR);
});
// If necessary, upgrade from older database format.
// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!::ChainstateActive().CoinsDB().Upgrade()) {
strLoadError = _("Error upgrading chainstate database").translated;
break;
}
// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!::ChainstateActive().ReplayBlocks(chainparams)) {
strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.").translated;
break;
}
// The on-disk coinsdb is now in a good state, create the cache
::ChainstateActive().InitCoinsCache();
assert(::ChainstateActive().CanFlushToDisk());
is_coinsview_empty = fReset || fReindexChainState ||
::ChainstateActive().CoinsTip().GetBestBlock().IsNull();
if (!is_coinsview_empty) {
// LoadChainTip initializes the chain based on CoinsTip()'s best block
if (!::ChainstateActive().LoadChainTip(chainparams)) {
strLoadError = _("Error initializing block database").translated;
break;
}
assert(::ChainActive().Tip() != nullptr);
}
} catch (const std::exception& e) {
LogPrintf("%s\n", e.what());
strLoadError = _("Error opening block database").translated;
break;
}
/////////////////////////////////////////////////////////// yupost
if((gArgs.IsArgSet("-dgpstorage") && gArgs.IsArgSet("-dgpevm")) || (!gArgs.IsArgSet("-dgpstorage") && gArgs.IsArgSet("-dgpevm")) ||
(!gArgs.IsArgSet("-dgpstorage") && !gArgs.IsArgSet("-dgpevm"))){
fGettingValuesDGP = true;
} else {
fGettingValuesDGP = false;
}
dev::eth::NoProof::init();
fs::path yupostStateDir = GetDataDir() / "stateYuPost";
bool fStatus = fs::exists(yupostStateDir);
const std::string dirYuPost(yupostStateDir.string());
const dev::h256 hashDB(dev::sha3(dev::rlp("")));
dev::eth::BaseState existsYuPoststate = fStatus ? dev::eth::BaseState::PreExisting : dev::eth::BaseState::Empty;
globalState = std::unique_ptr<YuPostState>(new YuPostState(dev::u256(0), YuPostState::openDB(dirYuPost, hashDB, dev::WithExisting::Trust), dirYuPost, existsYuPoststate));
dev::eth::ChainParams cp(chainparams.EVMGenesisInfo());
globalSealEngine = std::unique_ptr<dev::eth::SealEngineFace>(cp.createSealEngine());
pstorageresult.reset(new StorageResults(yupostStateDir.string()));
if (fReset) {
pstorageresult->wipeResults();
}
if(::ChainActive().Tip() != nullptr){
globalState->setRoot(uintToh256(::ChainActive().Tip()->hashStateRoot));
globalState->setRootUTXO(uintToh256(::ChainActive().Tip()->hashUTXORoot));
} else {
globalState->setRoot(dev::sha3(dev::rlp("")));
globalState->setRootUTXO(uintToh256(chainparams.GenesisBlock().hashUTXORoot));
globalState->populateFrom(cp.genesisState);
}
globalState->db().commit();
globalState->dbUtxo().commit();
fRecordLogOpcodes = gArgs.IsArgSet("-record-log-opcodes");
fIsVMlogFile = fs::exists(GetDataDir() / "vmExecLogs.json");
///////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////// // yupost
if (fAddressIndex != gArgs.GetBoolArg("-addrindex", DEFAULT_ADDRINDEX)) {
strLoadError = _("You need to rebuild the database using -reindex to change -addrindex").translated;
break;
}
///////////////////////////////////////////////////////////////
// Check for changed -logevents state
if (fLogEvents != gArgs.GetBoolArg("-logevents", DEFAULT_LOGEVENTS) && !fLogEvents) {
strLoadError = _("You need to rebuild the database using -reindex to enable -logevents").translated;
break;
}
if (!gArgs.GetBoolArg("-logevents", DEFAULT_LOGEVENTS))
{
pstorageresult->wipeResults();
pblocktree->WipeHeightIndex();
fLogEvents = false;
pblocktree->WriteFlag("logevents", fLogEvents);
}
if (!fReset) {
// Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
// It both disconnects blocks based on ::ChainActive(), and drops block data in
// BlockIndex() based on lack of available witness data.
uiInterface.InitMessage(_("Rewinding blocks...").translated);
if (!RewindBlockIndex(chainparams)) {
strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain").translated;
break;
}
}
try {
LOCK(cs_main);
YuPostDGP yupostDGP(globalState.get(), fGettingValuesDGP);
globalSealEngine->setYuPostSchedule(yupostDGP.getGasSchedule(::ChainActive().Height() + (::ChainActive().Height()+1 >= chainparams.GetConsensus().QIP7Height ? 0 : 1) ));
if (!is_coinsview_empty) {
uiInterface.InitMessage(_("Verifying blocks...").translated);
if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
MIN_BLOCKS_TO_KEEP);
}
CBlockIndex* tip = ::ChainActive().Tip();
RPCNotifyBlockChange(true, tip);
if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
strLoadError = _("The block database contains a block which appears to be from the future. "
"This may be due to your computer's date and time being set incorrectly. "
"Only rebuild the block database if you are sure that your computer's date and time are correct").translated;
break;
}
if (!CVerifyDB().VerifyDB(chainparams, &::ChainstateActive().CoinsDB(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
strLoadError = _("Corrupted block database detected").translated;
break;
}
}
} catch (const std::exception& e) {
LogPrintf("%s\n", e.what());
strLoadError = _("Error opening block database").translated;
break;
}
fLoaded = true;
LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
} while(false);
if (!fLoaded && !ShutdownRequested()) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeQuestion(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?").translated,
strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
AbortShutdown();
} else {
LogPrintf("Aborted block database rebuild. Exiting.\n");
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// As LoadBlockIndex can take several minutes, it's possible the user
// requested to kill the GUI during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (ShutdownRequested()) {
LogPrintf("Shutdown requested. Exiting.\n");
return false;
}
fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
// Allowed to fail as this file IS missing on first startup.
if (!est_filein.IsNull())
::feeEstimator.Read(est_filein);
fFeeEstimatesInitialized = true;
// ********************************************************* Step 8: start indexers
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
g_txindex = MakeUnique<TxIndex>(nTxIndexCache, false, fReindex);
g_txindex->Start();
}
for (const auto& filter_type : g_enabled_filter_types) {
InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex);
GetBlockFilterIndex(filter_type)->Start();
}
// ********************************************************* Step 9: load wallet
for (const auto& client : node.chain_clients) {
if (!client->load()) {
return false;
}
}
// ********************************************************* Step 10: data directory maintenance
// if pruning, unset the service bit and perform the initial blockstore prune
// after any wallet rescanning has taken place.
if (fPruneMode) {
LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
if (!fReindex) {
uiInterface.InitMessage(_("Pruning blockstore...").translated);
::ChainstateActive().PruneAndFlush();
}
}
if (chainparams.GetConsensus().SegwitHeight != std::numeric_limits<int>::max()) {
// Advertise witness capabilities.
// The option to not set NODE_WITNESS is only used in the tests and should be removed.
nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
}
// ********************************************************* Step 11: import blocks
if (!CheckDiskSpace(GetDataDir())) {
InitError(strprintf(_("Error: Disk space is low for %s").translated, GetDataDir()));
return false;
}
if (!CheckDiskSpace(GetBlocksDir())) {
InitError(strprintf(_("Error: Disk space is low for %s").translated, GetBlocksDir()));
return false;
}
// Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
// No locking, as this happens before any background thread is started.
boost::signals2::connection block_notify_genesis_wait_connection;
if (::ChainActive().Tip() == nullptr) {
block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(BlockNotifyGenesisWait);
} else {
fHaveGenesis = true;
}
#if HAVE_SYSTEM
if (gArgs.IsArgSet("-blocknotify"))
uiInterface.NotifyBlockTip_connect(BlockNotifyCallback);
#endif
std::vector<fs::path> vImportFiles;
for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(std::bind(&ThreadImport, vImportFiles));
if(gArgs.GetBoolArg("-cleanblockindex", DEFAULT_CLEANBLOCKINDEX))
threadGroup.create_thread(std::bind(&CleanBlockIndex));
// Wait for genesis block to be processed
{
WAIT_LOCK(g_genesis_wait_mutex, lock);
// We previously could hang here if StartShutdown() is called prior to
// ThreadImport getting started, so instead we just wait on a timer to
// check ShutdownRequested() regularly.
while (!fHaveGenesis && !ShutdownRequested()) {
g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
}
block_notify_genesis_wait_connection.disconnect();
}
if (ShutdownRequested()) {
return false;
}
// ********************************************************* Step 12: start node
int chain_active_height;
//// debug print
{
LOCK(cs_main);
LogPrintf("block tree size = %u\n", ::BlockIndex().size());
chain_active_height = ::ChainActive().Height();
}
LogPrintf("nBestHeight = %d\n", chain_active_height);
if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
StartTorControl();
Discover();
// Map ports with UPnP
if (gArgs.GetBoolArg("-upnp", DEFAULT_UPNP)) {
StartMapPort();
}
CConnman::Options connOptions;
connOptions.nLocalServices = nLocalServices;
connOptions.nMaxConnections = nMaxConnections;
connOptions.m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, connOptions.nMaxConnections);
connOptions.m_max_outbound_block_relay = std::min(MAX_BLOCKS_ONLY_CONNECTIONS, connOptions.nMaxConnections-connOptions.m_max_outbound_full_relay);
connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
connOptions.nMaxFeeler = 1;
connOptions.nBestHeight = chain_active_height;
connOptions.uiInterface = &uiInterface;
connOptions.m_banman = node.banman.get();
connOptions.m_msgproc = node.peer_logic.get();
connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
connOptions.m_added_nodes = gArgs.GetArgs("-addnode");
connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
connOptions.m_peer_connect_timeout = peer_connect_timeout;
for (const std::string& strBind : gArgs.GetArgs("-bind")) {
CService addrBind;
if (!Lookup(strBind, addrBind, GetListenPort(), false)) {
return InitError(ResolveErrMsg("bind", strBind));
}
connOptions.vBinds.push_back(addrBind);
}
for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
NetWhitebindPermissions whitebind;
std::string error;
if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
connOptions.vWhiteBinds.push_back(whitebind);
}
for (const auto& net : gArgs.GetArgs("-whitelist")) {
NetWhitelistPermissions subnet;
std::string error;
if (!NetWhitelistPermissions::TryParse(net, subnet, error)) return InitError(error);
connOptions.vWhitelistedRange.push_back(subnet);
}
connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
// Initiate outbound connections unless connect=0
connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect");
if (!connOptions.m_use_addrman_outgoing) {
const auto connect = gArgs.GetArgs("-connect");
if (connect.size() != 1 || connect[0] != "0") {
connOptions.m_specified_outgoing = connect;
}
}
if (!node.connman->Start(*node.scheduler, connOptions)) {
return false;
}
// ********************************************************* Step 13: finished
SetRPCWarmupFinished();
uiInterface.InitMessage(_("Done loading").translated);
for (const auto& client : node.chain_clients) {
client->start(*node.scheduler);
}
BanMan* banman = node.banman.get();
node.scheduler->scheduleEvery([banman]{
banman->DumpBanlist();
}, DUMP_BANS_INTERVAL);
return true;
}
void UnlockDataDirectory()
{
// Unlock
LockDataDirectory(true, false);
}
|
#include "linesfadepopup.h"
// Tnz6 includes
#include "tapp.h"
#include "menubarcommandids.h"
#include "cellselection.h"
#include "filmstripselection.h"
#include "imageviewer.h"
// TnzLib includes
#include "toonz/txshcell.h"
#include "toonz/txsheethandle.h"
#include "toonz/tframehandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/txshleveltypes.h"
// TnzQt includes
#include "toonzqt/menubarcommand.h"
#include "toonzqt/planeviewer.h"
#include "toonzqt/colorfield.h"
#include "toonzqt/tselectionhandle.h"
#include "toonzqt/icongenerator.h"
#include "toonzqt/intfield.h"
// TnzCore includes
#include "tpixelgr.h"
#include "trasterimage.h"
#include "tundo.h"
#include "timagecache.h"
// Qt includes
#include <QSplitter>
#include <QScrollArea>
#include <QGridLayout>
#include <QPushButton>
#include <QLabel>
#include <QMainWindow>
using namespace DVGui;
//**************************************************************************
// Local namespace stuff
//**************************************************************************
namespace {
void onChange(TRaster32P &rasIn, const TRaster32P &rasOut, TPixel32 col,
int _intensity) {
double intensity = _intensity / 100.0;
col = premultiply(col);
int j;
rasIn->lock();
rasOut->lock();
for (j = 0; j < rasIn->getLy(); j++) {
TPixel32 *pixIn = rasIn->pixels(j);
TPixel32 *pixOut = rasOut->pixels(j);
TPixel32 *endPixIn = pixIn + rasIn->getLx();
while (pixIn < endPixIn) {
double factor = pixIn->m / (double)255;
int val;
val = troundp(pixIn->r + intensity * (col.r * factor - pixIn->r));
pixOut->r = (val > 255) ? 255 : val;
val = troundp(pixIn->g + intensity * (col.g * factor - pixIn->g));
pixOut->g = (val > 255) ? 255 : val;
val = troundp(pixIn->b + intensity * (col.b * factor - pixIn->b));
pixOut->b = (val > 255) ? 255 : val;
val = troundp(pixIn->m + intensity * (col.m * factor - pixIn->m));
pixOut->m = (val > 255) ? 255 : val;
/* Fading matte here
pix->r=(UCHAR)(pix->r+intensity*(col.r-pix->r));
pix->g=(UCHAR)(pix->g+intensity*(col.g-pix->g));
pix->b=(UCHAR)(pix->b+intensity*(col.b-pix->b));
pix->m=(UCHAR)(pix->m+intensity*(col.m-pix->m));*/
++pixOut;
++pixIn;
}
}
rasIn->unlock();
rasOut->unlock();
}
} // namespace
//**************************************************************************
// BrightnessAndContrastPopup Swatch
//**************************************************************************
class LinesFadePopup::Swatch final : public PlaneViewer {
TRasterP m_ras;
public:
Swatch(QWidget *parent = 0) : PlaneViewer(parent) {
setBgColor(TPixel32::White, TPixel32::White);
}
TRasterP raster() const { return m_ras; }
TRasterP &raster() { return m_ras; }
void paintGL() override {
drawBackground();
if (m_ras) {
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// Note GL_ONE instead of GL_SRC_ALPHA: it's needed since the input
// image is supposedly premultiplied - and it works because the
// viewer's background is opaque.
// See tpixelutils.h's overPixT function for comparison.
pushGLWorldCoordinates();
draw(m_ras);
popGLCoordinates();
glDisable(GL_BLEND);
}
}
};
//**************************************************************************
// LinesFadePopup implementation
//**************************************************************************
LinesFadePopup::LinesFadePopup()
: Dialog(TApp::instance()->getMainWindow(), true, false, "LinesFade")
, m_startRas(0) {
setWindowTitle(tr("Color Fade"));
setLabelWidth(0);
setModal(false);
setTopMargin(0);
setTopSpacing(0);
beginVLayout();
QSplitter *splitter = new QSplitter(Qt::Vertical);
splitter->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,
QSizePolicy::MinimumExpanding));
addWidget(splitter);
endVLayout();
//------------------------- Top Layout --------------------------
QScrollArea *scrollArea = new QScrollArea(splitter);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea->setWidgetResizable(true);
splitter->addWidget(scrollArea);
splitter->setStretchFactor(0, 1);
QFrame *topWidget = new QFrame(scrollArea);
topWidget->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,
QSizePolicy::MinimumExpanding));
scrollArea->setWidget(topWidget);
QGridLayout *topLayout = new QGridLayout();
topWidget->setLayout(topLayout);
//------------------------- Parameters --------------------------
// Fade
QLabel *fadeLabel = new QLabel(tr("Fade:"));
topLayout->addWidget(fadeLabel, 0, 0, Qt::AlignRight | Qt::AlignVCenter);
m_linesColorField = new DVGui::ColorField(this, true, TPixel32::Black, 40);
m_linesColorField->setFixedHeight(40);
topLayout->addWidget(m_linesColorField, 0, 1);
// Intensity
QLabel *intensityLabel = new QLabel(tr("Intensity:"));
topLayout->addWidget(intensityLabel, 1, 0, Qt::AlignRight | Qt::AlignVCenter);
m_intensity = new IntField(this);
m_intensity->setValues(100, 0, 100);
topLayout->addWidget(m_intensity, 1, 1);
topLayout->setRowStretch(2, 1);
//--------------------------- Swatch ----------------------------
m_viewer = new Swatch(splitter);
m_viewer->setMinimumHeight(150);
m_viewer->setFocusPolicy(Qt::WheelFocus);
splitter->addWidget(m_viewer);
//--------------------------- Button ----------------------------
m_okBtn = new QPushButton(QString(tr("Apply")), this);
connect(m_okBtn, SIGNAL(clicked()), this, SLOT(apply()));
addButtonBarWidget(m_okBtn);
//------------------------ Connections --------------------------
TApp *app = TApp::instance();
bool ret = true;
ret = ret &&
connect(m_linesColorField, SIGNAL(colorChanged(const TPixel32 &, bool)),
this, SLOT(onLinesColorChanged(const TPixel32 &, bool)));
ret = ret && connect(m_intensity, SIGNAL(valueChanged(bool)), this,
SLOT(onIntensityChanged(bool)));
assert(ret);
m_viewer->resize(0, 350);
resize(600, 500);
}
//-----------------------------------------------------------------------------
void LinesFadePopup::setCurrentSampleRaster() {
TRaster32P sampleRas;
m_startRas = TRaster32P();
TSelection *selection =
TApp::instance()->getCurrentSelection()->getSelection();
TCellSelection *cellSelection = dynamic_cast<TCellSelection *>(selection);
TFilmstripSelection *filmstripSelection =
dynamic_cast<TFilmstripSelection *>(selection);
if (cellSelection) {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TXshCell cell = xsh->getCell(app->getCurrentFrame()->getFrameIndex(),
app->getCurrentColumn()->getColumnIndex());
TRasterImageP rasImage = cell.getImage(true);
if (rasImage && rasImage->getRaster())
sampleRas = rasImage->getRaster()->clone();
} else if (filmstripSelection) {
TApp *app = TApp::instance();
TXshSimpleLevel *simpleLevel = app->getCurrentLevel()->getSimpleLevel();
if (simpleLevel) {
TRasterImageP rasImage = (TRasterImageP)simpleLevel->getFrame(
app->getCurrentFrame()->getFid(), true);
if (rasImage && rasImage->getRaster())
sampleRas = rasImage->getRaster()->clone();
}
}
if (!sampleRas) {
m_viewer->raster() = TRasterP();
m_viewer->update();
m_okBtn->setEnabled(false);
return;
}
m_okBtn->setEnabled(true);
m_startRas = sampleRas->clone();
onChange(m_startRas, sampleRas, m_linesColorField->getColor(),
m_intensity->getValue());
m_viewer->raster() = sampleRas;
m_viewer->update();
}
//-----------------------------------------------------------------------------
void LinesFadePopup::showEvent(QShowEvent *se) {
TApp *app = TApp::instance();
bool ret = true;
ret = ret && connect(app->getCurrentFrame(), SIGNAL(frameTypeChanged()), this,
SLOT(setCurrentSampleRaster()));
ret = ret && connect(app->getCurrentFrame(), SIGNAL(frameSwitched()), this,
SLOT(setCurrentSampleRaster()));
ret = ret && connect(app->getCurrentColumn(), SIGNAL(columnIndexSwitched()),
this, SLOT(setCurrentSampleRaster()));
assert(ret);
setCurrentSampleRaster();
}
//-----------------------------------------------------------------------------
void LinesFadePopup::hideEvent(QHideEvent *he) {
TApp *app = TApp::instance();
disconnect(app->getCurrentFrame(), SIGNAL(frameTypeChanged()), this,
SLOT(setCurrentSampleRaster()));
disconnect(app->getCurrentFrame(), SIGNAL(frameSwitched()), this,
SLOT(setCurrentSampleRaster()));
disconnect(app->getCurrentColumn(), SIGNAL(columnIndexSwitched()), this,
SLOT(setCurrentSampleRaster()));
Dialog::hideEvent(he);
m_viewer->raster() = TRasterP();
m_startRas = TRaster32P();
}
//-----------------------------------------------------------------------------
class TLineFadeUndo final : public TUndo {
int m_r, m_c;
TPixel32 m_color;
int m_intensity;
QString m_rasId;
int m_rasSize;
public:
TLineFadeUndo(const TPixel32 &color, int intensity, int r, int c,
TRaster32P ras)
: m_r(r)
, m_c(c)
, m_rasId()
, m_color(color)
, m_intensity(intensity)
, m_rasSize(ras->getLx() * ras->getLy() * ras->getPixelSize()) {
m_rasId = QString("LineFadeUndo") + QString::number((uintptr_t)this);
TImageCache::instance()->add(m_rasId, TRasterImageP(ras));
}
~TLineFadeUndo() { TImageCache::instance()->remove(m_rasId); }
void undo() const override {
TXsheet *xsheet = TApp::instance()->getCurrentXsheet()->getXsheet();
TXshCell cell = xsheet->getCell(m_r, m_c);
TRasterImageP rasImage = (TRasterImageP)cell.getImage(true);
if (!rasImage) return;
rasImage->setRaster(
((TRasterImageP)TImageCache::instance()->get(m_rasId, true))
->getRaster()
->clone());
TXshSimpleLevel *simpleLevel = cell.getSimpleLevel();
assert(simpleLevel);
simpleLevel->touchFrame(cell.getFrameId());
simpleLevel->setDirtyFlag(false);
IconGenerator::instance()->invalidate(simpleLevel, cell.getFrameId());
if (m_isLastInBlock) {
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
}
}
void redo() const override {
TXsheet *xsheet = TApp::instance()->getCurrentXsheet()->getXsheet();
TXshCell cell = xsheet->getCell(m_r, m_c);
TRasterImageP rasImage = (TRasterImageP)cell.getImage(true);
if (!rasImage) return;
TRaster32P ras = rasImage->getRaster();
if (!ras) return;
onChange(ras, ras, m_color, m_intensity);
TXshSimpleLevel *simpleLevel = cell.getSimpleLevel();
assert(simpleLevel);
simpleLevel->touchFrame(cell.getFrameId());
simpleLevel->setDirtyFlag(false);
IconGenerator::instance()->invalidate(simpleLevel, cell.getFrameId());
if (m_isLastInBlock) {
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
}
}
int getSize() const override { return sizeof(*this) + m_rasSize; }
};
//-----------------------------------------------------------------------------
void LinesFadePopup::apply() {
TCellSelection *cellSelection =
dynamic_cast<TCellSelection *>(TSelection::getCurrent());
TPixel32 color = m_linesColorField->getColor();
int intensity = m_intensity->getValue();
if (cellSelection) {
std::set<TRasterImage *> images;
int r0, c0, r1, c1;
cellSelection->getSelectedCells(r0, c0, r1, c1);
TXsheet *xsheet = TApp::instance()->getCurrentXsheet()->getXsheet();
bool oneImageChanged = false;
int c, r;
TUndoManager::manager()->beginBlock();
for (c = c0; c <= c1; c++)
for (r = r0; r <= r1; r++) {
TXshCell cell = xsheet->getCell(r, c);
TRasterImageP rasImage = (TRasterImageP)cell.getImage(true);
if (!rasImage) continue;
if (images.find(rasImage.getPointer()) != images.end()) continue;
TRaster32P ras = rasImage->getRaster();
if (!ras) continue;
images.insert(rasImage.getPointer());
TUndoManager::manager()->add(
new TLineFadeUndo(color, intensity, r, c, ras->clone()));
oneImageChanged = true;
onChange(ras, ras, color, intensity);
TXshSimpleLevel *simpleLevel = cell.getSimpleLevel();
assert(simpleLevel);
simpleLevel->touchFrame(cell.getFrameId());
simpleLevel->setDirtyFlag(true);
IconGenerator::instance()->invalidate(simpleLevel, cell.getFrameId());
}
TUndoManager::manager()->endBlock();
images.clear();
if (oneImageChanged) {
close();
return;
}
}
TFilmstripSelection *filmstripSelection =
dynamic_cast<TFilmstripSelection *>(TSelection::getCurrent());
if (filmstripSelection) {
TXshSimpleLevel *simpleLevel =
TApp::instance()->getCurrentLevel()->getSimpleLevel();
if (simpleLevel) {
std::set<TFrameId> fids = filmstripSelection->getSelectedFids();
bool oneImageChanged = false;
for (auto const &fid : fids) {
TRasterImageP rasImage =
(TRasterImageP)simpleLevel->getFrame(fid, true);
;
if (!rasImage) continue;
TRaster32P ras = rasImage->getRaster();
if (!ras) continue;
oneImageChanged = true;
onChange(ras, ras, color, intensity);
simpleLevel->touchFrame(fid);
simpleLevel->setDirtyFlag(true);
IconGenerator::instance()->invalidate(simpleLevel, fid);
}
if (oneImageChanged) {
close();
return;
}
}
}
DVGui::error(QObject::tr("The current selection is invalid."));
return;
}
//-----------------------------------------------------------------------------
void LinesFadePopup::onLinesColorChanged(const TPixel32 &color,
bool isDragging) {
if (!m_startRas || !m_viewer->raster()) return;
onChange(m_startRas, m_viewer->raster(), color, m_intensity->getValue());
m_viewer->update();
}
//-----------------------------------------------------------------------------
void LinesFadePopup::onIntensityChanged(bool isDragging) {
if (!m_startRas || !m_viewer->raster()) return;
onChange(m_startRas, m_viewer->raster(), m_linesColorField->getColor(),
m_intensity->getValue());
m_viewer->update();
}
//-----------------------------------------------------------------------------
OpenPopupCommandHandler<LinesFadePopup> openLinesFadePopup(MI_LinesFade);
|
//Illustration of Viola-Jones object detection
// Andreas Unterweger, 2017-2019
//This code is licensed under the 3-Clause BSD License. See LICENSE file for details.
#include <iostream>
#include <vector>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/imgproc.hpp>
#include "colors.hpp"
using namespace std;
using namespace cv;
using namespace imgutils;
static bool InitClassifier(CascadeClassifier &classifier)
{
constexpr auto classifier_path = "/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_alt.xml";
const bool successful = classifier.load(classifier_path);
return successful;
}
static void FindFaces(const Mat &image, /*const*/ CascadeClassifier &classifier, vector<Rect> &faces) //TODO: detectMultiScale should be const, but is not
{
classifier.detectMultiScale(image, faces);
}
static void HighlightFaces(Mat &image, vector<Rect> faces)
{
const auto face_color = Red;
for (const auto &face : faces)
rectangle(image, face, face_color);
}
static Mat GetColorImage(const Mat &image)
{
Mat color_image;
cvtColor(image, color_image, COLOR_GRAY2BGRA);
return color_image;
}
static void ShowImage(const Mat &image, /*const*/ CascadeClassifier &classifier)
{
constexpr auto window_name = "Image with objects to detect";
namedWindow(window_name, WINDOW_GUI_NORMAL | WINDOW_AUTOSIZE);
moveWindow(window_name, 0, 0);
vector<Rect> faces;
FindFaces(image, classifier, faces);
Mat image_with_faces = GetColorImage(image);
HighlightFaces(image_with_faces, faces);
imshow(window_name, image_with_faces);
}
int main(const int argc, const char * const argv[])
{
if (argc < 2)
{
cout << "Illustrates object detection on multiple input frames with the object detector by Viola and Jones." << endl;
cout << "Usage: " << argv[0] << " <input image 1> [<input image 2> ... [<input image n>]]" << endl;
return 1;
}
CascadeClassifier classifier;
if (!InitClassifier(classifier))
{
cerr << "Could not initialize cascade classifier" << endl;
return 2;
}
vector<const char*> image_filenames(argv + 1, argv + argc); //Start from first actual parameter (ignore program name)
for (const auto &image_filename : image_filenames)
{
Mat image = imread(image_filename, IMREAD_GRAYSCALE);
if (image.empty())
{
cerr << "Could not read input image '" << image_filename << "'" << endl;
return 3;
}
ShowImage(image, classifier);
waitKey(0);
}
return 0;
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/serial/serial_device_enumerator_linux.h"
#include <stdint.h>
#include <memory>
#include <utility>
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
namespace device {
namespace {
const char kSerialSubsystem[] = "tty";
const char kHostPathKey[] = "DEVNAME";
const char kHostBusKey[] = "ID_BUS";
const char kVendorIDKey[] = "ID_VENDOR_ID";
const char kProductIDKey[] = "ID_MODEL_ID";
const char kProductNameKey[] = "ID_MODEL";
} // namespace
// static
std::unique_ptr<SerialDeviceEnumerator> SerialDeviceEnumerator::Create() {
return std::unique_ptr<SerialDeviceEnumerator>(
new SerialDeviceEnumeratorLinux());
}
SerialDeviceEnumeratorLinux::SerialDeviceEnumeratorLinux() {
udev_.reset(udev_new());
}
SerialDeviceEnumeratorLinux::~SerialDeviceEnumeratorLinux() {}
std::vector<serial::DeviceInfoPtr> SerialDeviceEnumeratorLinux::GetDevices() {
std::vector<serial::DeviceInfoPtr> devices;
ScopedUdevEnumeratePtr enumerate(udev_enumerate_new(udev_.get()));
if (!enumerate) {
LOG(ERROR) << "Serial device enumeration failed.";
return devices;
}
if (udev_enumerate_add_match_subsystem(enumerate.get(), kSerialSubsystem)) {
LOG(ERROR) << "Serial device enumeration failed.";
return devices;
}
if (udev_enumerate_scan_devices(enumerate.get())) {
LOG(ERROR) << "Serial device enumeration failed.";
return devices;
}
udev_list_entry* entry = udev_enumerate_get_list_entry(enumerate.get());
for (; entry != NULL; entry = udev_list_entry_get_next(entry)) {
ScopedUdevDevicePtr device(udev_device_new_from_syspath(
udev_.get(), udev_list_entry_get_name(entry)));
// TODO(rockot): There may be a better way to filter serial devices here,
// but it's not clear what that would be. Udev will list lots of virtual
// devices with no real endpoint to back them anywhere. The presence of
// a bus identifier (e.g., "pci" or "usb") seems to be a good heuristic
// for detecting actual devices.
const char* path =
udev_device_get_property_value(device.get(), kHostPathKey);
const char* bus = udev_device_get_property_value(device.get(), kHostBusKey);
if (path != NULL && bus != NULL) {
serial::DeviceInfoPtr info(serial::DeviceInfo::New());
info->path = path;
const char* vendor_id =
udev_device_get_property_value(device.get(), kVendorIDKey);
const char* product_id =
udev_device_get_property_value(device.get(), kProductIDKey);
const char* product_name =
udev_device_get_property_value(device.get(), kProductNameKey);
uint32_t int_value;
if (vendor_id && base::HexStringToUInt(vendor_id, &int_value)) {
info->vendor_id = int_value;
info->has_vendor_id = true;
}
if (product_id && base::HexStringToUInt(product_id, &int_value)) {
info->product_id = int_value;
info->has_product_id = true;
}
if (product_name)
info->display_name.emplace(product_name);
devices.push_back(std::move(info));
}
}
return devices;
}
} // namespace device
|
// prints the first "x:.../activate.bat" in the first 10000 bytes of
// the binary file (second arg). Characters may or may not be 16 bit
// integers (ignore '\0')
// (return 0 if found, 1 if not found or error)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, const char** argv) {
if (argc != 3) {
fprintf(stderr, "Usage: nrnbinstr \"pattern\" \"binaryfile\"\n");
return 1;
}
const char* pat = argv[1];
const char* fname = argv[2];
FILE* f = fopen(fname, "rb");
if (!f) {
fprintf(stderr, "Could not open %s\n", fname);
return 1;
}
char* buf = new char[10000];
int size = fread(buf, sizeof(char), 10000, f);
fclose(f);
int c;
char* result = new char[10000];
int lenpat = strlen(pat);
int ifirst=0, ipat=0, iresult=0;
int icolon=0;
for (int i=0; i < size-1; ++i) {
c = buf[i];
if (c == 0 && buf[i+1] != 0) { continue; } // ignore single '\0'
if (isprint(c)) {
if (c == ':' && iresult > 0) {
icolon = iresult - 1; // must be single character drive letter
}
result[iresult++] = c;
if (c == pat[ipat]) {
ipat++;
if (ipat == lenpat) {
result[iresult] = '\0';
printf("%s\n", result + icolon);
return 0;
}
}else if (ipat > 0) {
ipat = 0;
}
}else{
icolon = 0;
iresult = 0;
ipat = 0;
ifirst = i+1;
}
}
return 1;
}
|
/*
* pgm.h
*
* Created on: Jun 9, 2016
* Author: kochoba
*/
#include <fstream>
#include <iostream>
#include <algorithm>
#include <string>
#include <stdint.h>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
#include <stdarg.h>
#include <png++/png.hpp>
#include <png.h>
#ifndef PGM_H_
#define PGM_H_
typedef uint16_t uint16;
typedef unsigned char uchar;
typedef uint8_t uint8;
class imgio {
public:
imgio(){
this->height = 0;
this->width=0;
this->intensity=255;
}
void read_image_meta( std::string filename ){
std::string ext = filename.substr(filename.find_last_of(".")+1);
if(ext == "png"){
this->read_png_file(filename.c_str());
}else if (ext == "pgm"){
this->readpgm(filename.c_str());
}else if(ext == "pfm"){
this->readpfm(filename.c_str());
}else{
std::cout << "Unsupported image extension exiting..." << std::endl;
exit(0);
}
}
template<typename T>
void read_image( std::string filename,T* img ){
std::string ext = filename.substr(filename.find_last_of(".")+1);
if(ext == "png"){
this->read_png_file(filename.c_str(),img);
}else if (ext == "pgm"){
this->readpgm(filename.c_str(),img);
}else if(ext == "pfm"){
this->readpfm(filename.c_str(),img);
}else{
std::cout << "Unsupported image extension! exiting..." << std::endl;
exit(0);
}
}
template<typename T>
void write_image(const std::string file_name,T* data_,std::string out_t){
std::string fname = file_name.substr(0,file_name.find_last_of(".")+1);
if(out_t == "pgm"){
this->writepgm((fname+"pgm").c_str(),data_);
}else if(out_t=="pfm"){
this->writepfm((fname+"pfm").c_str(),data_);
}else if(out_t=="png"){
this->write_png_file((fname+"png").c_str(),data_);
}else if(out_t=="disp"){
this->writeDisparityMap ((fname+"png").c_str(),data_);
}
else{
std::cout << "Unsupported output type! exiting..." << std::endl;
exit(0);
}
}
void readpgm(const char* filename){
std::ifstream ifs(filename,std::ifstream::binary);
std::string c;
if (ifs){
ifs >> c;
if(!c.compare("P2")|| !c.compare("P5")){
ifs >> c;
if(c.substr(0,1).compare("#") == 0){
getline(ifs,c);
ifs >> c;
}
this->width = atoi(c.c_str());
ifs >> c;
this->height = atoi(c.c_str());
ifs >> c;
this->intensity = atoi(c.c_str());
char b;
ifs.read(&b, 1);
}else{
std::cout << "Invalid magic number!" << std::endl;
ifs.close();
exit(1);
}
}else{
std::cout << "File " << filename << " does not exist!" << std::endl;
ifs.close();
exit(1);
}
ifs.close();
}
template<typename T>
void readpgm(const char* filename,T* img){
std::ifstream ifs(filename,std::ifstream::binary);
std::string c;
if (ifs){
ifs >> c;
if(!c.compare("P2")|| !c.compare("P5")){
ifs >> c;
if(c.substr(0,1).compare("#") == 0){
getline(ifs,c);
ifs >> c;
}
this->width = atoi(c.c_str());
ifs >> c;
this->height = atoi(c.c_str());
ifs >> c;
this->intensity = atoi(c.c_str());
char b;
ifs.read(&b, 1);
unsigned char * buffer = new unsigned char[this->width*this->height];
ifs.read((char *)buffer,this->width*this->height);
for(int i=0; i< this->width*this->height; i++)
img[i] = (T) buffer[i];
delete[] buffer;
if(ifs){
}
else{
std::cout << "Error only "<< ifs.gcount()<< " was read..." << std::endl;
ifs.close();
exit(1);
}
}else{
std::cout << "Invalid magic number!" << std::endl;
ifs.close();
exit(1);
}
}else{
std::cout << "File " << filename << " does not exist!" << std::endl;
ifs.close();
exit(1);
}
ifs.close();
}
template<typename T>
void writepgm(const char* filename,T* imgbuffer){
char* buff = (char*)calloc(this->width*this->height,sizeof(char));
#pragma omp parallel
{
#pragma omp for
for (int i=0; i<this->width*this->height;i++ ){
buff[i] = (char)imgbuffer[i];
}
}
std::ofstream ofs(filename,std::ifstream::binary);
ofs << "P5\n" << this->width << " " << this->height << "\n"<<255 << "\n";
ofs.write((char *)buff,this->width*this->height);
ofs.close();
delete[] buff;
}
void readpfm(const char* filename){
FILE * pFile;
pFile = fopen(filename,"rb");
char c[100];
if (pFile != NULL){
int res = fscanf(pFile, "%s", c);
if(res!=EOF && !strcmp(c,"Pf")){
res = fscanf(pFile, "%s", c);
this->width = atoi(c);
res =fscanf(pFile, "%s", c);
this->height = atoi(c);
//fscanf(pFile, "%s", c);
res = fscanf(pFile, "%s", c);
this->endianess = atof(c);
}else{
std::cout << "Invalid magic number! " <<std::endl;
fclose(pFile);exit(1);
}
}else{
std::cout << "File " << filename << " does not exist!" << std::endl;
fclose(pFile);exit(1);
}
fclose(pFile);
}
template<typename T>
void readpfm(const char* filename,T* buffer){
FILE * pFile;
pFile = fopen(filename,"rb");
char c[100];
if (pFile != NULL){
int res = fscanf(pFile, "%s", c);
if(res !=EOF && !strcmp(c,"Pf")){
res = fscanf(pFile, "%s", c);
this->width = atoi(c);
res =fscanf(pFile, "%s", c);
this->height = atoi(c);
res = fscanf(pFile, "%s", c);
this->endianess = atof(c);
fseek (pFile , 0, SEEK_END);
long lSize = ftell (pFile);
long pos = lSize - this->width*this->height*4;
fseek (pFile , pos, SEEK_SET);
T* img = new T[this->width*this->height];
size_t result =fread(img,sizeof(T),this->width*this->height,pFile);
fclose(pFile);
//PFM SPEC image stored bottom -> top reversing image
if(result >0){
#pragma omp parallel
{
#pragma omp for
for(int i =0; i< this->height; i++){
memcpy(&buffer[(this->height -i-1)*this->width],&img[(i*this->width)],this->width*sizeof(T));
}
}
delete [] img;
}
}else{
std::cout << "Invalid magic number! " <<std::endl;
fclose(pFile);exit(1);
}
}else{
std::cout << "File " << filename << " does not exist!" << std::endl;
fclose(pFile);exit(1);
}
fclose(pFile);
}
template<typename T>
void writepfm(const char* filename,T* imgbuffer){
std::ofstream ofs(filename,std::ifstream::binary);
ofs << "Pf\n" << this->width << " " << this->height << "\n"<<-1.0<< "\n";
T* tbimg = (T *)malloc(this->width*this->height*sizeof(T));
//PFM SPEC image stored bottom -> top reversing image
#pragma omp parallel
{
#pragma omp for
for(int i =0; i< this->height; i++){
memcpy(&tbimg[(this->height -i-1)*this->width],&imgbuffer[(i*this->width)],this->width*sizeof(T));
}
}
ofs.write(( char *)tbimg,this->width*this->height*sizeof(T));
ofs.close();
free(tbimg);
}
template<typename T>
void readpbm(const char* filename,T* buffer){
std::ifstream ifs(filename,std::ifstream::binary);
std::string c;
if (ifs){
ifs >> c;
if(!c.compare("P4")){
ifs >> c;
if(c.substr(0,1).compare("#") == 0){
getline(ifs,c);
ifs >> c;
}
this->width = atoi(c.c_str());
ifs >> c;
this->height = atoi(c.c_str());
char b;
ifs.read(&b, 1);
unsigned char c2;
int numbyte =0;
int index =0;
for ( int j = 0; j < this->height; j++ )
{
for ( int i = 0; i < this->width; i++ )
{
if ( i%8 == 0 )
{
ifs.read ( &b, 1 );
c2 = ( unsigned char ) b;
if ( ifs.eof ( ) )
{
std::cout << "\n";
std::cout << "PBM - Fatal error!\n";
std::cout << " Failed reading byte " << numbyte << "\n";
ifs.close();
exit(1);
}
numbyte = numbyte + 1;
}
int k = 7 - i%8;
int bit = ( c2 >> k )%2;
buffer[j*this->width+i] = ((int)bit +1)%2;
index = index + 1;
}
}
ifs.close();
}else if(!c.compare("P1")){
std::cout << "Not implemented yet" << std::endl;
}else{
std::cout << "Invalid magic number!" << std::endl;
ifs.close();
exit(1);
}
}else{
std::cout << "File " << filename << " does not exist!" << std::endl;
ifs.close();
exit(1);
}
ifs.close();
}
void abort_(const char * s, ...)
{
va_list args;
va_start(args, s);
vfprintf(stderr, s, args);
fprintf(stderr, "\n");
va_end(args);
abort();
}
void read_png_file(const char* file_name){
png::image<png::gray_pixel> img(file_name);
this->width = img.get_width();
this->height = img.get_height();
}
template<typename T>
void read_png_file(const char* file_name,T* buffer){
png::image<png::gray_pixel> img(file_name);
this->width = img.get_width();
this->height = img.get_height();
#pragma omp parallel
{
#pragma omp for
for(uint i=0;i<img.get_height();i++)
{
for(uint j=0;j<img.get_width();j++)
{
buffer[i*this->width+j] = (T)img.get_pixel(j,i);
}
}
}
}
template<typename T>
void write_png_file(const char* file_name,T * buffer){
png::image<png::gray_pixel> img(this->width,this->height);
#pragma omp parallel
{
#pragma omp for
for(uint i=0;i<img.get_height();i++)
{
for(uint j=0;j<img.get_width();j++)
{
img.set_pixel(j,i,buffer[i*this->width+j]);
}
}
}
img.write(file_name);
}
// is disparity at given pixel to invalid
inline void setInvalid (float* data_,const int32_t u,const int32_t v) {
data_[v*this->width+u] = -1;
}
// set disparity at given pixel
inline void setDisp (float* data_,const int32_t u,const int32_t v,const float val) {
data_[v*this->width+u] = val;
}
float* readDisparityMap (const std::string file_name) {
png::image<png::gray_pixel_16> image(file_name);
this->width = image.get_width();
this->height = image.get_height();
float* data_ = (float*)malloc(this->width*this->height*sizeof(float));
#pragma omp parallel
{
#pragma omp for
for (int32_t v=0; v<this->height; v++) {
for (int32_t u=0; u<this->width; u++) {
uint16_t val = image.get_pixel(u,v);
if (val==0)
setInvalid(data_,u,v);
else
setDisp(data_,u,v,((float)val)/256.0);
}
}
}
return data_;
}
// get disparity at given pixel
inline float getDisp (float* data_,const int32_t u,const int32_t v) {
return data_[v*this->width+u];
}
// is disparity valid
inline bool isValid (float* data_,const int32_t u,const int32_t v) {
return data_[v*this->width+u]>=0;
}
void writeDisparityMap (const std::string file_name,float* data_) {
png::image< png::gray_pixel_16 > image(this->width,this->height);
#pragma omp parallel
{
#pragma omp for
for (int32_t v=0; v<this->height; v++) {
for (int32_t u=0; u<this->width; u++) {
if (isValid(data_,u,v))
image.set_pixel(u,v,(uint16_t)(std::max(getDisp(data_,u,v)*256.0,1.0)));
else
image.set_pixel(u,v,0);
}
}
}
image.write(file_name);
}
void setHeight(int height){
this->height=height;
}
void setWidth(int width){
this->width=width;
}
int getHeight(void){
return this->height;
}
int getWidth(void){
return this->width;
}
int getIntensity(void){
return this->intensity;
}
virtual ~imgio(){}
private:
int height;
int width;
int intensity;
float endianess;
uchar color_type;
uchar bit_depth;
};
#endif /* PGM_H_ */
|
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_PARSE_NOT_FWD_HPP_INCLUDED
#define FCPPT_PARSE_NOT_FWD_HPP_INCLUDED
namespace fcppt
{
namespace parse
{
template<
typename Parser
>
class not_;
}
}
#endif
|
/***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XWIDGETS_IMAGE_HPP
#define XWIDGETS_IMAGE_HPP
#include <cstddef>
#include <string>
#include <vector>
#include "xmaterialize.hpp"
#include "xmedia.hpp"
namespace xw
{
/*********************
* image declaration *
*********************/
template <class D>
class ximage : public xmedia<D>
{
public:
using base_type = xmedia<D>;
using derived_type = D;
void serialize_state(nl::json& state, xeus::buffer_sequence&) const;
void apply_patch(const nl::json&, const xeus::buffer_sequence&);
XPROPERTY(std::string, derived_type, format, "png");
XPROPERTY(std::string, derived_type, width, "");
XPROPERTY(std::string, derived_type, height, "");
protected:
ximage();
using base_type::base_type;
private:
void set_defaults();
};
using image = xmaterialize<ximage>;
/*************************
* ximage implementation *
*************************/
template <class D>
inline void ximage<D>::serialize_state(nl::json& state, xeus::buffer_sequence& buffers) const
{
base_type::serialize_state(state, buffers);
xwidgets_serialize(format(), state["format"], buffers);
xwidgets_serialize(width(), state["width"], buffers);
xwidgets_serialize(height(), state["height"], buffers);
}
template <class D>
inline void ximage<D>::apply_patch(const nl::json& patch, const xeus::buffer_sequence& buffers)
{
base_type::apply_patch(patch, buffers);
set_property_from_patch(format, patch, buffers);
set_property_from_patch(width, patch, buffers);
set_property_from_patch(height, patch, buffers);
}
template <class D>
inline ximage<D>::ximage()
: base_type()
{
set_defaults();
}
template <class D>
inline void ximage<D>::set_defaults()
{
this->_model_name() = "ImageModel";
this->_view_name() = "ImageView";
}
inline auto image_from_file(const std::string& filename)
{
return image::initialize().value(read_file(filename));
}
inline auto image_from_url(const std::string& url)
{
std::vector<char> value(url.cbegin(), url.cend());
return image::initialize().value(value).format("url");
}
/**********************
* custom serializers *
**********************/
inline void set_property_from_patch(decltype(image::value)& property,
const nl::json& patch,
const xeus::buffer_sequence& buffers)
{
auto it = patch.find(property.name());
if (it != patch.end())
{
using value_type = typename decltype(image::value)::value_type;
std::size_t index = buffer_index(patch[property.name()].template get<std::string>());
const auto& value_buffer = buffers[index];
const char* value_buf = value_buffer.data<const char>();
property = value_type(value_buf, value_buf + value_buffer.size());
}
}
/*********************
* precompiled types *
*********************/
extern template class xmaterialize<ximage>;
extern template class xtransport<xmaterialize<ximage>>;
}
#endif
|
#include "projection.hpp"
#include <algorithm>
#include <functional>
#include <memory>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "constant_mappings.hpp"
#include "operators/pqp_expression.hpp"
#include "resolve_type.hpp"
#include "scheduler/current_scheduler.hpp"
#include "sql/sql_query_plan.hpp"
#include "storage/create_iterable_from_column.hpp"
#include "storage/materialize.hpp"
#include "storage/reference_column.hpp"
#include "utils/arithmetic_operator_expression.hpp"
namespace opossum {
Projection::Projection(const std::shared_ptr<const AbstractOperator>& in, const ColumnExpressions& column_expressions)
: AbstractReadOnlyOperator(OperatorType::Projection, in), _column_expressions(column_expressions) {}
const std::string Projection::name() const { return "Projection"; }
const std::string Projection::description(DescriptionMode description_mode) const {
std::stringstream desc;
desc << "[Projection] ";
for (size_t expression_idx = 0; expression_idx < _column_expressions.size(); ++expression_idx) {
desc << _column_expressions[expression_idx]->description();
if (expression_idx + 1 < _column_expressions.size()) {
desc << ", ";
}
}
return desc.str();
}
const Projection::ColumnExpressions& Projection::column_expressions() const { return _column_expressions; }
std::shared_ptr<AbstractOperator> Projection::_on_recreate(
const std::vector<AllParameterVariant>& args, const std::shared_ptr<AbstractOperator>& recreated_input_left,
const std::shared_ptr<AbstractOperator>& recreated_input_right) const {
ColumnExpressions new_column_expressions;
for (const auto& column_expression : _column_expressions) {
std::shared_ptr<PQPExpression> new_column_expression = column_expression;
if (column_expression->type() == ExpressionType::Placeholder) {
auto value_placeholder = column_expression->value_placeholder();
if (value_placeholder.index() < args.size()) {
const auto& parameter_variant = args[value_placeholder.index()];
auto value = boost::get<AllTypeVariant>(parameter_variant);
new_column_expression = column_expression->copy_with_placeholder_value(value);
}
} else if (column_expression->type() == ExpressionType::Subselect) {
const auto new_subselect_operator = column_expression->subselect_operator()->recreate(args);
new_column_expression = PQPExpression::create_subselect(new_subselect_operator, column_expression->alias());
}
new_column_expressions.push_back(new_column_expression);
}
return std::make_shared<Projection>(recreated_input_left, new_column_expressions);
}
template <typename T>
std::shared_ptr<BaseColumn> Projection::_create_column(boost::hana::basic_type<T> type, const ChunkID chunk_id,
const std::shared_ptr<PQPExpression>& expression,
std::shared_ptr<const Table> input_table_left,
bool reuse_column_from_input) {
// check whether term is a just a simple column and bypass this column
if (reuse_column_from_input) {
// we have to use get_mutable_column here because we cannot add a const column to the chunk
return input_table_left->get_chunk(chunk_id)->get_mutable_column(expression->column_id());
}
if (expression->is_null_literal()) {
// fill a nullable column with NULLs
auto row_count = input_table_left->get_chunk(chunk_id)->size();
auto null_values = pmr_concurrent_vector<bool>(row_count, true);
// explicitly pass T{} because in some cases it won't initialize otherwise
auto values = pmr_concurrent_vector<T>(row_count, T{});
return std::make_shared<ValueColumn<T>>(std::move(values), std::move(null_values));
} else if (expression->type() == ExpressionType::Subselect) {
// since we are only extracting one value from the subselect
// table, using Table::get_value is not a performance issue
PerformanceWarningDisabler performance_warning_disabler;
// the subquery result table can only contain exactly one column with one row
// since we checked for this at subquery execution time we can make some assumptions here
const auto subselect_table = expression->subselect_table();
const auto subselect_value = subselect_table->get_value<T>(ColumnID(0), 0u);
auto row_count = input_table_left->get_chunk(chunk_id)->size();
// materialize the result of the subquery for every row in the input table
auto null_values = pmr_concurrent_vector<bool>(row_count, false);
auto values = pmr_concurrent_vector<T>(row_count, subselect_value);
return std::make_shared<ValueColumn<T>>(std::move(values), std::move(null_values));
} else {
// fill a value column with the specified expression
auto values = _evaluate_expression<T>(expression, input_table_left, chunk_id);
pmr_concurrent_vector<T> non_null_values;
non_null_values.grow_to_at_least(values.size());
pmr_concurrent_vector<bool> null_values;
null_values.grow_to_at_least(values.size());
ChunkOffset offset{0};
for (const auto value : values) {
non_null_values[offset] = value.second;
null_values[offset] = value.first;
offset++;
}
return std::make_shared<ValueColumn<T>>(std::move(non_null_values), std::move(null_values));
}
}
std::shared_ptr<const Table> Projection::_on_execute() {
auto reuse_columns_from_input = true;
/**
* Determine the TableColumnDefinitions and create empty output table from them
*/
TableColumnDefinitions column_definitions;
for (const auto& column_expression : _column_expressions) {
TableColumnDefinition column_definition;
// For subselects, we need to execute the subquery in order to use the result table later
if (column_expression->is_subselect() && !column_expression->has_subselect_table()) {
// Because subqueries are still WIP, we do not clean up their temporary tables. Otherwise, we would have to
// somehow pass in cleanup_temporaries from the pipeline.
SQLQueryPlan query_plan{CleanupTemporaries::No};
query_plan.add_tree_by_root(column_expression->subselect_operator());
auto transaction_context = this->transaction_context();
if (transaction_context) {
query_plan.set_transaction_context(transaction_context);
}
const auto tasks = query_plan.create_tasks();
CurrentScheduler::schedule_and_wait_for_tasks(tasks);
auto result_table = tasks.back()->get_operator()->get_output();
DebugAssert(result_table->column_count() == 1, "Subselect table must have exactly one column.");
Assert(result_table->row_count() == 1,
"Subselect returned " + std::to_string(result_table->row_count()) + " rows instead of one");
column_expression->set_subselect_table(result_table);
}
// Determine column name
if (column_expression->alias()) {
column_definition.name = *column_expression->alias();
} else if (column_expression->type() == ExpressionType::Column) {
column_definition.name = input_table_left()->column_name(column_expression->column_id());
} else if (column_expression->is_arithmetic_operator() || column_expression->type() == ExpressionType::Literal) {
column_definition.name = column_expression->to_string(input_table_left()->column_names());
} else if (column_expression->is_subselect()) {
column_definition.name = column_expression->subselect_table()->column_names()[0];
} else {
Fail("Expression type is not supported.");
}
if (column_expression->type() != ExpressionType::Column) {
reuse_columns_from_input = false;
}
const auto type = _get_type_of_expression(column_expression, input_table_left());
if (type == DataType::Null) {
// in case of a NULL literal, simply add a nullable int column
column_definition.data_type = DataType::Int;
column_definition.nullable = true;
} else {
column_definition.data_type = type;
}
column_definitions.emplace_back(column_definition);
}
const auto table_type = reuse_columns_from_input ? input_table_left()->type() : TableType::Data;
auto output_table = std::make_shared<Table>(column_definitions, table_type, input_table_left()->max_chunk_size());
/**
* Perform the projection
*/
for (ChunkID chunk_id{0}; chunk_id < input_table_left()->chunk_count(); ++chunk_id) {
ChunkColumns output_columns;
for (uint16_t expression_index = 0u; expression_index < _column_expressions.size(); ++expression_index) {
resolve_data_type(output_table->column_data_type(ColumnID{expression_index}), [&](auto type) {
const auto column = _create_column(type, chunk_id, _column_expressions[expression_index], input_table_left(),
reuse_columns_from_input);
output_columns.push_back(column);
});
}
output_table->append_chunk(output_columns);
}
return output_table;
}
DataType Projection::_get_type_of_expression(const std::shared_ptr<PQPExpression>& expression,
const std::shared_ptr<const Table>& table) {
if (expression->type() == ExpressionType::Literal || expression->type() == ExpressionType::Placeholder) {
return data_type_from_all_type_variant(expression->value());
}
if (expression->type() == ExpressionType::Placeholder) {
return data_type_from_all_type_variant(expression->value());
}
if (expression->type() == ExpressionType::Column) {
return table->column_data_type(expression->column_id());
}
if (expression->type() == ExpressionType::Subselect) {
return expression->subselect_table()->column_data_type(ColumnID(0));
}
Assert(expression->is_arithmetic_operator(),
"Only literals, columns, and arithmetic operators supported for expression type evaluation");
const auto type_left = _get_type_of_expression(expression->left_child(), table);
const auto type_right = _get_type_of_expression(expression->right_child(), table);
if (type_left == DataType::Null) return type_right;
if (type_right == DataType::Null) return type_left;
const auto type_string_left = data_type_to_string.left.at(type_left);
const auto type_string_right = data_type_to_string.left.at(type_right);
// TODO(anybody): int + float = float etc...
// This is currently not supported by `_evaluate_expression()` because it is only templated once.
Assert(type_left == type_right, "Projection currently only supports expressions with same type on both sides (" +
type_string_left + " vs " + type_string_right + ")");
return type_left;
}
template <typename T>
const pmr_concurrent_vector<std::pair<bool, T>> Projection::_evaluate_expression(
const std::shared_ptr<PQPExpression>& expression, const std::shared_ptr<const Table> table,
const ChunkID chunk_id) {
/**
* Handle Literal
* This is only used if the Literal represents a constant column, e.g. in 'SELECT 5 FROM table_a'.
* On the other hand this is not used for nested arithmetic Expressions, such as 'SELECT a + 5 FROM table_a'.
*/
if (expression->type() == ExpressionType::Literal) {
return pmr_concurrent_vector<std::pair<bool, T>>(table->get_chunk(chunk_id)->size(),
std::make_pair(false, boost::get<T>(expression->value())));
}
/**
* Handle column reference
*/
if (expression->type() == ExpressionType::Column) {
const auto chunk = table->get_chunk(chunk_id);
pmr_concurrent_vector<std::pair<bool, T>> values_and_nulls;
values_and_nulls.reserve(chunk->size());
materialize_values_and_nulls(*chunk->get_column(expression->column_id()), values_and_nulls);
return values_and_nulls;
}
/**
* Handle arithmetic expression
*/
Assert(expression->is_arithmetic_operator(), "Projection only supports literals, column refs and arithmetics");
const auto& arithmetic_operator_function = function_for_arithmetic_expression<T>(expression->type());
pmr_concurrent_vector<std::pair<bool, T>> values;
values.resize(table->get_chunk(chunk_id)->size());
const auto& left = expression->left_child();
const auto& right = expression->right_child();
const auto left_is_literal = left->type() == ExpressionType::Literal;
const auto right_is_literal = right->type() == ExpressionType::Literal;
if ((left_is_literal && variant_is_null(left->value())) || (right_is_literal && variant_is_null(right->value()))) {
// one of the operands is a literal null - early out.
std::fill(values.begin(), values.end(), std::make_pair(true, T{}));
} else if (left_is_literal && right_is_literal) {
std::fill(values.begin(), values.end(),
std::make_pair(
false, arithmetic_operator_function(boost::get<T>(left->value()), boost::get<T>(right->value()))));
} else if (right_is_literal) {
auto left_values = _evaluate_expression<T>(left, table, chunk_id);
auto right_value = boost::get<T>(right->value());
// apply operator function to both vectors
auto func = [&](const std::pair<bool, T>& left_value) -> std::pair<bool, T> {
return std::make_pair(left_value.first, arithmetic_operator_function(left_value.second, right_value));
};
std::transform(left_values.begin(), left_values.end(), values.begin(), func);
} else if (left_is_literal) {
auto right_values = _evaluate_expression<T>(right, table, chunk_id);
auto left_value = boost::get<T>(left->value());
// apply operator function to both vectors
auto func = [&](const std::pair<bool, T>& right_value) -> std::pair<bool, T> {
return std::make_pair(right_value.first, arithmetic_operator_function(left_value, right_value.second));
};
std::transform(right_values.begin(), right_values.end(), values.begin(), func);
} else {
auto left_values = _evaluate_expression<T>(left, table, chunk_id);
auto right_values = _evaluate_expression<T>(right, table, chunk_id);
// apply operator function to both vectors
auto func = [&](const std::pair<bool, T>& left, const std::pair<bool, T>& right) -> std::pair<bool, T> {
return std::make_pair(left.first || right.first, arithmetic_operator_function(left.second, right.second));
};
std::transform(left_values.begin(), left_values.end(), right_values.begin(), values.begin(), func);
}
return values;
}
// returns the singleton dummy table used for literal projections
std::shared_ptr<Table> Projection::dummy_table() {
static auto shared_dummy = std::make_shared<DummyTable>();
return shared_dummy;
}
} // namespace opossum
|
/*
* MIT License
*
* Copyright (c) 2017 Pedro Cuadra
*
* 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 HARRISLAPLACEDETECT_H
#define HARRISLAPLACEDETECT_H
#include <opencv2/core/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <detectors/FeatureDetect.hpp>
using namespace cv;
using namespace cv::xfeatures2d;
using namespace std;
class HarrisLaplaceDetect : public FeatureDetect {
public:
/** Comand line parser options */
static const String options;
/**
* Harris-Laplace feature detection
* @param parser Comand Line Parser
*/
HarrisLaplaceDetect(CommandLineParser parser)
: FeatureDetect(parser, "Harris Laplace", "harrislaplace") {
this->detector = HarrisLaplaceFeatureDetector::create();
}
};
const String HarrisLaplaceDetect::options =
"{harrislaplace | | Harris Laplace Enable }";
#endif /* HARRISLAPLACEDETECT_H */
|
#pragma once
#include <Windows.h>
#include "Debug.h"
decltype(Debug::mode_) Debug::mode_ = Debug::Mode::File;
decltype(Debug::logFunc_) Debug::logFunc_ = nullptr;
decltype(Debug::errFunc_) Debug::errFunc_ = nullptr;
decltype(Debug::fs_) Debug::fs_;
decltype(Debug::ss_) Debug::ss_;
decltype(Debug::mutex_) Debug::mutex_;
void Debug::Initialize()
{
if (mode_ == Mode::File)
{
fs_.open("uWindowCapture.log");
Debug::Log("Start");
}
}
void Debug::Finalize()
{
if (mode_ == Mode::File)
{
Debug::Log("Stop");
fs_.close();
}
}
void OutputApiError(const char* apiName)
{
const auto error = ::GetLastError();
Debug::Error(apiName, "() failed with error code: ", error);
}
void OutputApiError(const char* func, const char* apiName)
{
const auto error = ::GetLastError();
Debug::Error(func, "() => ", apiName, "() failed with error code: ", error);
}
|
#include<stdio.h>
int main ()
{
int a[100],n,i;
void reverse(int a[],int n);
printf("Enter no of elements:\n");
scanf("%d",&n);
printf("Enter elements:\n");
for(i=o;i<n;i++)
scanf("%d",&a[i]);
reverse(a,n);
return 0;
}
void reverse(int a[],int n)
{
int i,rev[100];
for(i=o;i<n;i++)
{
rev[n-i-1]=a[i];
}
printf("Reversed array:\n");
for(i=o;i<n;i++)
{
printf("%d",rev[i]);
}
}
/*O/P:
*/
|
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#include "ai/ai_profiles.h"
#include "debugconsole/console.h"
#include "freespace.h"
#include "hud/hud.h"
#include "hud/hudmessage.h"
#include "iff_defs/iff_defs.h"
#include "localization/localize.h"
#include "mission/missionparse.h"
#include "network/multi.h"
#include "network/multi_dogfight.h"
#include "network/multi_pmsg.h"
#include "network/multi_team.h"
#include "network/multimsgs.h"
#include "network/multiutil.h"
#include "object/object.h"
#include "parse/parselo.h"
#include "pilotfile/pilotfile.h"
#include "playerman/player.h"
#include "ship/ship.h"
#include "stats/medals.h"
#include "stats/scoring.h"
#include "weapon/weapon.h"
/*
// uncomment to get extra debug messages when a player scores
#define SCORING_DEBUG
*/
// what percent of points of total damage to a ship a player has to have done to get an assist (or a kill) when it is killed
float Kill_percentage = 0.30f;
float Assist_percentage = 0.15f;
// traitor stuff
extern debriefing Traitor_debriefing;
traitor_stuff Traitor;
// these tables are overwritten with the values from rank.tbl
rank_stuff Ranks[NUM_RANKS];
// scoring scale factors by skill level
float Scoring_scale_factors[NUM_SKILL_LEVELS] = {
0.2f, // very easy
0.4f, // easy
0.7f, // medium
1.0f, // hard
1.25f // insane
};
void parse_rank_tbl()
{
try
{
read_file_text("rank.tbl", CF_TYPE_TABLES);
reset_parse();
// parse in all the rank names
int idx = 0;
skip_to_string("[RANK NAMES]");
ignore_white_space();
while (required_string_either("#End", "$Name:"))
{
Assert(idx < NUM_RANKS);
required_string("$Name:");
stuff_string(Ranks[idx].name, F_NAME, NAME_LENGTH);
required_string("$Points:");
stuff_int(&Ranks[idx].points);
required_string("$Bitmap:");
stuff_string(Ranks[idx].bitmap, F_NAME, MAX_FILENAME_LEN);
required_string("$Promotion Voice Base:");
stuff_string(Ranks[idx].promotion_voice_base, F_NAME, MAX_FILENAME_LEN);
while (check_for_string("$Promotion Text:"))
{
SCP_string buf;
int persona = -1;
required_string("$Promotion Text:");
stuff_string(buf, F_MULTITEXT);
drop_white_space(buf);
compact_multitext_string(buf);
if (optional_string("+Persona:"))
{
stuff_int(&persona);
if (persona < 0)
{
Warning(LOCATION, "Debriefing text for %s rank is assigned to an invalid persona: %i (must be 0 or greater).\n", Ranks[idx].name, persona);
continue;
}
}
Ranks[idx].promotion_text[persona] = buf;
}
if (Ranks[idx].promotion_text.find(-1) == Ranks[idx].promotion_text.end())
{
Warning(LOCATION, "%s rank is missing default debriefing text.\n", Ranks[idx].name);
Ranks[idx].promotion_text[-1] = "";
}
idx++;
}
required_string("#End");
// be sure that all rank points are in order
for (idx = 0; idx < NUM_RANKS - 1; idx++) {
if (Ranks[idx].points >= Ranks[idx + 1].points)
Warning(LOCATION, "Rank #%d (%s) has a higher \"$Points:\" value (%d) than the following rank (%s, %d points). This shouldn't actually crash FSO, but it might result in unexpected or incorrect behavior.\n", idx + 1, Ranks[idx].name, Ranks[idx].points, Ranks[idx+1].name, Ranks[idx+1].points);
}
}
catch (const parse::ParseException& e)
{
mprintf(("TABLES: Unable to parse '%s'! Error message = %s.\n", "rank.tbl", e.what()));
return;
}
}
void parse_traitor_tbl()
{
try
{
read_file_text("traitor.tbl", CF_TYPE_TABLES);
reset_parse();
// simplified form of the debriefing stuff.
auto debrief = &Traitor_debriefing;
required_string("#Debriefing_info");
required_string("$Num stages:");
stuff_int(&debrief->num_stages);
Assert(debrief->num_stages == 1);
int stage_num = 0;
auto stagep = &debrief->stages[stage_num++];
required_string("$Formula:");
stagep->formula = 1; // sexp nodes aren't initialized yet, but node 1 will be Locked_sexp_true
skip_to_start_of_string("$multi text"); // just skip over the sexp, since it must always be locked-true anyway
while (check_for_string("$multi text"))
{
SCP_string text;
int persona = -1;
required_string("$multi text");
stuff_string(text, F_MULTITEXT);
if (optional_string("+Persona:"))
{
stuff_int(&persona);
if (persona < 0)
{
Warning(LOCATION, "Traitor information is assigned to an invalid persona: %i (must be 0 or greater).\n", persona);
continue;
}
}
Traitor.debriefing_text[persona] = text;
}
if (Traitor.debriefing_text.find(-1) == Traitor.debriefing_text.end())
{
Warning(LOCATION, "Traitor is missing default debriefing information.\n");
Traitor.debriefing_text[-1] = "";
}
if (optional_string("$Voice:"))
stuff_string(Traitor.traitor_voice_base, F_FILESPEC, MAX_FILENAME_LEN);
required_string("$Recommendation text:");
stuff_string(Traitor.recommendation_text, F_MULTITEXT);
}
catch (const parse::ParseException& e)
{
mprintf(("TABLES: Unable to parse '%s'! Error message = %s.\n", "traitor.tbl", e.what()));
return;
}
}
// initialize a nice blank scoring element
void scoring_struct::init()
{
flags = 0;
score = 0;
rank = RANK_ENSIGN;
medal_counts.assign(Num_medals, 0);
memset(kills, 0, sizeof(kills));
assists = 0;
kill_count = 0;
kill_count_ok = 0;
p_shots_fired = 0;
s_shots_fired = 0;
p_shots_hit = 0;
s_shots_hit = 0;
p_bonehead_hits = 0;
s_bonehead_hits = 0;
bonehead_kills = 0;
missions_flown = 0;
flight_time = 0;
last_flown = 0;
last_backup = 0;
m_medal_earned = -1; // hasn't earned a medal yet
m_promotion_earned = -1;
m_badge_earned.clear();
m_score = 0;
memset(m_kills, 0, sizeof(m_kills));
memset(m_okKills, 0, sizeof(m_okKills));
m_kill_count = 0;
m_kill_count_ok = 0;
m_assists = 0;
mp_shots_fired = 0;
ms_shots_fired = 0;
mp_shots_hit = 0;
ms_shots_hit = 0;
mp_bonehead_hits = 0;
ms_bonehead_hits = 0;
m_bonehead_kills = 0;
m_player_deaths = 0;
memset(m_dogfight_kills, 0, sizeof(m_dogfight_kills));
}
// clone someone else's scoring element
void scoring_struct::assign(const scoring_struct &s)
{
flags = s.flags;
score = s.score;
rank = s.rank;
medal_counts.assign(s.medal_counts.begin(), s.medal_counts.end());
memcpy(kills, s.kills, MAX_SHIP_CLASSES * sizeof(int));
assists = s.assists;
kill_count = s.kill_count;
kill_count_ok = s.kill_count_ok;
p_shots_fired = s.p_shots_fired;
s_shots_fired = s.s_shots_fired;
p_shots_hit = s.p_shots_hit;
s_shots_hit = s.s_shots_hit;
p_bonehead_hits = s.p_bonehead_hits;
s_bonehead_hits = s.s_bonehead_hits;
bonehead_kills = s.bonehead_kills;
missions_flown = s.missions_flown;
flight_time = s.flight_time;
last_flown = s.last_flown;
last_backup = s.last_backup;
m_medal_earned = s.m_medal_earned;
m_promotion_earned = s.m_promotion_earned;
m_badge_earned = s.m_badge_earned;
m_score = s.m_score;
memcpy(m_kills, s.m_kills, MAX_SHIP_CLASSES * sizeof(int));
memcpy(m_okKills, s.m_okKills, MAX_SHIP_CLASSES * sizeof(int));
m_kill_count = s.m_kill_count;
m_kill_count_ok = s.m_kill_count_ok;
m_assists = s.m_assists;
mp_shots_fired = s.mp_shots_fired;
ms_shots_fired = s.ms_shots_fired;
mp_shots_hit = s.mp_shots_hit;
ms_shots_hit = s.ms_shots_hit;
mp_bonehead_hits = s.mp_bonehead_hits;
ms_bonehead_hits = s.ms_bonehead_hits;
m_bonehead_kills = s.m_bonehead_kills;
m_player_deaths = s.m_player_deaths;
memcpy(m_dogfight_kills, s.m_dogfight_kills, MAX_PLAYERS * sizeof(int));
}
template<typename T, size_t N>
bool array_compare(const T (&left)[N], const T (&right)[N]) {
auto left_el = std::begin(left);
auto right_el = std::begin(right);
auto left_end = std::end(left);
auto right_end = std::end(right);
for (; left_el != left_end && right_el != right_end; ++left_el, ++right_el) {
if (!(*left_el == *right_el)) {
return false;
}
}
return true;
}
bool scoring_struct::operator==(const scoring_struct& rhs) const {
return flags == rhs.flags && score == rhs.score && rank == rhs.rank && medal_counts == rhs.medal_counts
&& array_compare(kills, rhs.kills) && assists == rhs.assists && kill_count == rhs.kill_count
&& kill_count_ok == rhs.kill_count_ok && p_shots_fired == rhs.p_shots_fired
&& s_shots_fired == rhs.s_shots_fired && p_shots_hit == rhs.p_shots_hit && s_shots_hit == rhs.s_shots_hit
&& p_bonehead_hits == rhs.p_bonehead_hits && s_bonehead_hits == rhs.s_bonehead_hits
&& bonehead_kills == rhs.bonehead_kills && missions_flown == rhs.missions_flown
&& flight_time == rhs.flight_time && last_flown == rhs.last_flown && last_backup == rhs.last_backup
&& m_medal_earned == rhs.m_medal_earned && m_badge_earned == rhs.m_badge_earned
&& m_promotion_earned == rhs.m_promotion_earned && m_score == rhs.m_score
&& array_compare(m_kills, rhs.m_kills)
&& array_compare(m_okKills, rhs.m_okKills) && m_kill_count == rhs.m_kill_count
&& m_kill_count_ok == rhs.m_kill_count_ok && m_assists == rhs.m_assists && mp_shots_fired == rhs.mp_shots_fired
&& ms_shots_fired == rhs.ms_shots_fired && mp_shots_hit == rhs.mp_shots_hit && ms_shots_hit == rhs.ms_shots_hit
&& mp_bonehead_hits == rhs.mp_bonehead_hits && ms_bonehead_hits == rhs.ms_bonehead_hits
&& m_bonehead_kills == rhs.m_bonehead_kills && m_player_deaths == rhs.m_player_deaths
&& array_compare(m_dogfight_kills, rhs.m_dogfight_kills) ;
}
bool scoring_struct::operator!=(const scoring_struct& rhs) const {
return !(rhs == *this);
}
// initialize the Player's mission-based stats before he goes into a mission
void scoring_level_init( scoring_struct *scp )
{
scp->m_medal_earned = -1; // hasn't earned a medal yet
scp->m_promotion_earned = -1;
scp->m_badge_earned.clear();
scp->m_score = 0;
scp->m_assists = 0;
scp->mp_shots_fired = 0;
scp->mp_shots_hit = 0;
scp->ms_shots_fired = 0;
scp->ms_shots_hit = 0;
scp->mp_bonehead_hits=0;
scp->ms_bonehead_hits=0;
scp->m_bonehead_kills=0;
memset(scp->m_kills, 0, MAX_SHIP_CLASSES * sizeof(int));
memset(scp->m_okKills, 0, MAX_SHIP_CLASSES * sizeof(int));
scp->m_kill_count = 0;
scp->m_kill_count_ok = 0;
scp->m_player_deaths = 0;
memset(scp->m_dogfight_kills, 0, MAX_PLAYERS * sizeof(int));
if (The_mission.ai_profile != NULL) {
Kill_percentage = The_mission.ai_profile->kill_percentage_scale[Game_skill_level];
Assist_percentage = The_mission.ai_profile->assist_percentage_scale[Game_skill_level];
} else {
Kill_percentage = 0.30f;
Assist_percentage = 0.15f;
}
}
void scoring_eval_rank( scoring_struct *sc )
{
int i, score, new_rank, old_rank;
old_rank = sc->rank;
new_rank = old_rank;
// first check to see if the promotion flag is set -- if so, return the new rank
if ( Player->flags & PLAYER_FLAGS_PROMOTED ) {
// if the player does indeed get promoted, we should change his mission score
// to reflect the difference between all time and new rank score
if ( old_rank < MAX_FREESPACE2_RANK ) {
new_rank++;
if ( (sc->m_score + sc->score) < Ranks[new_rank].points )
sc->m_score = (Ranks[new_rank].points - sc->score);
}
} else {
// we get here only if player wasn't promoted automatically.
// it is possible to get a negative mission score but that will
// never result in a degradation
score = sc->m_score + sc->score;
for (i=old_rank + 1; i<NUM_RANKS; i++) {
if ( score >= Ranks[i].points )
new_rank = i;
}
}
// if the ranks do not match, then "grant" the new rank
if ( old_rank != new_rank ) {
Assert( new_rank >= 0 );
sc->m_promotion_earned = new_rank;
sc->rank = new_rank;
}
}
// function to evaluate whether or not a new badge is going to be awarded. This function returns
// which medal is awarded.
void scoring_eval_badges(scoring_struct *sc)
{
int total_kills;
// to determine badges, we count kills based on fighter/bomber types. We must count kills in
// all time stats + current mission stats. And, only for enemy fighters/bombers
total_kills = 0;
for (auto it = Ship_info.cbegin(); it != Ship_info.cend(); ++it) {
if (it->is_fighter_bomber()) {
auto i = std::distance(Ship_info.cbegin(), it);
total_kills += sc->m_okKills[i];
total_kills += sc->kills[i];
}
}
// total_kills should now reflect the number of kills on hostile fighters/bombers. Check this number
// against badge kill numbers, and award the appropriate badges as neccessary.
int last_badge_kills = 0;
for (auto i = 0; i < Num_medals; i++ ) {
if ( total_kills >= Medals[i].kills_needed
&& Medals[i].kills_needed > last_badge_kills
&& Medals[i].kills_needed > 0 )
{
last_badge_kills = Medals[i].kills_needed;
if (sc->medal_counts[i] < 1) {
sc->medal_counts[i] = 1;
sc->m_badge_earned.push_back(i);
}
}
}
}
// central point for dealing with accepting the score for a misison.
void scoring_do_accept(scoring_struct *score)
{
int idx;
// do rank, badges, and medals first since they require the alltime stuff
// to not be updated yet.
// do medal stuff
if ( score->m_medal_earned != -1 ){
score->medal_counts[score->m_medal_earned]++;
}
// return when in training mission. We can grant a medal in training, but don't
// want to calculate any other statistics.
if (The_mission.game_type == MISSION_TYPE_TRAINING){
return;
}
scoring_eval_rank(score);
scoring_eval_badges(score);
score->kill_count += score->m_kill_count;
score->kill_count_ok += score->m_kill_count_ok;
score->score += score->m_score;
score->assists += score->m_assists;
score->p_shots_fired += score->mp_shots_fired;
score->s_shots_fired += score->ms_shots_fired;
score->p_shots_hit += score->mp_shots_hit;
score->s_shots_hit += score->ms_shots_hit;
score->p_bonehead_hits += score->mp_bonehead_hits;
score->s_bonehead_hits += score->ms_bonehead_hits;
score->bonehead_kills += score->m_bonehead_kills;
for(idx=0;idx<MAX_SHIP_CLASSES;idx++){
score->kills[idx] = (int)(score->kills[idx] + score->m_okKills[idx]);
}
// add in mission time
score->flight_time += (unsigned int)f2fl(Missiontime);
score->last_backup = score->last_flown;
score->last_flown = (_fs_time_t)time(NULL);
score->missions_flown++;
}
// backout the score for a mission. This function gets called when the player chooses to refly a misison
// after debriefing
void scoring_backout_accept( scoring_struct *score )
{
int idx;
// if a badge was earned, take it back
if ( score->m_badge_earned.size() ){
for (size_t medal = 0; medal < score->m_badge_earned.size(); medal++) {
score->medal_counts[score->m_badge_earned[medal]] = 0;
}
}
// return when in training mission. We can grant a medal in training, but don't
// want to calculate any other statistics.
if (The_mission.game_type == MISSION_TYPE_TRAINING){
return;
}
score->kill_count -= score->m_kill_count;
score->kill_count_ok -= score->m_kill_count_ok;
score->score -= score->m_score;
score->assists -= score->m_assists;
score->p_shots_fired -= score->mp_shots_fired;
score->s_shots_fired -= score->ms_shots_fired;
score->p_shots_hit -= score->mp_shots_hit;
score->s_shots_hit -= score->ms_shots_hit;
score->p_bonehead_hits -= score->mp_bonehead_hits;
score->s_bonehead_hits -= score->ms_bonehead_hits;
score->bonehead_kills -= score->m_bonehead_kills;
for(idx=0;idx<MAX_SHIP_CLASSES;idx++){
score->kills[idx] = (unsigned short)(score->kills[idx] - score->m_okKills[idx]);
}
// if the player was given a medal, take it back
if ( score->m_medal_earned != -1 ) {
score->medal_counts[score->m_medal_earned]--;
Assert( score->medal_counts[score->m_medal_earned] >= 0 );
}
// if the player was promoted, take it back
if ( score->m_promotion_earned != -1) {
score->rank--;
Assert( score->rank >= 0 );
}
score->flight_time -= (unsigned int)f2fl(Missiontime);
score->last_flown = score->last_backup;
score->missions_flown--;
}
// merge any mission stats accumulated into the alltime stats (as well as updating per campaign stats)
void scoring_level_close(int accepted)
{
// want to calculate any other statistics.
if (The_mission.game_type == MISSION_TYPE_TRAINING){
// call scoring_do_accept
// this will grant any potential medals and then early bail, and
// then we will early bail
scoring_do_accept(&Player->stats);
Pilot.update_stats(&Player->stats, true);
return;
}
if(accepted){
// apply mission stats for all players in the game
int idx;
scoring_struct *sc;
if(Game_mode & GM_MULTIPLAYER){
nprintf(("Network","Storing stats for all players now\n"));
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){
// get the scoring struct
sc = &Net_players[idx].m_player->stats;
scoring_do_accept( sc );
if (Net_player == &Net_players[idx]) {
Pilot.update_stats(sc);
}
}
}
} else {
nprintf(("General","Storing stats now\n"));
scoring_do_accept( &Player->stats );
}
// If this mission doesn't allow promotion or badges
// then be sure that these don't get done. Don't allow promotions or badges when
// playing normally and not in a campaign.
if ( (The_mission.flags[Mission::Mission_Flags::No_promotion]) || ((Game_mode & GM_NORMAL) && !(Game_mode & GM_CAMPAIGN_MODE)) ) {
if ( Player->stats.m_promotion_earned != -1) {
Player->stats.rank--;
Player->stats.m_promotion_earned = -1;
}
// if a badge was earned, take it back
if ( Player->stats.m_badge_earned.size() ){
for (size_t medal = 0; medal < Player->stats.m_badge_earned.size(); medal++) {
Player->stats.medal_counts[Player->stats.m_badge_earned[medal]] = 0;
}
Player->stats.m_badge_earned.clear();
}
}
if ( !(Game_mode & GM_MULTIPLAYER) ) {
Pilot.update_stats(&Player->stats);
}
}
}
// STATS damage, assists recording stuff
void scoring_add_damage(object *ship_objp,object *other_obj,float damage)
{
int found_slot, signature;
int lowest_index,idx;
object *use_obj;
ship *sp;
// multiplayer clients bail here
if(MULTIPLAYER_CLIENT){
return;
}
// if we have no other object, bail
if(other_obj == NULL){
return;
}
// for player kill/assist evaluation, we have to know exactly how much damage really mattered. For example, if
// a ship had 1 hit point left, and the player hit it with a nuke, it doesn't matter that it did 10,000,000
// points of damage, only that 1 point would count
float actual_damage = 0.0f;
// other_obj might not always be the parent of other_obj (in the case of debug code for sure). See
// if the other_obj has a parent, and if so, use the parent. If no parent, see if other_obj is a ship
// and if so, use that ship.
if ( other_obj->parent != -1 ){
use_obj = &Objects[other_obj->parent];
signature = use_obj->signature;
} else {
signature = other_obj->signature;
use_obj = other_obj;
}
// don't count damage done to a ship by himself
if(use_obj == ship_objp){
return;
}
// get a pointer to the ship and add the actual amount of damage done to it
// get the ship object, and determine the _actual_ amount of damage done
sp = &Ships[ship_objp->instance];
// see comments at beginning of function
if(ship_objp->hull_strength < 0.0f){
actual_damage = damage + ship_objp->hull_strength;
} else {
actual_damage = damage;
}
if(actual_damage < 0.0f){
actual_damage = 0.0f;
}
sp->total_damage_received += actual_damage;
// go through and clear out all old damagers
for(idx=0; idx<MAX_DAMAGE_SLOTS; idx++){
if((sp->damage_ship_id[idx] >= 0) && (ship_get_by_signature(sp->damage_ship_id[idx]) < 0)){
sp->damage_ship_id[idx] = -1;
sp->damage_ship[idx] = 0;
}
}
// only evaluate possible kill/assist numbers if the hitting object (use_obj) is a piloted ship (ie, ignore asteroids, etc)
// don't store damage a ship may do to himself
if((ship_objp->type == OBJ_SHIP) && (use_obj->type == OBJ_SHIP)){
found_slot = 0;
// try and find an open slot
for(idx=0;idx<MAX_DAMAGE_SLOTS;idx++){
// if this ship object doesn't exist anymore, use the slot
if((sp->damage_ship_id[idx] == -1) || (ship_get_by_signature(sp->damage_ship_id[idx]) < 0) || (sp->damage_ship_id[idx] == signature) ){
found_slot = 1;
break;
}
}
// if not found (implying all slots are taken), then find the slot with the lowest damage % and use that
if(!found_slot){
lowest_index = 0;
for(idx=0;idx<MAX_DAMAGE_SLOTS;idx++){
if(sp->damage_ship[idx] < sp->damage_ship[lowest_index]){
lowest_index = idx;
}
}
} else {
lowest_index = idx;
}
// fill in the slot damage and damager-index
if(found_slot){
sp->damage_ship[lowest_index] += actual_damage;
} else {
sp->damage_ship[lowest_index] = actual_damage;
}
sp->damage_ship_id[lowest_index] = signature;
}
}
char Scoring_debug_text[4096];
// evaluate a kill on a ship
int scoring_eval_kill(object *ship_objp)
{
float max_damage_pct; // the pct% of total damage the max damage object did
int max_damage_index; // the index into the dying ship's damage_ship[] array corresponding the greatest amount of damage
int killer_sig; // signature of the guy getting credit for the kill (or -1 if none)
int idx,net_player_num;
player *plr; // pointer to a player struct if it was a player who got the kill
net_player *net_plr = NULL;
ship *dead_ship; // the ship which was killed
net_player *dead_plr = NULL;
float scoring_scale_by_damage = 1; // percentage to scale the killer's score by if we score based on the amount of damage caused
int kill_score, assist_score;
bool is_enemy_player = false; // true if the player just killed an enemy player ship
// multiplayer clients bail here
if(MULTIPLAYER_CLIENT){
return -1;
}
// we don't evaluate kills on anything except ships
if(ship_objp->type != OBJ_SHIP){
return -1;
}
if((ship_objp->instance < 0) || (ship_objp->instance >= MAX_SHIPS)){
return -1;
}
// assign the dead ship
dead_ship = &Ships[ship_objp->instance];
// evaluate player deaths
if(Game_mode & GM_MULTIPLAYER){
net_player_num = multi_find_player_by_object(ship_objp);
if(net_player_num != -1){
Net_players[net_player_num].m_player->stats.m_player_deaths++;
nprintf(("Network","Setting player %s deaths to %d\n",Net_players[net_player_num].m_player->callsign,Net_players[net_player_num].m_player->stats.m_player_deaths));
dead_plr = &Net_players[net_player_num];
is_enemy_player = true;
}
} else {
if(ship_objp == Player_obj){
Player->stats.m_player_deaths++;
}
}
net_player_num = -1;
// clear out invalid damager ships
for(idx=0; idx<MAX_DAMAGE_SLOTS; idx++){
if((dead_ship->damage_ship_id[idx] >= 0) && (ship_get_by_signature(dead_ship->damage_ship_id[idx]) < 0)){
dead_ship->damage_ship[idx] = 0.0f;
dead_ship->damage_ship_id[idx] = -1;
}
}
// determine which object did the most damage to the dying object, and how much damage that was
max_damage_index = -1;
for(idx=0;idx<MAX_DAMAGE_SLOTS;idx++){
// bogus ship
if(dead_ship->damage_ship_id[idx] < 0){
continue;
}
// if this slot did more damage then the next highest slot
if((max_damage_index == -1) || (dead_ship->damage_ship[idx] > dead_ship->damage_ship[max_damage_index])){
max_damage_index = idx;
}
}
// doh
if((max_damage_index < 0) || (max_damage_index >= MAX_DAMAGE_SLOTS)){
return -1;
}
// the pct of total damage applied to this ship
max_damage_pct = dead_ship->damage_ship[max_damage_index] / dead_ship->total_damage_received;
CLAMP(max_damage_pct, 0.0f, 1.0f);
// only evaluate if the max damage % is high enough to record a kill and it was done by a valid object
if((max_damage_pct >= Kill_percentage) && (dead_ship->damage_ship_id[max_damage_index] >= 0)){
// set killer_sig for this ship to the signature of the guy who gets credit for the kill
killer_sig = dead_ship->damage_ship_id[max_damage_index];
// set the scale value if we only award 100% score for 100% damage
if (The_mission.ai_profile->flags[AI::Profile_Flags::Kill_scoring_scales_with_damage]) {
scoring_scale_by_damage = max_damage_pct;
}
// null this out for now
plr = NULL;
net_plr = NULL;
// get the player (whether single or multiplayer)
net_player_num = -1;
if(Game_mode & GM_MULTIPLAYER){
net_player_num = multi_find_player_by_signature(killer_sig);
if(net_player_num != -1){
plr = Net_players[net_player_num].m_player;
net_plr = &Net_players[net_player_num];
}
} else {
if(Objects[Player->objnum].signature == killer_sig){
plr = Player;
}
}
// if we found a valid player, evaluate some kill details
if(plr != NULL){
int si_index;
// bogus
if((plr->objnum < 0) || (plr->objnum >= MAX_OBJECTS)){
return -1;
}
// get the ship info index of the ship type of this kill. we need to take ship
// copies into account here.
si_index = dead_ship->ship_info_index;
if (Ship_info[si_index].flags[Ship::Info_Flags::Ship_copy])
{
char temp[NAME_LENGTH];
strcpy_s(temp, Ship_info[si_index].name);
end_string_at_first_hash_symbol(temp);
// Goober5000 - previous error checking (for base ship in ship_parse_post_cleanup()) guarantees that this will be >= 0
si_index = ship_info_lookup(temp);
}
// if he killed a guy on his own team increment his bonehead kills
if((Ships[Objects[plr->objnum].instance].team == dead_ship->team) && !MULTI_DOGFIGHT ){
if (!(The_mission.flags[Mission::Mission_Flags::No_traitor])) {
plr->stats.m_bonehead_kills++;
kill_score = -(int)(dead_ship->score * scoring_get_scale_factor());
plr->stats.m_score += kill_score;
if(net_plr != NULL ) {
multi_team_maybe_add_score(-(dead_ship->score), net_plr->p_info.team);
}
}
}
// otherwise increment his valid kill count and score
else {
// dogfight mode
if(MULTI_DOGFIGHT && (multi_find_player_by_object(ship_objp) < 0)){
// don't add a kill for dogfight kills on non-players
} else {
plr->stats.m_okKills[si_index]++;
plr->stats.m_kill_count_ok++;
// only computer controlled enemies should scale with difficulty
if (is_enemy_player) {
kill_score = (int)(dead_ship->score * scoring_scale_by_damage);
}
else {
kill_score = (int)(dead_ship->score * scoring_get_scale_factor() * scoring_scale_by_damage);
}
plr->stats.m_score += kill_score;
hud_gauge_popup_start(HUD_KILLS_GAUGE);
#ifdef SCORING_DEBUG
char kill_score_text[1024] = "";
sprintf(kill_score_text, "SCORING : %s killed a ship worth %d points and gets %d pts for the kill\n", plr->callsign, dead_ship->score, kill_score);
if (MULTIPLAYER_MASTER) {
send_game_chat_packet(Net_player, kill_score_text, MULTI_MSG_ALL);
}
HUD_printf(kill_score_text);
mprintf((kill_score_text));
#endif
// multiplayer
if(net_plr != NULL){
multi_team_maybe_add_score(dead_ship->score , net_plr->p_info.team);
// award teammates % of score value for big ship kills
// not in dogfight tho
// and not if there is no assist threshold (as otherwise assists could get higher scores than kills)
if (!(Netgame.type_flags & NG_TYPE_DOGFIGHT) && (Ship_info[dead_ship->ship_info_index].is_big_or_huge())) {
for (idx=0; idx<MAX_PLAYERS; idx++) {
if (MULTI_CONNECTED(Net_players[idx]) && (Net_players[idx].p_info.team == net_plr->p_info.team) && (&Net_players[idx] != net_plr)) {
assist_score = (int)(dead_ship->score * The_mission.ai_profile->assist_award_percentage_scale[Game_skill_level]);
Net_players[idx].m_player->stats.m_score += assist_score;
#ifdef SCORING_DEBUG
// DEBUG CODE TO TEST NEW SCORING
char score_text[1024] = "";
sprintf(score_text, "SCORING : All team mates get %d pts for helping kill the capship\n", assist_score);
send_game_chat_packet(Net_player, score_text, MULTI_MSG_ALL);
HUD_printf(score_text);
mprintf((score_text));
#endif
}
}
}
// death message
if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (net_plr != NULL) && (dead_plr != NULL) && (net_plr->m_player != NULL) && (dead_plr->m_player != NULL)){
char dead_text[1024] = "";
sprintf(dead_text, "%s gets the kill for %s", net_plr->m_player->callsign, dead_plr->m_player->callsign);
send_game_chat_packet(Net_player, dead_text, MULTI_MSG_ALL, NULL, NULL, 2);
HUD_printf("%s", dead_text);
}
}
}
}
// increment his all-encompassing kills
plr->stats.m_kills[si_index]++;
plr->stats.m_kill_count++;
// update everyone on this guy's kills if this is multiplayer
if(MULTIPLAYER_MASTER && (net_player_num != -1)){
// send appropriate stats
if(Netgame.type_flags & NG_TYPE_DOGFIGHT){
// evaluate dogfight kills
multi_df_eval_kill(&Net_players[net_player_num], ship_objp);
// update stats
send_player_stats_block_packet(&Net_players[net_player_num], STATS_DOGFIGHT_KILLS);
} else {
send_player_stats_block_packet(&Net_players[net_player_num], STATS_MISSION_KILLS);
}
}
}
} else {
// set killer_sig for this ship to -1, indicating no one got the kill for it
killer_sig = -1;
}
// pass in the guy who got the credit for the kill (if any), so that he doesn't also
// get credit for an assist
scoring_eval_assists(dead_ship,killer_sig, is_enemy_player);
#ifdef SCORING_DEBUG
if (Game_mode & GM_MULTIPLAYER) {
char buf[256];
sprintf(Scoring_debug_text, "SCORING : %s killed.\nDamage by ship:\n\n", Ship_info[dead_ship->ship_info_index].name);
// show damage done by player
for (int i=0; i<MAX_DAMAGE_SLOTS; i++) {
int net_player_num = multi_find_player_by_signature(dead_ship->damage_ship_id[i]);
if (net_player_num != -1) {
plr = Net_players[net_player_num].m_player;
sprintf(buf, "%s: %f", plr->callsign, dead_ship->damage_ship[i]);
if (dead_ship->damage_ship_id[i] == killer_sig ) {
strcat_s(buf, " KILLER\n");
} else {
strcat_s(buf, "\n");
}
strcat_s(Scoring_debug_text, buf);
}
}
mprintf ((Scoring_debug_text));
}
#endif
return max_damage_index;
}
//evaluate a kill on a weapon, right now this is only called on bombs. -Halleck
int scoring_eval_kill_on_weapon(object *weapon_obj, object *other_obj) {
int killer_sig; // signature of the guy getting credit for the kill (or -1 if none)
int net_player_num;
player *plr; // pointer to a player struct if it was a player who got the kill
net_player *net_plr = NULL;
int kill_score;
// multiplayer clients bail here
if(MULTIPLAYER_CLIENT){
return -1;
}
// we don't evaluate kills on anything except weapons
// also make sure there was a killer, and that it was a ship
if((weapon_obj->type != OBJ_WEAPON) || (weapon_obj->instance < 0) || (weapon_obj->instance >= MAX_WEAPONS)
|| (other_obj == nullptr) || (other_obj->type != OBJ_WEAPON) || (other_obj->instance < 0) || (other_obj->instance >= MAX_WEAPONS)
|| (other_obj->parent == -1) || (Objects[other_obj->parent].type != OBJ_SHIP)) {
return -1;
}
weapon *dead_wp = &Weapons[weapon_obj->instance]; // the weapon that was killed
weapon_info *dead_wip = &Weapon_info[dead_wp->weapon_info_index]; // info on the weapon that was killed
// we don't evaluate kills on anything except bombs, currently. -Halleck
if(!(dead_wip->wi_flags[Weapon::Info_Flags::Bomb])) {
return -1;
}
// set killer_sig for this weapon to the signature of the guy who gets credit for the kill
killer_sig = Objects[other_obj->parent].signature;
// only evaluate if the kill was done by a valid object
if(killer_sig >= 0) {
// null this out for now
plr = NULL;
net_plr = NULL;
// get the player (whether single or multiplayer)
net_player_num = -1;
if(Game_mode & GM_MULTIPLAYER){
net_player_num = multi_find_player_by_signature(killer_sig);
if(net_player_num != -1){
plr = Net_players[net_player_num].m_player;
net_plr = &Net_players[net_player_num];
}
} else {
if(Objects[Player->objnum].signature == killer_sig){
plr = Player;
}
}
// if we found a valid player, evaluate some kill details
if(plr != NULL){
// bogus
if((plr->objnum < 0) || (plr->objnum >= MAX_OBJECTS)){
return -1;
}
// if he killed a bomb on his own team increment his bonehead kills
if((Ships[Objects[plr->objnum].instance].team == dead_wp->team) && !MULTI_DOGFIGHT ){
if (!(The_mission.flags[Mission::Mission_Flags::No_traitor])) {
plr->stats.m_bonehead_kills++;
kill_score = -(int)(dead_wip->score * scoring_get_scale_factor());
plr->stats.m_score += kill_score;
if(net_plr != NULL ) {
multi_team_maybe_add_score(-(dead_wip->score), net_plr->p_info.team);
}
}
}
// otherwise increment his valid kill count and score
else {
// dogfight mode
if(MULTI_DOGFIGHT && (multi_find_player_by_object(weapon_obj) < 0)){
// don't add a kill for dogfight kills on non-players
} else {
// bombs don't scale with difficulty at the moment. If we change this we want to *scoring_get_scale_factor()
kill_score = dead_wip->score;
plr->stats.m_score += kill_score;
hud_gauge_popup_start(HUD_KILLS_GAUGE);
#ifdef SCORING_DEBUG
char kill_score_text[1024] = "";
sprintf(kill_score_text, "SCORING : %s killed a bomb worth %i points and gets %i pts for the kill", plr->callsign, dead_wip->score, kill_score);
if (MULTIPLAYER_MASTER) {
send_game_chat_packet(Net_player, kill_score_text, MULTI_MSG_ALL);
}
HUD_printf(kill_score_text);
mprintf((kill_score_text));
#endif
// multiplayer
if(net_plr != NULL){
multi_team_maybe_add_score(dead_wip->score , net_plr->p_info.team);
}
}
}
}
}
#ifdef SCORING_DEBUG
if (Game_mode & GM_MULTIPLAYER) {
sprintf(Scoring_debug_text, "SCORING : %s killed.\nKilled by player:\n", dead_wip->name);
int net_player_num = multi_find_player_by_signature(killer_sig);
if (net_player_num != -1) {
plr = Net_players[net_player_num].m_player;
char buf[256];
sprintf(buf, " %s\n", plr->callsign);
strcat_s(Scoring_debug_text, buf);
}
mprintf ((Scoring_debug_text));
}
#endif
return killer_sig;
}
// kill_id is the object signature of the guy who got the credit for the kill (may be -1, if no one got it)
// this is to ensure that you don't also get an assist if you get the kill.
void scoring_eval_assists(ship *sp,int killer_sig, bool is_enemy_player)
{
int idx;
player *plr;
float scoring_scale_by_damage = 1; // percentage to scale the score by if we score based on the amount of damage caused
int assist_score;
int net_player_num;
float scoring_scale_factor;
// multiplayer clients bail here
if(MULTIPLAYER_CLIENT){
return;
}
// evaluate each damage slot to see if it did enough to give the assis
for(idx=0;idx<MAX_DAMAGE_SLOTS;idx++){
// if this slot did enough damage to get an assist
if(((sp->damage_ship[idx]/sp->total_damage_received) >= Assist_percentage) || (The_mission.ai_profile->flags[AI::Profile_Flags::Assist_scoring_scales_with_damage])){
// get the player which did this damage (if any)
plr = NULL;
// multiplayer
if(Game_mode & GM_MULTIPLAYER){
net_player_num = multi_find_player_by_signature(sp->damage_ship_id[idx]);
if(net_player_num != -1){
plr = Net_players[net_player_num].m_player;
}
}
// single player
else {
if(Objects[Player->objnum].signature == sp->damage_ship_id[idx]){
plr = Player;
}
}
// if we found a player, give him the assist if he attacks it
if ((plr != NULL) && (iff_x_attacks_y(Ships[Objects[plr->objnum].instance].team, sp->team)) && (killer_sig != Objects[plr->objnum].signature))
{
// player has to equal the threshold to get an assist
if ((sp->damage_ship[idx]/sp->total_damage_received) >= Assist_percentage) {
plr->stats.m_assists++;
nprintf(("Network","-==============GAVE PLAYER %s AN ASSIST=====================-\n",plr->callsign));
}
// Don't scale in TvT and dogfight
if (is_enemy_player) {
Assert(Game_mode & GM_MULTIPLAYER);
scoring_scale_factor = 1.0f;
}
else {
scoring_scale_factor = scoring_get_scale_factor();
}
// maybe award assist points based on damage
if (The_mission.ai_profile->flags[AI::Profile_Flags::Assist_scoring_scales_with_damage]) {
scoring_scale_by_damage = (sp->damage_ship[idx]/sp->total_damage_received);
assist_score = (int)(sp->score * scoring_scale_factor * scoring_scale_by_damage);
plr->stats.m_score += assist_score;
}
// otherwise give the points based on the percentage in the mission file
else {
assist_score = (int)(sp->score * sp->assist_score_pct * scoring_scale_factor );
plr->stats.m_score += assist_score;
}
#ifdef SCORING_DEBUG
// DEBUG CODE TO TEST NEW SCORING
char score_text[1024] = "";
sprintf(score_text, "SCORING : %s gets %d pts for getting an assist\n", plr->callsign, assist_score);
if (MULTIPLAYER_MASTER) {
send_game_chat_packet(Net_player, score_text, MULTI_MSG_ALL);
}
HUD_printf(score_text);
mprintf ((score_text));
#endif
}
}
}
}
// eval a hit on an object (for primary and secondary hit purposes)
void scoring_eval_hit(object *hit_obj, object *other_obj,int from_blast)
{
// multiplayer clients bail here
if(MULTIPLAYER_CLIENT){
return;
}
// only evaluate hits on ships, asteroids, and weapons! -Halleck
if((hit_obj->type != OBJ_SHIP) && (hit_obj->type != OBJ_ASTEROID) && (hit_obj->type != OBJ_WEAPON)){
return;
}
// if the other_obj == NULL, we can't evaluate where it came from, so bail here
if(other_obj == NULL){
return;
}
// other bogus situtations
if(other_obj->instance < 0){
return;
}
if((other_obj->type == OBJ_WEAPON) && !(Weapons[other_obj->instance].weapon_flags[Weapon::Weapon_Flags::Already_applied_stats])){
// bogus weapon
if(other_obj->instance >= MAX_WEAPONS){
return;
}
// bogus parent
if(other_obj->parent < 0){
return;
}
if(other_obj->parent >= MAX_OBJECTS){
return;
}
if(Objects[other_obj->parent].type != OBJ_SHIP){
return;
}
if((Objects[other_obj->parent].instance < 0) || (Objects[other_obj->parent].instance >= MAX_SHIPS)){
return;
}
//Only evaluate hits on bomb weapons. -Halleck
bool hit_obj_is_bomb = false;
if(hit_obj->type == OBJ_WEAPON){
//Hit weapon is bogus
if (hit_obj->instance >= MAX_WEAPONS) {
return;
}
hit_obj_is_bomb = (Weapon_info[Weapons[hit_obj->instance].weapon_info_index].wi_flags[Weapon::Info_Flags::Bomb]) ? true : false;
//If it's not a bomb but just a regular weapon, we don't care about it (for now, at least.) -Halleck
if (!hit_obj_is_bomb) {
return;
}
}
int is_bonehead = 0;
int sub_type = Weapon_info[Weapons[other_obj->instance].weapon_info_index].subtype;
// determine if this was a bonehead hit or not
if(hit_obj->type == OBJ_SHIP){
is_bonehead = Ships[hit_obj->instance].team==Ships[Objects[other_obj->parent].instance].team ? 1 : 0;
} else if (hit_obj_is_bomb) {
is_bonehead = Weapons[hit_obj->instance].team==Ships[Objects[other_obj->parent].instance].team ? 1 : 0;
}
// can't have a bonehead hit on an asteroid
else {
is_bonehead = 0;
}
// set the flag indicating that we've already applied a "stats" hit for this weapon
// Weapons[other_obj->instance].weapon_flags |= WF_ALREADY_APPLIED_STATS;
// in multiplayer -- only the server records the stats
if( Game_mode & GM_MULTIPLAYER ) {
if ( Net_player->flags & NETINFO_FLAG_AM_MASTER ) {
int player_num;
// get the player num of the parent object. A player_num of -1 means that the
// parent of this object was not a player
player_num = multi_find_player_by_object( &Objects[other_obj->parent] );
if ( player_num != -1 ) {
switch(sub_type) {
case WP_LASER :
if(is_bonehead){
Net_players[player_num].m_player->stats.mp_bonehead_hits++;
} else {
Net_players[player_num].m_player->stats.mp_shots_hit++;
}
// Assert( Net_players[player_num].player->stats.mp_shots_hit <= Net_players[player_num].player->stats.mp_shots_fired );
break;
case WP_MISSILE :
// friendly hit, once it hits a friendly, its done
if(is_bonehead){
if(!from_blast){
Net_players[player_num].m_player->stats.ms_bonehead_hits++;
}
}
// hostile hit
else {
// if its a bomb, count every bit of damage it does
if(Weapon_info[Weapons[other_obj->instance].weapon_info_index].wi_flags[Weapon::Info_Flags::Bomb]){
// once we get impact damage, stop keeping track of it
Net_players[player_num].m_player->stats.ms_shots_hit++;
}
// if its not a bomb, only count impact damage
else {
if(!from_blast){
Net_players[player_num].m_player->stats.ms_shots_hit++;
}
}
}
default :
break;
}
}
}
} else {
if(Player_obj == &(Objects[other_obj->parent])){
switch(sub_type){
case WP_LASER :
if(is_bonehead){
Player->stats.mp_bonehead_hits++;
} else {
Player->stats.mp_shots_hit++;
}
break;
case WP_MISSILE :
// friendly hit, once it hits a friendly, its done
if(is_bonehead){
if(!from_blast){
Player->stats.ms_bonehead_hits++;
}
}
// hostile hit
else {
// if its a bomb, count every bit of damage it does
if(Weapon_info[Weapons[other_obj->instance].weapon_info_index].wi_flags[Weapon::Info_Flags::Bomb]){
// once we get impact damage, stop keeping track of it
Player->stats.ms_shots_hit++;
}
// if its not a bomb, only count impact damage
else {
if(!from_blast){
Player->stats.ms_shots_hit++;
}
}
}
break;
default :
break;
}
}
}
}
}
// get a scaling factor for adding/subtracting from mission score
float scoring_get_scale_factor()
{
// multiplayer dogfight. don't scale anything
if(MULTI_DOGFIGHT){
return 1.0f;
}
// check for bogus Skill_level values
Assert((Game_skill_level >= 0) && (Game_skill_level < NUM_SKILL_LEVELS));
if((Game_skill_level < 0) || (Game_skill_level > NUM_SKILL_LEVELS-1)){
return Scoring_scale_factors[0];
}
// return the correct scale value
return Scoring_scale_factors[Game_skill_level];
}
// ----------------------------------------------------------------------------------------
// DCF functions
//
// bash the passed player to the specified rank
void scoring_bash_rank(player *pl,int rank)
{
// if this is an invalid rank, do nothing
if((rank < RANK_ENSIGN) || (rank > RANK_ADMIRAL)){
nprintf(("General","Could not bash player rank - invalid value!!!\n"));
return;
}
// set the player's score and rank
pl->stats.score = Ranks[rank].points + 1;
pl->stats.rank = rank;
}
DCF(rank, "changes player rank")
{
int rank;
if (dc_optional_string_either("help", "--help")) {
dc_printf("Usage: rank <index>\n");
dc_printf(" <index> The rank index you wish to have. For retail ranks, these correspond to:\n");
dc_printf("\t0 : Ensign\n");
dc_printf("\t1 : Lieutenant Junior Grade\n");
dc_printf("\t2 : Lietenant\n");
dc_printf("\t3 : Lieutenant Commander\n");
dc_printf("\t4 : Commander\n");
dc_printf("\t5 : Captain\n");
dc_printf("\t6 : Commodore\n");
dc_printf("\t7 : Rear Admiral\n");
dc_printf("\t8 : Vice Admiral\n");
dc_printf("\t9 : Admiral\n\n");
return;
}
if (dc_optional_string_either("status", "--status") || dc_optional_string_either("?", "--?")) {
if (Player != NULL) {
dc_printf("Current rank is %i\n", Player->stats.rank);
} else {
dc_printf("Error! Current Player not active or loaded\n");
}
}
dc_stuff_int(&rank);
// parse the argument and change things around accordingly
if (Player != NULL) {
scoring_bash_rank(Player, rank);
} else {
dc_printf("Error! Current Player not active or loaded\n");
}
}
void scoring_close()
{
for(int i = 0; i<NUM_RANKS; i++) {
Ranks[i].promotion_text.clear();
}
Traitor.debriefing_text.clear();
Traitor.recommendation_text.clear();
}
|
// Copyright (c) 2017-2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "device_ledger.hpp"
#include "log.hpp"
#include "ringct/rctOps.h"
#include "cryptonote_basic/account.h"
#include "cryptonote_basic/subaddress_index.h"
#include <boost/thread/locks.hpp>
#include <boost/thread/lock_guard.hpp>
namespace hw {
namespace ledger {
#ifdef WITH_DEVICE_LEDGER
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "device.ledger"
/* ===================================================================== */
/* === Debug ==== */
/* ===================================================================== */
#ifdef WIN32
static char *pcsc_stringify_error(LONG rv) {
static __thread char out[20];
sprintf_s(out, sizeof(out), "0x%08lX", rv);
return out;
}
#endif
void set_apdu_verbose(bool verbose) {
apdu_verbose = verbose;
}
#define TRACKD MTRACE("hw")
#define ASSERT_RV(rv) CHECK_AND_ASSERT_THROW_MES((rv)==SCARD_S_SUCCESS, "Fail SCard API : (" << (rv) << ") "<< pcsc_stringify_error(rv)<<" Device="<<this->id<<", hCard="<<hCard<<", hContext="<<hContext);
#define ASSERT_SW(sw,ok,msk) CHECK_AND_ASSERT_THROW_MES(((sw)&(mask))==(ok), "Wrong Device Status : SW=" << std::hex << (sw) << " (EXPECT=" << std::hex << (ok) << ", MASK=" << std::hex << (mask) << ")") ;
#define ASSERT_T0(exp) CHECK_AND_ASSERT_THROW_MES(exp, "Protocol assert failure: "#exp ) ;
#define ASSERT_X(exp,msg) CHECK_AND_ASSERT_THROW_MES(exp, msg);
#ifdef DEBUG_HWDEVICE
crypto::secret_key dbg_viewkey;
crypto::secret_key dbg_spendkey;
#endif
/* ===================================================================== */
/* === Keymap ==== */
/* ===================================================================== */
ABPkeys::ABPkeys(const rct::key& A, const rct::key& B, const bool is_subaddr, const size_t real_output_index, const rct::key& P, const rct::key& AK) {
Aout = A;
Bout = B;
is_subaddress = is_subaddr;
index = real_output_index;
Pout = P;
AKout = AK;
}
ABPkeys::ABPkeys(const ABPkeys& keys) {
Aout = keys.Aout;
Bout = keys.Bout;
is_subaddress = keys.is_subaddress;
index = keys.index;
Pout = keys.Pout;
AKout = keys.AKout;
}
bool Keymap::find(const rct::key& P, ABPkeys& keys) const {
size_t sz = ABP.size();
for (size_t i=0; i<sz; i++) {
if (ABP[i].Pout == P) {
keys = ABP[i];
return true;
}
}
return false;
}
void Keymap::add(const ABPkeys& keys) {
ABP.push_back(keys);
}
void Keymap::clear() {
ABP.clear();
}
#ifdef DEBUG_HWDEVICE
void Keymap::log() {
log_message("keymap", "content");
size_t sz = ABP.size();
for (size_t i=0; i<sz; i++) {
log_message(" keymap", std::to_string(i));
log_hexbuffer(" Aout", (char*)ABP[i].Aout.bytes, 32);
log_hexbuffer(" Bout", (char*)ABP[i].Bout.bytes, 32);
log_message (" is_sub", std::to_string(ABP[i].is_subaddress));
log_message (" index", std::to_string(ABP[i].index));
log_hexbuffer(" Pout", (char*)ABP[i].Pout.bytes, 32);
}
}
#endif
/* ===================================================================== */
/* === Internal Helpers ==== */
/* ===================================================================== */
static bool is_fake_view_key(const crypto::secret_key &sec) {
return sec == crypto::null_skey;
}
bool operator==(const crypto::key_derivation &d0, const crypto::key_derivation &d1) {
return !memcmp(&d0, &d1, sizeof(d0));
}
/* ===================================================================== */
/* === Device ==== */
/* ===================================================================== */
static int device_id = 0;
#define INS_NONE 0x00
#define INS_RESET 0x02
#define INS_GET_KEY 0x20
#define INS_PUT_KEY 0x22
#define INS_GET_CHACHA8_PREKEY 0x24
#define INS_VERIFY_KEY 0x26
#define INS_SECRET_KEY_TO_PUBLIC_KEY 0x30
#define INS_GEN_KEY_DERIVATION 0x32
#define INS_DERIVATION_TO_SCALAR 0x34
#define INS_DERIVE_PUBLIC_KEY 0x36
#define INS_DERIVE_SECRET_KEY 0x38
#define INS_GEN_KEY_IMAGE 0x3A
#define INS_SECRET_KEY_ADD 0x3C
#define INS_SECRET_KEY_SUB 0x3E
#define INS_GENERATE_KEYPAIR 0x40
#define INS_SECRET_SCAL_MUL_KEY 0x42
#define INS_SECRET_SCAL_MUL_BASE 0x44
#define INS_DERIVE_SUBADDRESS_PUBLIC_KEY 0x46
#define INS_GET_SUBADDRESS 0x48
#define INS_GET_SUBADDRESS_SPEND_PUBLIC_KEY 0x4A
#define INS_GET_SUBADDRESS_SECRET_KEY 0x4C
#define INS_OPEN_TX 0x70
#define INS_SET_SIGNATURE_MODE 0x72
#define INS_GET_ADDITIONAL_KEY 0x74
#define INS_STEALTH 0x76
#define INS_BLIND 0x78
#define INS_UNBLIND 0x7A
#define INS_VALIDATE 0x7C
#define INS_MLSAG 0x7E
#define INS_CLOSE_TX 0x80
#define INS_GET_RESPONSE 0xc0
void device_ledger::logCMD() {
if (apdu_verbose) {
char strbuffer[1024];
snprintf(strbuffer, sizeof(strbuffer), "%.02x %.02x %.02x %.02x %.02x ",
this->buffer_send[0],
this->buffer_send[1],
this->buffer_send[2],
this->buffer_send[3],
this->buffer_send[4]
);
const size_t len = strlen(strbuffer);
buffer_to_str(strbuffer+len, sizeof(strbuffer)-len, (char*)(this->buffer_send+5), this->length_send-5);
MDEBUG( "CMD :" << strbuffer);
}
}
void device_ledger::logRESP() {
if (apdu_verbose) {
char strbuffer[1024];
snprintf(strbuffer, sizeof(strbuffer), "%.02x%.02x ",
this->buffer_recv[this->length_recv-2],
this->buffer_recv[this->length_recv-1]
);
const size_t len = strlen(strbuffer);
buffer_to_str(strbuffer+len, sizeof(strbuffer)-len, (char*)(this->buffer_recv), this->length_recv-2);
MDEBUG( "RESP :" << strbuffer);
}
}
/* -------------------------------------------------------------- */
device_ledger::device_ledger() {
this->id = device_id++;
this->hCard = 0;
this->hContext = 0;
this->reset_buffer();
this->mode = NONE;
this->has_view_key = false;
MDEBUG( "Device "<<this->id <<" Created");
}
device_ledger::~device_ledger() {
this->release();
MDEBUG( "Device "<<this->id <<" Destroyed");
}
/* ======================================================================= */
/* LOCKER */
/* ======================================================================= */
//automatic lock one more level on device ensuring the current thread is allowed to use it
#define AUTO_LOCK_CMD() \
/* lock both mutexes without deadlock*/ \
boost::lock(device_locker, command_locker); \
/* make sure both already-locked mutexes are unlocked at the end of scope */ \
boost::lock_guard<boost::recursive_mutex> lock1(device_locker, boost::adopt_lock); \
boost::lock_guard<boost::mutex> lock2(command_locker, boost::adopt_lock)
//lock the device for a long sequence
void device_ledger::lock(void) {
MDEBUG( "Ask for LOCKING for device "<<this->name << " in thread ");
device_locker.lock();
MDEBUG( "Device "<<this->name << " LOCKed");
}
//lock the device for a long sequence
bool device_ledger::try_lock(void) {
MDEBUG( "Ask for LOCKING(try) for device "<<this->name << " in thread ");
bool r = device_locker.try_lock();
if (r) {
MDEBUG( "Device "<<this->name << " LOCKed(try)");
} else {
MDEBUG( "Device "<<this->name << " not LOCKed(try)");
}
return r;
}
//lock the device for a long sequence
void device_ledger::unlock(void) {
try {
MDEBUG( "Ask for UNLOCKING for device "<<this->name << " in thread ");
} catch (...) {
}
device_locker.unlock();
MDEBUG( "Device "<<this->name << " UNLOCKed");
}
/* ======================================================================= */
/* MISC */
/* ======================================================================= */
bool device_ledger::reset() {
int offset;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_RESET;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
return true;
}
unsigned int device_ledger::exchange(unsigned int ok, unsigned int mask) {
LONG rv;
unsigned int sw;
ASSERT_T0(this->length_send <= BUFFER_SEND_SIZE);
logCMD();
this->length_recv = BUFFER_RECV_SIZE;
rv = SCardTransmit(this->hCard,
SCARD_PCI_T0, this->buffer_send, this->length_send,
NULL, this->buffer_recv, &this->length_recv);
ASSERT_RV(rv);
ASSERT_T0(this->length_recv >= 2);
ASSERT_T0(this->length_recv <= BUFFER_RECV_SIZE);
logRESP();
sw = (this->buffer_recv[this->length_recv-2]<<8) | this->buffer_recv[this->length_recv-1];
ASSERT_SW(sw,ok,msk);
return sw;
}
void device_ledger::reset_buffer() {
this->length_send = 0;
memset(this->buffer_send, 0, BUFFER_SEND_SIZE);
this->length_recv = 0;
memset(this->buffer_recv, 0, BUFFER_RECV_SIZE);
}
/* ======================================================================= */
/* SETUP/TEARDOWN */
/* ======================================================================= */
bool device_ledger::set_name(const std::string & name) {
this->name = name;
return true;
}
const std::string device_ledger::get_name() const {
if (this->full_name.empty() || (this->hCard == 0)) {
return std::string("<disconnected:").append(this->name).append(">");
}
return this->full_name;
}
bool device_ledger::init(void) {
#ifdef DEBUG_HWDEVICE
this->controle_device = &hw::get_device("default");
#endif
LONG rv;
this->release();
rv = SCardEstablishContext(SCARD_SCOPE_SYSTEM,0,0, &this->hContext);
ASSERT_RV(rv);
MDEBUG( "Device "<<this->id <<" SCardContext created: hContext="<<this->hContext);
this->hCard = 0;
return true;
}
bool device_ledger::release() {
this->disconnect();
if (this->hContext) {
SCardReleaseContext(this->hContext);
MDEBUG( "Device "<<this->id <<" SCardContext released: hContext="<<this->hContext);
this->hContext = 0;
this->full_name.clear();
}
return true;
}
bool device_ledger::connect(void) {
BYTE pbAtr[MAX_ATR_SIZE];
LPSTR mszReaders;
DWORD dwReaders;
LONG rv;
DWORD dwState, dwProtocol, dwAtrLen, dwReaderLen;
this->disconnect();
#ifdef SCARD_AUTOALLOCATE
dwReaders = SCARD_AUTOALLOCATE;
rv = SCardListReaders(this->hContext, NULL, (LPSTR)&mszReaders, &dwReaders);
#else
dwReaders = 0;
rv = SCardListReaders(this->hContext, NULL, NULL, &dwReaders);
if (rv != SCARD_S_SUCCESS)
return false;
mszReaders = (LPSTR)calloc(dwReaders, sizeof(char));
rv = SCardListReaders(this->hContext, NULL, mszReaders, &dwReaders);
#endif
if (rv == SCARD_S_SUCCESS) {
char* p;
const char* prefix = this->name.c_str();
p = mszReaders;
MDEBUG( "Looking for " << std::string(prefix));
while (*p) {
MDEBUG( "Device Found: " << std::string(p));
if ((strncmp(prefix, p, strlen(prefix))==0)) {
MDEBUG( "Device Match: " << std::string(p));
if ((rv = SCardConnect(this->hContext,
p, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0,
&this->hCard, &dwProtocol))!=SCARD_S_SUCCESS) {
break;
}
MDEBUG( "Device "<<this->id <<" Connected: hCard="<<this->hCard);
dwAtrLen = sizeof(pbAtr);
if ((rv = SCardStatus(this->hCard, NULL, &dwReaderLen, &dwState, &dwProtocol, pbAtr, &dwAtrLen))!=SCARD_S_SUCCESS) {
break;
}
MDEBUG( "Device "<<this->id <<" Status OK");
rv = SCARD_S_SUCCESS ;
this->full_name = std::string(p);
break;
}
p += strlen(p) +1;
}
}
if (rv == SCARD_S_SUCCESS && mszReaders) {
#ifdef SCARD_AUTOALLOCATE
SCardFreeMemory(this->hContext, mszReaders);
#else
free(mszReaders);
#endif
mszReaders = NULL;
}
if (rv != SCARD_S_SUCCESS) {
if ( hCard) {
SCardDisconnect(this->hCard, SCARD_UNPOWER_CARD);
MDEBUG( "Device "<<this->id <<" disconnected: hCard="<<this->hCard);
this->hCard = 0;
}
}
ASSERT_RV(rv);
this->reset();
#ifdef DEBUG_HWDEVICE
cryptonote::account_public_address pubkey;
this->get_public_address(pubkey);
#endif
crypto::secret_key vkey;
crypto::secret_key skey;
this->get_secret_keys(vkey,skey);
return rv==SCARD_S_SUCCESS;
}
bool device_ledger::disconnect() {
if (this->hCard) {
SCardDisconnect(this->hCard, SCARD_UNPOWER_CARD);
MDEBUG( "Device "<<this->id <<" disconnected: hCard="<<this->hCard);
this->hCard = 0;
}
return true;
}
bool device_ledger::set_mode(device_mode mode) {
AUTO_LOCK_CMD();
int offset;
reset_buffer();
switch(mode) {
case TRANSACTION_CREATE_REAL:
case TRANSACTION_CREATE_FAKE:
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_SET_SIGNATURE_MODE;
this->buffer_send[2] = 0x01;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//account
this->buffer_send[offset] = mode;
offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
this->mode = mode;
break;
case TRANSACTION_PARSE:
case NONE:
this->mode = mode;
break;
default:
CHECK_AND_ASSERT_THROW_MES(false, " device_ledger::set_mode(unsigned int mode): invalid mode: "<<mode);
}
MDEBUG("Switch to mode: " <<mode);
return true;
}
/* ======================================================================= */
/* WALLET & ADDRESS */
/* ======================================================================= */
bool device_ledger::get_public_address(cryptonote::account_public_address &pubkey){
AUTO_LOCK_CMD();
int offset;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GET_KEY;
this->buffer_send[2] = 0x01;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(pubkey.m_view_public_key.data, this->buffer_recv, 32);
memmove(pubkey.m_spend_public_key.data, this->buffer_recv+32, 32);
return true;
}
bool device_ledger::get_secret_keys(crypto::secret_key &vkey , crypto::secret_key &skey) {
AUTO_LOCK_CMD();
//secret key are represented as fake key on the wallet side
memset(vkey.data, 0x00, 32);
memset(skey.data, 0xFF, 32);
//spcialkey, normal conf handled in decrypt
int offset;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GET_KEY;
this->buffer_send[2] = 0x02;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//View key is retrievied, if allowed, to speed up blockchain parsing
memmove(this->viewkey.data, this->buffer_recv+0, 32);
if (is_fake_view_key(this->viewkey)) {
MDEBUG("Have Not view key");
this->has_view_key = false;
} else {
MDEBUG("Have view key");
this->has_view_key = true;
}
#ifdef DEBUG_HWDEVICE
memmove(dbg_viewkey.data, this->buffer_recv+0, 32);
memmove(dbg_spendkey.data, this->buffer_recv+32, 32);
#endif
return true;
}
bool device_ledger::generate_chacha_key(const cryptonote::account_keys &keys, crypto::chacha_key &key) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
crypto::chacha_key key_x;
cryptonote::account_keys keys_x = hw::ledger::decrypt(keys);
this->controle_device->generate_chacha_key(keys_x, key_x);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GET_CHACHA8_PREKEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
char prekey[200];
memmove(prekey, &this->buffer_recv[0], 200);
crypto::generate_chacha_key_prehashed(&prekey[0], sizeof(prekey), key);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("generate_chacha_key_prehashed", "key", (char*)key_x.data(), (char*)key.data());
#endif
return true;
}
/* ======================================================================= */
/* SUB ADDRESS */
/* ======================================================================= */
bool device_ledger::derive_subaddress_public_key(const crypto::public_key &pub, const crypto::key_derivation &derivation, const std::size_t output_index, crypto::public_key &derived_pub){
AUTO_LOCK_CMD();
#ifdef DEBUG_HWDEVICE
const crypto::public_key pub_x = pub;
crypto::key_derivation derivation_x;
if ((this->mode == TRANSACTION_PARSE) && has_view_key) {
derivation_x = derivation;
} else {
derivation_x = hw::ledger::decrypt(derivation);
}
const std::size_t output_index_x = output_index;
crypto::public_key derived_pub_x;
hw::ledger::log_hexbuffer("derive_subaddress_public_key: [[IN]] pub ", pub_x.data, 32);
hw::ledger::log_hexbuffer("derive_subaddress_public_key: [[IN]] derivation", derivation_x.data, 32);
hw::ledger::log_message ("derive_subaddress_public_key: [[IN]] index ", std::to_string((int)output_index_x));
this->controle_device->derive_subaddress_public_key(pub_x, derivation_x,output_index_x,derived_pub_x);
hw::ledger::log_hexbuffer("derive_subaddress_public_key: [[OUT]] derived_pub", derived_pub_x.data, 32);
#endif
if ((this->mode == TRANSACTION_PARSE) && has_view_key) {
//If we are in TRANSACTION_PARSE, the given derivation has been retrieved uncrypted (wihtout the help
//of the device), so continue that way.
MDEBUG( "derive_subaddress_public_key : PARSE mode with known viewkey");
crypto::derive_subaddress_public_key(pub, derivation, output_index,derived_pub);
} else {
int offset =0;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_DERIVE_SUBADDRESS_PUBLIC_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//pub
memmove(this->buffer_send+offset, pub.data, 32);
offset += 32;
//derivation
memmove(this->buffer_send+offset, derivation.data, 32);
offset += 32;
//index
this->buffer_send[offset+0] = output_index>>24;
this->buffer_send[offset+1] = output_index>>16;
this->buffer_send[offset+2] = output_index>>8;
this->buffer_send[offset+3] = output_index>>0;
offset += 4;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(derived_pub.data, &this->buffer_recv[0], 32);
}
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("derive_subaddress_public_key", "derived_pub", derived_pub_x.data, derived_pub.data);
#endif
return true;
}
crypto::public_key device_ledger::get_subaddress_spend_public_key(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) {
AUTO_LOCK_CMD();
crypto::public_key D;
int offset;
#ifdef DEBUG_HWDEVICE
const cryptonote::account_keys keys_x = hw::ledger::decrypt(keys);
const cryptonote::subaddress_index index_x = index;
crypto::public_key D_x;
hw::ledger::log_hexbuffer("get_subaddress_spend_public_key: [[IN]] keys.m_view_secret_key ", keys_x.m_view_secret_key.data,32);
hw::ledger::log_hexbuffer("get_subaddress_spend_public_key: [[IN]] keys.m_spend_secret_key", keys_x.m_spend_secret_key.data,32);
hw::ledger::log_message ("get_subaddress_spend_public_key: [[IN]] index ", std::to_string(index_x.major)+"."+std::to_string(index_x.minor));
D_x = this->controle_device->get_subaddress_spend_public_key(keys_x, index_x);
hw::ledger::log_hexbuffer("get_subaddress_spend_public_key: [[OUT]] derivation ", D_x.data, 32);
#endif
if (index.is_zero()) {
D = keys.m_account_address.m_spend_public_key;
} else {
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GET_SUBADDRESS_SPEND_PUBLIC_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//index
static_assert(sizeof(cryptonote::subaddress_index) == 8, "cryptonote::subaddress_index shall be 8 bytes length");
memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index));
offset +=8 ;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(D.data, &this->buffer_recv[0], 32);
}
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("get_subaddress_spend_public_key", "D", D_x.data, D.data);
#endif
return D;
}
std::vector<crypto::public_key> device_ledger::get_subaddress_spend_public_keys(const cryptonote::account_keys &keys, uint32_t account, uint32_t begin, uint32_t end) {
std::vector<crypto::public_key> pkeys;
cryptonote::subaddress_index index = {account, begin};
crypto::public_key D;
for (uint32_t idx = begin; idx < end; ++idx) {
index.minor = idx;
D = this->get_subaddress_spend_public_key(keys, index);
pkeys.push_back(D);
}
return pkeys;
}
cryptonote::account_public_address device_ledger::get_subaddress(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) {
AUTO_LOCK_CMD();
cryptonote::account_public_address address;
int offset;
#ifdef DEBUG_HWDEVICE
const cryptonote::account_keys keys_x = hw::ledger::decrypt(keys);
const cryptonote::subaddress_index index_x = index;
cryptonote::account_public_address address_x;
hw::ledger::log_hexbuffer("get_subaddress: [[IN]] keys.m_view_secret_key ", keys_x.m_view_secret_key.data, 32);
hw::ledger::log_hexbuffer("get_subaddress: [[IN]] keys.m_view_public_key", keys_x.m_account_address.m_view_public_key.data, 32);
hw::ledger::log_hexbuffer("get_subaddress: [[IN]] keys.m_view_secret_key ", keys_x.m_view_secret_key.data, 32);
hw::ledger::log_hexbuffer("get_subaddress: [[IN]] keys.m_spend_public_key", keys_x.m_account_address.m_spend_public_key.data, 32);
hw::ledger::log_message ("get_subaddress: [[IN]] index ", std::to_string(index_x.major)+"."+std::to_string(index_x.minor));
address_x = this->controle_device->get_subaddress(keys_x, index_x);
hw::ledger::log_hexbuffer("get_subaddress: [[OUT]] keys.m_view_public_key ", address_x.m_view_public_key.data, 32);
hw::ledger::log_hexbuffer("get_subaddress: [[OUT]] keys.m_spend_public_key", address_x.m_spend_public_key.data, 32);
#endif
if (index.is_zero()) {
address = keys.m_account_address;
} else {
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GET_SUBADDRESS;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//index
static_assert(sizeof(cryptonote::subaddress_index) == 8, "cryptonote::subaddress_index shall be 8 bytes length");
memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index));
offset +=8 ;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(address.m_view_public_key.data, &this->buffer_recv[0], 32);
memmove(address.m_spend_public_key.data, &this->buffer_recv[32], 32);
}
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("get_subaddress", "address.m_view_public_key.data", address_x.m_view_public_key.data, address.m_view_public_key.data);
hw::ledger::check32("get_subaddress", "address.m_spend_public_key.data", address_x.m_spend_public_key.data, address.m_spend_public_key.data);
#endif
return address;
}
crypto::secret_key device_ledger::get_subaddress_secret_key(const crypto::secret_key &sec, const cryptonote::subaddress_index &index) {
AUTO_LOCK_CMD();
crypto::secret_key sub_sec;
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::secret_key sec_x = hw::ledger::decrypt(sec);
const cryptonote::subaddress_index index_x = index;
crypto::secret_key sub_sec_x;
hw::ledger::log_message ("get_subaddress_secret_key: [[IN]] index ", std::to_string(index.major)+"."+std::to_string(index.minor));
hw::ledger::log_hexbuffer("get_subaddress_secret_key: [[IN]] sec ", sec_x.data, 32);
sub_sec_x = this->controle_device->get_subaddress_secret_key(sec_x, index_x);
hw::ledger::log_hexbuffer("get_subaddress_secret_key: [[OUT]] sub_sec", sub_sec_x.data, 32);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GET_SUBADDRESS_SECRET_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//sec
memmove(this->buffer_send+offset, sec.data, 32);
offset += 32;
//index
static_assert(sizeof(cryptonote::subaddress_index) == 8, "cryptonote::subaddress_index shall be 8 bytes length");
memmove(this->buffer_send+offset, &index, sizeof(cryptonote::subaddress_index));
offset +=8 ;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(sub_sec.data, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
crypto::secret_key sub_sec_clear = hw::ledger::decrypt(sub_sec);
hw::ledger::check32("get_subaddress_secret_key", "sub_sec", sub_sec_x.data, sub_sec_clear.data);
#endif
return sub_sec;
}
/* ======================================================================= */
/* DERIVATION & KEY */
/* ======================================================================= */
bool device_ledger::verify_keys(const crypto::secret_key &secret_key, const crypto::public_key &public_key) {
AUTO_LOCK_CMD();
int offset, sw;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_VERIFY_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//sec
memmove(this->buffer_send+offset, secret_key.data, 32);
offset += 32;
//pub
memmove(this->buffer_send+offset, public_key.data, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
uint32_t verified =
this->buffer_recv[0] << 24 |
this->buffer_recv[1] << 16 |
this->buffer_recv[2] << 8 |
this->buffer_recv[3] << 0 ;
return verified == 1;
}
bool device_ledger::scalarmultKey(rct::key & aP, const rct::key &P, const rct::key &a) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const rct::key P_x = P;
const rct::key a_x = hw::ledger::decrypt(a);
rct::key aP_x;
hw::ledger::log_hexbuffer("scalarmultKey: [[IN]] P ", (char*)P_x.bytes, 32);
hw::ledger::log_hexbuffer("scalarmultKey: [[IN]] a ", (char*)a_x.bytes, 32);
this->controle_device->scalarmultKey(aP_x, P_x, a_x);
hw::ledger::log_hexbuffer("scalarmultKey: [[OUT]] aP", (char*)aP_x.bytes, 32);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_SECRET_SCAL_MUL_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//pub
memmove(this->buffer_send+offset, P.bytes, 32);
offset += 32;
//sec
memmove(this->buffer_send+offset, a.bytes, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(aP.bytes, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("scalarmultKey", "mulkey", (char*)aP_x.bytes, (char*)aP.bytes);
#endif
return true;
}
bool device_ledger::scalarmultBase(rct::key &aG, const rct::key &a) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const rct::key a_x = hw::ledger::decrypt(a);
rct::key aG_x;
hw::ledger::log_hexbuffer("scalarmultKey: [[IN]] a ", (char*)a_x.bytes, 32);
this->controle_device->scalarmultBase(aG_x, a_x);
hw::ledger::log_hexbuffer("scalarmultKey: [[OUT]] aG", (char*)aG_x.bytes, 32);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_SECRET_SCAL_MUL_BASE;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//sec
memmove(this->buffer_send+offset, a.bytes, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(aG.bytes, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("scalarmultBase", "mulkey", (char*)aG_x.bytes, (char*)aG.bytes);
#endif
return true;
}
bool device_ledger::sc_secret_add( crypto::secret_key &r, const crypto::secret_key &a, const crypto::secret_key &b) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::secret_key a_x = hw::ledger::decrypt(a);
const crypto::secret_key b_x = hw::ledger::decrypt(b);
crypto::secret_key r_x;
this->controle_device->sc_secret_add(r_x, a_x, b_x);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_SECRET_KEY_ADD;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//sec key
memmove(this->buffer_send+offset, a.data, 32);
offset += 32;
//sec key
memmove(this->buffer_send+offset, b.data, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(r.data, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
crypto::secret_key r_clear = hw::ledger::decrypt(r);
hw::ledger::check32("sc_secret_add", "r", r_x.data, r_clear.data);
#endif
return true;
}
crypto::secret_key device_ledger::generate_keys(crypto::public_key &pub, crypto::secret_key &sec, const crypto::secret_key& recovery_key, bool recover) {
AUTO_LOCK_CMD();
if (recover) {
throw std::runtime_error("device generate key does not support recover");
}
int offset;
#ifdef DEBUG_HWDEVICE
bool recover_x = recover;
const crypto::secret_key recovery_key_x = recovery_key;
crypto::public_key pub_x;
crypto::secret_key sec_x;
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GENERATE_KEYPAIR;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(pub.data, &this->buffer_recv[0], 32);
memmove(sec.data, &this->buffer_recv[32], 32);
#ifdef DEBUG_HWDEVICE
crypto::secret_key sec_clear = hw::ledger::decrypt(sec);
sec_x = sec_clear;
crypto::secret_key_to_public_key(sec_x,pub_x);
hw::ledger::check32("generate_keys", "pub", pub_x.data, pub.data);
#endif
return sec;
}
bool device_ledger::generate_key_derivation(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_derivation &derivation) {
AUTO_LOCK_CMD();
bool r = false;
#ifdef DEBUG_HWDEVICE
const crypto::public_key pub_x = pub;
const crypto::secret_key sec_x = hw::ledger::decrypt(sec);
crypto::key_derivation derivation_x;
hw::ledger::log_hexbuffer("generate_key_derivation: [[IN]] pub ", pub_x.data, 32);
hw::ledger::log_hexbuffer("generate_key_derivation: [[IN]] sec ", sec_x.data, 32);
this->controle_device->generate_key_derivation(pub_x, sec_x, derivation_x);
hw::ledger::log_hexbuffer("generate_key_derivation: [[OUT]] derivation", derivation_x.data, 32);
#endif
if ((this->mode == TRANSACTION_PARSE) && has_view_key) {
//A derivation is resquested in PASRE mode and we have the view key,
//so do that wihtout the device and return the derivation unencrypted.
MDEBUG( "generate_key_derivation : PARSE mode with known viewkey");
//Note derivation in PARSE mode can only happen with viewkey, so assert it!
assert(is_fake_view_key(sec));
r = crypto::generate_key_derivation(pub, this->viewkey, derivation);
} else {
int offset;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GEN_KEY_DERIVATION;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//pub
memmove(this->buffer_send+offset, pub.data, 32);
offset += 32;
//sec
memmove(this->buffer_send+offset, sec.data, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//derivattion data
memmove(derivation.data, &this->buffer_recv[0], 32);
r = true;
}
#ifdef DEBUG_HWDEVICE
crypto::key_derivation derivation_clear ;
if ((this->mode == TRANSACTION_PARSE) && has_view_key) {
derivation_clear = derivation;
}else {
derivation_clear = hw::ledger::decrypt(derivation);
}
hw::ledger::check32("generate_key_derivation", "derivation", derivation_x.data, derivation_clear.data);
#endif
return r;
}
bool device_ledger::conceal_derivation(crypto::key_derivation &derivation, const crypto::public_key &tx_pub_key, const std::vector<crypto::public_key> &additional_tx_pub_keys, const crypto::key_derivation &main_derivation, const std::vector<crypto::key_derivation> &additional_derivations) {
const crypto::public_key *pkey=NULL;
if (derivation == main_derivation) {
pkey = &tx_pub_key;
MDEBUG("conceal derivation with main tx pub key");
} else {
for(size_t n=0; n < additional_derivations.size();++n) {
if(derivation == additional_derivations[n]) {
pkey = &additional_tx_pub_keys[n];
MDEBUG("conceal derivation with additionnal tx pub key");
break;
}
}
}
ASSERT_X(pkey, "Mismatched derivation on scan info");
return this->generate_key_derivation(*pkey, crypto::null_skey, derivation);
}
bool device_ledger::derivation_to_scalar(const crypto::key_derivation &derivation, const size_t output_index, crypto::ec_scalar &res) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation);
const size_t output_index_x = output_index;
crypto::ec_scalar res_x;
hw::ledger::log_hexbuffer("derivation_to_scalar: [[IN]] derivation ", derivation_x.data, 32);
hw::ledger::log_message ("derivation_to_scalar: [[IN]] output_index ", std::to_string(output_index_x));
this->controle_device->derivation_to_scalar(derivation_x, output_index_x, res_x);
hw::ledger::log_hexbuffer("derivation_to_scalar: [[OUT]] res ", res_x.data, 32);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_DERIVATION_TO_SCALAR;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//derivattion
memmove(this->buffer_send+offset, derivation.data, 32);
offset += 32;
//index
this->buffer_send[offset+0] = output_index>>24;
this->buffer_send[offset+1] = output_index>>16;
this->buffer_send[offset+2] = output_index>>8;
this->buffer_send[offset+3] = output_index>>0;
offset += 4;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//derivattion data
memmove(res.data, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
crypto::ec_scalar res_clear = hw::ledger::decrypt(res);
hw::ledger::check32("derivation_to_scalar", "res", res_x.data, res_clear.data);
#endif
return true;
}
bool device_ledger::derive_secret_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::secret_key &sec, crypto::secret_key &derived_sec) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation);
const std::size_t output_index_x = output_index;
const crypto::secret_key sec_x = hw::ledger::decrypt(sec);
crypto::secret_key derived_sec_x;
hw::ledger::log_hexbuffer("derive_secret_key: [[IN]] derivation ", derivation_x.data, 32);
hw::ledger::log_message ("derive_secret_key: [[IN]] index ", std::to_string(output_index_x));
hw::ledger::log_hexbuffer("derive_secret_key: [[IN]] sec ", sec_x.data, 32);
this->controle_device->derive_secret_key(derivation_x, output_index_x, sec_x, derived_sec_x);
hw::ledger::log_hexbuffer("derive_secret_key: [[OUT]] derived_sec", derived_sec_x.data, 32);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_DERIVE_SECRET_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//derivation
memmove(this->buffer_send+offset, derivation.data, 32);
offset += 32;
//index
this->buffer_send[offset+0] = output_index>>24;
this->buffer_send[offset+1] = output_index>>16;
this->buffer_send[offset+2] = output_index>>8;
this->buffer_send[offset+3] = output_index>>0;
offset += 4;
//sec
memmove(this->buffer_send+offset, sec.data, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(derived_sec.data, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
crypto::secret_key derived_sec_clear = hw::ledger::decrypt(derived_sec);
hw::ledger::check32("derive_secret_key", "derived_sec", derived_sec_x.data, derived_sec_clear.data);
#endif
return true;
}
bool device_ledger::derive_public_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::public_key &pub, crypto::public_key &derived_pub){
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::key_derivation derivation_x = hw::ledger::decrypt(derivation);
const std::size_t output_index_x = output_index;
const crypto::public_key pub_x = pub;
crypto::public_key derived_pub_x;
hw::ledger::log_hexbuffer("derive_public_key: [[IN]] derivation ", derivation_x.data, 32);
hw::ledger::log_message ("derive_public_key: [[IN]] output_index", std::to_string(output_index_x));
hw::ledger::log_hexbuffer("derive_public_key: [[IN]] pub ", pub_x.data, 32);
this->controle_device->derive_public_key(derivation_x, output_index_x, pub_x, derived_pub_x);
hw::ledger::log_hexbuffer("derive_public_key: [[OUT]] derived_pub ", derived_pub_x.data, 32);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_DERIVE_PUBLIC_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//derivation
memmove(this->buffer_send+offset, derivation.data, 32);
offset += 32;
//index
this->buffer_send[offset+0] = output_index>>24;
this->buffer_send[offset+1] = output_index>>16;
this->buffer_send[offset+2] = output_index>>8;
this->buffer_send[offset+3] = output_index>>0;
offset += 4;
//pub
memmove(this->buffer_send+offset, pub.data, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(derived_pub.data, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("derive_public_key", "derived_pub", derived_pub_x.data, derived_pub.data);
#endif
return true;
}
bool device_ledger::secret_key_to_public_key(const crypto::secret_key &sec, crypto::public_key &pub) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::secret_key sec_x = hw::ledger::decrypt(sec);
crypto::public_key pub_x;
hw::ledger::log_hexbuffer("secret_key_to_public_key: [[IN]] sec ", sec_x.data, 32);
bool rc = this->controle_device->secret_key_to_public_key(sec_x, pub_x);
hw::ledger::log_hexbuffer("secret_key_to_public_key: [[OUT]] pub", pub_x.data, 32);
if (!rc){
hw::ledger::log_message("secret_key_to_public_key", "secret_key rejected");
}
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_SECRET_KEY_TO_PUBLIC_KEY;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//sec key
memmove(this->buffer_send+offset, sec.data, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(pub.data, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("secret_key_to_public_key", "pub", pub_x.data, pub.data);
#endif
return true;
}
bool device_ledger::generate_key_image(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_image &image){
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::public_key pub_x = pub;
const crypto::secret_key sec_x = hw::ledger::decrypt(sec);
crypto::key_image image_x;
hw::ledger::log_hexbuffer("generate_key_image: [[IN]] pub ", pub_x.data, 32);
hw::ledger::log_hexbuffer("generate_key_image: [[IN]] sec ", sec_x.data, 32);
this->controle_device->generate_key_image(pub_x, sec_x, image_x);
hw::ledger::log_hexbuffer("generate_key_image: [[OUT]] image ", image_x.data, 32);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_GEN_KEY_IMAGE;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0;
offset += 1;
//pub
memmove(this->buffer_send+offset, pub.data, 32);
offset += 32;
//sec
memmove(this->buffer_send+offset, sec.data, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pub key
memmove(image.data, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("generate_key_image", "image", image_x.data, image.data);
#endif
return true;
}
/* ======================================================================= */
/* TRANSACTION */
/* ======================================================================= */
bool device_ledger::open_tx(crypto::secret_key &tx_key) {
AUTO_LOCK_CMD();
int offset;
reset_buffer();
key_map.clear();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_OPEN_TX;
this->buffer_send[2] = 0x01;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//account
this->buffer_send[offset+0] = 0x00;
this->buffer_send[offset+1] = 0x00;
this->buffer_send[offset+2] = 0x00;
this->buffer_send[offset+3] = 0x00;
offset += 4;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(tx_key.data, &this->buffer_recv[32], 32);
return true;
}
bool device_ledger::encrypt_payment_id(crypto::hash8 &payment_id, const crypto::public_key &public_key, const crypto::secret_key &secret_key) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const crypto::public_key public_key_x = public_key;
const crypto::secret_key secret_key_x = hw::ledger::decrypt(secret_key);
crypto::hash8 payment_id_x = payment_id;
this->controle_device->encrypt_payment_id(payment_id_x, public_key_x, secret_key_x);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_STEALTH;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//pub
memmove(&this->buffer_send[offset], public_key.data, 32);
offset += 32;
//sec
memmove(&this->buffer_send[offset], secret_key.data, 32);
offset += 32;
//id
memmove(&this->buffer_send[offset], payment_id.data, 8);
offset += 8;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(payment_id.data, &this->buffer_recv[0], 8);
#ifdef DEBUG_HWDEVICE
hw::ledger::check8("stealth", "payment_id", payment_id_x.data, payment_id.data);
#endif
return true;
}
bool device_ledger::add_output_key_mapping(const crypto::public_key &Aout, const crypto::public_key &Bout, const bool is_subaddress, const size_t real_output_index,
const rct::key &amount_key, const crypto::public_key &out_eph_public_key) {
AUTO_LOCK_CMD();
key_map.add(ABPkeys(rct::pk2rct(Aout),rct::pk2rct(Bout), is_subaddress, real_output_index, rct::pk2rct(out_eph_public_key), amount_key));
return true;
}
bool device_ledger::ecdhEncode(rct::ecdhTuple & unmasked, const rct::key & AKout) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const rct::key AKout_x = hw::ledger::decrypt(AKout);
rct::ecdhTuple unmasked_x = unmasked;
this->controle_device->ecdhEncode(unmasked_x, AKout_x);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_BLIND;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
// AKout
memmove(this->buffer_send+offset, AKout.bytes, 32);
offset += 32;
//mask k
memmove(this->buffer_send+offset, unmasked.mask.bytes, 32);
offset += 32;
//value v
memmove(this->buffer_send+offset, unmasked.amount.bytes, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(unmasked.amount.bytes, &this->buffer_recv[0], 32);
memmove(unmasked.mask.bytes, &this->buffer_recv[32], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("ecdhEncode", "amount", (char*)unmasked_x.amount.bytes, (char*)unmasked.amount.bytes);
hw::ledger::check32("ecdhEncode", "mask", (char*)unmasked_x.mask.bytes, (char*)unmasked.mask.bytes);
hw::ledger::log_hexbuffer("Blind AKV input", (char*)&this->buffer_recv[64], 3*32);
#endif
return true;
}
bool device_ledger::ecdhDecode(rct::ecdhTuple & masked, const rct::key & AKout) {
AUTO_LOCK_CMD();
int offset;
#ifdef DEBUG_HWDEVICE
const rct::key AKout_x = hw::ledger::decrypt(AKout);
rct::ecdhTuple masked_x = masked;
this->controle_device->ecdhDecode(masked_x, AKout_x);
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_UNBLIND;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
// AKout
memmove(this->buffer_send+offset, AKout.bytes, 32);
offset += 32;
//mask k
memmove(this->buffer_send+offset, masked.mask.bytes, 32);
offset += 32;
//value v
memmove(this->buffer_send+offset, masked.amount.bytes, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(masked.amount.bytes, &this->buffer_recv[0], 32);
memmove(masked.mask.bytes, &this->buffer_recv[32], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("ecdhDecode", "amount", (char*)masked_x.amount.bytes, (char*)masked.amount.bytes);
hw::ledger::check32("ecdhDecode", "mask", (char*)masked_x.mask.bytes,(char*) masked.mask.bytes);
#endif
return true;
}
bool device_ledger::mlsag_prehash(const std::string &blob, size_t inputs_size, size_t outputs_size,
const rct::keyV &hashes, const rct::ctkeyV &outPk,
rct::key &prehash) {
AUTO_LOCK_CMD();
unsigned int data_offset, C_offset, kv_offset, i;
const char *data;
#ifdef DEBUG_HWDEVICE
const std::string blob_x = blob;
size_t inputs_size_x = inputs_size;
size_t outputs_size_x = outputs_size;
const rct::keyV hashes_x = hashes;
const rct::ctkeyV outPk_x = outPk;
rct::key prehash_x;
this->controle_device->mlsag_prehash(blob_x, inputs_size_x, outputs_size_x, hashes_x, outPk_x, prehash_x);
if (inputs_size) {
log_message("mlsag_prehash", (std::string("inputs_size not null: ") + std::to_string(inputs_size)).c_str());
}
this->key_map.log();
#endif
data = blob.data();
// ====== u8 type, varint txnfee ======
int offset;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_VALIDATE;
this->buffer_send[2] = 0x01;
this->buffer_send[3] = 0x01;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = (inputs_size == 0)?0x00:0x80;
offset += 1;
//type
uint8_t type = data[0];
this->buffer_send[offset] = data[0];
offset += 1;
//txnfee
data_offset = 1;
while (data[data_offset]&0x80) {
this->buffer_send[offset] = data[data_offset];
offset += 1;
data_offset += 1;
}
this->buffer_send[offset] = data[data_offset];
offset += 1;
data_offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//pseudoOuts
if ((type == rct::RCTTypeSimple) || (type == rct::RCTTypeSimpleBulletproof)) {
for ( i = 0; i < inputs_size; i++) {
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_VALIDATE;
this->buffer_send[2] = 0x01;
this->buffer_send[3] = i+2;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = (i==inputs_size-1)? 0x00:0x80;
offset += 1;
//pseudoOut
memmove(this->buffer_send+offset, data+data_offset,32);
offset += 32;
data_offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
}
}
// ====== Aout, Bout, AKout, C, v, k ======
kv_offset = data_offset;
C_offset = kv_offset+ (32*2)*outputs_size;
for ( i = 0; i < outputs_size; i++) {
ABPkeys outKeys;
bool found;
found = this->key_map.find(outPk[i].dest, outKeys);
if (!found) {
log_hexbuffer("Pout not found", (char*)outPk[i].dest.bytes, 32);
CHECK_AND_ASSERT_THROW_MES(found, "Pout not found");
}
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_VALIDATE;
this->buffer_send[2] = 0x02;
this->buffer_send[3] = i+1;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = (i==outputs_size-1)? 0x00:0x80 ;
offset += 1;
if (found) {
//is_subaddress
this->buffer_send[offset] = outKeys.is_subaddress;
offset++;
//Aout
memmove(this->buffer_send+offset, outKeys.Aout.bytes, 32);
offset+=32;
//Bout
memmove(this->buffer_send+offset, outKeys.Bout.bytes, 32);
offset+=32;
//AKout
memmove(this->buffer_send+offset, outKeys.AKout.bytes, 32);
offset+=32;
} else {
// dummy: is_subaddress Aout Bout AKout
offset += 1+32*3;
}
//C
memmove(this->buffer_send+offset, data+C_offset,32);
offset += 32;
C_offset += 32;
//k
memmove(this->buffer_send+offset, data+kv_offset,32);
offset += 32;
//v
kv_offset += 32;
memmove(this->buffer_send+offset, data+kv_offset,32);
offset += 32;
kv_offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
#ifdef DEBUG_HWDEVICE
hw::ledger::log_hexbuffer("Prehash AKV input", (char*)&this->buffer_recv[64], 3*32);
#endif
}
// ====== C[], message, proof======
C_offset = kv_offset;
for (i = 0; i < outputs_size; i++) {
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_VALIDATE;
this->buffer_send[2] = 0x03;
this->buffer_send[3] = i+1;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x80 ;
offset += 1;
//C
memmove(this->buffer_send+offset, data+C_offset,32);
offset += 32;
C_offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
}
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_VALIDATE;
this->buffer_send[2] = 0x03;
this->buffer_send[3] = i+1;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//message
memmove(this->buffer_send+offset, hashes[0].bytes,32);
offset += 32;
//proof
memmove(this->buffer_send+offset, hashes[2].bytes,32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(prehash.bytes, this->buffer_recv, 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("mlsag_prehash", "prehash", (char*)prehash_x.bytes, (char*)prehash.bytes);
#endif
return true;
}
bool device_ledger::mlsag_prepare(const rct::key &H, const rct::key &xx,
rct::key &a, rct::key &aG, rct::key &aHP, rct::key &II) {
AUTO_LOCK_CMD();
int offset;
unsigned char options;
#ifdef DEBUG_HWDEVICE
const rct::key H_x = H;
const rct::key xx_x = hw::ledger::decrypt(xx);
rct::key a_x;
rct::key aG_x;
rct::key aHP_x;
rct::key II_x;
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_MLSAG;
this->buffer_send[2] = 0x01;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
//value H
memmove(this->buffer_send+offset, H.bytes, 32);
offset += 32;
//mask xin
memmove(this->buffer_send+offset, xx.bytes, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(a.bytes, &this->buffer_recv[32*0], 32);
memmove(aG.bytes, &this->buffer_recv[32*1], 32);
memmove(aHP.bytes, &this->buffer_recv[32*2], 32);
memmove(II.bytes, &this->buffer_recv[32*3], 32);
#ifdef DEBUG_HWDEVICE
a_x = hw::ledger::decrypt(a);
rct::scalarmultBase(aG_x, a_x);
rct::scalarmultKey(aHP_x, H_x, a_x);
rct::scalarmultKey(II_x, H_x, xx_x);
hw::ledger::check32("mlsag_prepare", "AG", (char*)aG_x.bytes, (char*)aG.bytes);
hw::ledger::check32("mlsag_prepare", "aHP", (char*)aHP_x.bytes, (char*)aHP.bytes);
hw::ledger::check32("mlsag_prepare", "II", (char*)II_x.bytes, (char*)II.bytes);
#endif
return true;
}
bool device_ledger::mlsag_prepare(rct::key &a, rct::key &aG) {
AUTO_LOCK_CMD();
int offset;
unsigned char options;
#ifdef DEBUG_HWDEVICE
rct::key a_x;
rct::key aG_x;
#endif
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_MLSAG;
this->buffer_send[2] = 0x01;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
memmove(a.bytes, &this->buffer_recv[32*0], 32);
memmove(aG.bytes, &this->buffer_recv[32*1], 32);
#ifdef DEBUG_HWDEVICE
a_x = hw::ledger::decrypt(a);
rct::scalarmultBase(aG_x, a_x);
hw::ledger::check32("mlsag_prepare", "AG", (char*)aG_x.bytes, (char*)aG.bytes);
#endif
return true;
}
bool device_ledger::mlsag_hash(const rct::keyV &long_message, rct::key &c) {
AUTO_LOCK_CMD();
int offset;
unsigned char options;
size_t cnt;
#ifdef DEBUG_HWDEVICE
const rct::keyV long_message_x = long_message;
rct::key c_x;
this->controle_device->mlsag_hash(long_message_x, c_x);
#endif
cnt = long_message.size();
for (size_t i = 0; i<cnt; i++) {
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_MLSAG;
this->buffer_send[2] = 0x02;
this->buffer_send[3] = i+1;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] =
(i==(cnt-1))?0x00:0x80; //last
offset += 1;
//msg part
memmove(this->buffer_send+offset, long_message[i].bytes, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
}
memmove(c.bytes, &this->buffer_recv[0], 32);
#ifdef DEBUG_HWDEVICE
hw::ledger::check32("mlsag_hash", "c", (char*)c_x.bytes, (char*)c.bytes);
#endif
return true;
}
bool device_ledger::mlsag_sign(const rct::key &c, const rct::keyV &xx, const rct::keyV &alpha, const size_t rows, const size_t dsRows, rct::keyV &ss) {
AUTO_LOCK_CMD();
int offset;
CHECK_AND_ASSERT_THROW_MES(dsRows<=rows, "dsRows greater than rows");
CHECK_AND_ASSERT_THROW_MES(xx.size() == rows, "xx size does not match rows");
CHECK_AND_ASSERT_THROW_MES(alpha.size() == rows, "alpha size does not match rows");
CHECK_AND_ASSERT_THROW_MES(ss.size() == rows, "ss size does not match rows");
#ifdef DEBUG_HWDEVICE
const rct::key c_x = c;
const rct::keyV xx_x = hw::ledger::decrypt(xx);
const rct::keyV alpha_x = hw::ledger::decrypt(alpha);
const int rows_x = rows;
const int dsRows_x = dsRows;
rct::keyV ss_x(ss.size());
this->controle_device->mlsag_sign(c_x, xx_x, alpha_x, rows_x, dsRows_x, ss_x);
#endif
for (size_t j = 0; j < dsRows; j++) {
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_MLSAG;
this->buffer_send[2] = 0x03;
this->buffer_send[3] = j+1;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
if (j==(dsRows-1)) {
this->buffer_send[offset] |= 0x80; //last
}
offset += 1;
//xx
memmove(this->buffer_send+offset, xx[j].bytes, 32);
offset += 32;
//alpa
memmove(this->buffer_send+offset, alpha[j].bytes, 32);
offset += 32;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
//ss
memmove(ss[j].bytes, &this->buffer_recv[0], 32);
}
for (size_t j = dsRows; j < rows; j++) {
sc_mulsub(ss[j].bytes, c.bytes, xx[j].bytes, alpha[j].bytes);
}
#ifdef DEBUG_HWDEVICE
for (size_t j = 0; j < rows; j++) {
hw::ledger::check32("mlsag_sign", "ss["+std::to_string(j)+"]", (char*)ss_x[j].bytes, (char*)ss[j].bytes);
}
#endif
return true;
}
bool device_ledger::close_tx() {
AUTO_LOCK_CMD();
int offset;
reset_buffer();
this->buffer_send[0] = 0x00;
this->buffer_send[1] = INS_CLOSE_TX;
this->buffer_send[2] = 0x00;
this->buffer_send[3] = 0x00;
this->buffer_send[4] = 0x00;
offset = 5;
//options
this->buffer_send[offset] = 0x00;
offset += 1;
this->buffer_send[4] = offset-5;
this->length_send = offset;
this->exchange();
return true;
}
/* ---------------------------------------------------------- */
static device_ledger *legder_device = NULL;
void register_all(std::map<std::string, std::unique_ptr<device>> ®istry) {
if (!legder_device) {
legder_device = new device_ledger();
legder_device->set_name("Ledger");
}
registry.insert(std::make_pair("Ledger", std::unique_ptr<device>(legder_device)));
}
#else //WITH_DEVICE_LEDGER
void register_all(std::map<std::string, std::unique_ptr<device>> ®istry) {
}
#endif //WITH_DEVICE_LEDGER
}
}
|
// Copyright (c) 2021-2022 Daniel Frey and Dr. Colin Hirsch
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#ifndef TAO_PQ_TABLE_ROW_HPP
#define TAO_PQ_TABLE_ROW_HPP
#include <cstddef>
#include <iterator>
#include <optional>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <utility>
#include <tao/pq/internal/demangle.hpp>
#include <tao/pq/internal/dependent_false.hpp>
#include <tao/pq/internal/printf.hpp>
#include <tao/pq/internal/unreachable.hpp>
#include <tao/pq/result_traits.hpp>
#include <tao/pq/table_field.hpp>
namespace tao::pq
{
class table_reader;
class table_row
{
protected:
friend class table_field;
friend class table_reader;
table_reader* m_reader;
std::size_t m_offset;
std::size_t m_columns;
table_row( table_reader& in_reader, const std::size_t in_offset, const std::size_t in_columns ) noexcept
: m_reader( &in_reader ),
m_offset( in_offset ),
m_columns( in_columns )
{}
void ensure_column( const std::size_t column ) const;
public:
[[nodiscard]] auto slice( const std::size_t offset, const std::size_t in_columns ) const -> table_row;
[[nodiscard]] auto columns() const noexcept -> std::size_t
{
return m_columns;
}
private:
class const_iterator
: private table_field
{
private:
friend class table_row;
explicit const_iterator( const table_field& f ) noexcept
: table_field( f )
{}
public:
using difference_type = std::int32_t;
using value_type = const table_field;
using pointer = const table_field*;
using reference = const table_field&;
using iterator_category = std::random_access_iterator_tag;
const_iterator() = default;
auto operator++() noexcept -> const_iterator&
{
++m_column;
return *this;
}
auto operator++( int ) noexcept -> const_iterator
{
const_iterator nrv( *this );
++*this;
return nrv;
}
auto operator+=( const difference_type n ) noexcept -> const_iterator&
{
m_column += n;
return *this;
}
auto operator--() noexcept -> const_iterator&
{
--m_column;
return *this;
}
auto operator--( int ) noexcept -> const_iterator
{
const_iterator nrv( *this );
--*this;
return nrv;
}
auto operator-=( const difference_type n ) noexcept -> const_iterator&
{
m_column -= n;
return *this;
}
[[nodiscard]] auto operator*() const noexcept -> const table_field&
{
return *this;
}
[[nodiscard]] auto operator->() const noexcept -> const table_field*
{
return this;
}
[[nodiscard]] auto operator[]( const difference_type n ) const noexcept -> table_field
{
return *( *this + n );
}
friend void swap( const_iterator& lhs, const_iterator& rhs ) noexcept
{
return swap( static_cast< table_field& >( lhs ), static_cast< table_field& >( rhs ) );
}
[[nodiscard]] friend auto operator+( const const_iterator& lhs, const difference_type rhs ) noexcept -> const_iterator
{
const_iterator nrv( lhs );
nrv += rhs;
return nrv;
}
[[nodiscard]] friend auto operator+( const difference_type lhs, const const_iterator& rhs ) noexcept -> const_iterator
{
const_iterator nrv( rhs );
nrv += lhs;
return nrv;
}
[[nodiscard]] friend auto operator-( const const_iterator& lhs, const difference_type rhs ) noexcept -> const_iterator
{
const_iterator nrv( lhs );
nrv -= rhs;
return nrv;
}
[[nodiscard]] friend auto operator-( const const_iterator& lhs, const const_iterator& rhs ) noexcept -> difference_type
{
return static_cast< difference_type >( lhs.index() ) - static_cast< difference_type >( rhs.index() );
}
[[nodiscard]] friend auto operator==( const const_iterator& lhs, const const_iterator& rhs ) noexcept
{
return lhs.index() == rhs.index();
}
[[nodiscard]] friend auto operator!=( const const_iterator& lhs, const const_iterator& rhs ) noexcept
{
return lhs.index() != rhs.index();
}
[[nodiscard]] friend auto operator<( const const_iterator& lhs, const const_iterator& rhs ) noexcept
{
return lhs.index() < rhs.index();
}
[[nodiscard]] friend auto operator>( const const_iterator& lhs, const const_iterator& rhs ) noexcept
{
return lhs.index() > rhs.index();
}
[[nodiscard]] friend auto operator<=( const const_iterator& lhs, const const_iterator& rhs ) noexcept
{
return lhs.index() <= rhs.index();
}
[[nodiscard]] friend auto operator>=( const const_iterator& lhs, const const_iterator& rhs ) noexcept
{
return lhs.index() >= rhs.index();
}
};
public:
[[nodiscard]] auto begin() const -> const_iterator;
[[nodiscard]] auto end() const -> const_iterator;
[[nodiscard]] auto cbegin() const
{
return begin();
}
[[nodiscard]] auto cend() const
{
return end();
}
[[nodiscard]] auto is_null( const std::size_t column ) const -> bool;
[[nodiscard]] auto get( const std::size_t column ) const -> const char*;
template< typename T >
[[nodiscard]] auto get( const std::size_t column ) const -> T
{
if constexpr( result_traits_size< T > == 0 ) {
static_assert( internal::dependent_false< T >, "tao::pq::result_traits<T>::size yields zero" );
TAO_PQ_UNREACHABLE; // LCOV_EXCL_LINE
}
else if constexpr( result_traits_size< T > == 1 ) {
const char* const value = get( column );
if( value == nullptr ) {
if constexpr( result_traits_has_null< T > ) {
return result_traits< T >::null();
}
else {
throw std::invalid_argument( "unexpected NULL value" );
}
}
return result_traits< T >::from( value );
}
else {
return result_traits< T >::from( slice( column, result_traits_size< T > ) );
}
}
template< typename T >
[[nodiscard]] auto optional( const std::size_t column ) const
{
return get< std::optional< T > >( column );
}
template< typename T >
[[nodiscard]] auto as() const -> T
{
if( result_traits_size< T > != m_columns ) {
const auto type = internal::demangle< T >();
throw std::out_of_range( internal::printf( "datatype (%.*s) requires %zu columns, but table_row/slice has %zu columns", static_cast< int >( type.size() ), type.data(), result_traits_size< T >, m_columns ) );
}
return get< T >( 0 );
}
template< typename T >
[[nodiscard]] auto optional() const
{
return as< std::optional< T > >();
}
template< typename T, typename U >
[[nodiscard]] auto pair() const
{
return as< std::pair< T, U > >();
}
template< typename... Ts >
[[nodiscard]] auto tuple() const
{
return as< std::tuple< Ts... > >();
}
[[nodiscard]] auto at( const std::size_t column ) const -> table_field;
[[nodiscard]] auto operator[]( const std::size_t column ) const noexcept -> table_field
{
return table_field( *this, m_offset + column );
}
friend void swap( table_row& lhs, table_row& rhs ) noexcept
{
std::swap( lhs.m_reader, rhs.m_reader );
std::swap( lhs.m_offset, rhs.m_offset );
std::swap( lhs.m_columns, rhs.m_columns );
}
};
template< typename T >
auto table_field::as() const -> T
{
static_assert( result_traits_size< T > == 1, "tao::pq::result_traits<T>::size does not yield exactly one column for T, which is required for field access" );
return m_row->get< T >( m_column );
}
} // namespace tao::pq
#endif
|
// Generated by Haxe 3.4.7
#include <hxcpp.h>
#ifndef INCLUDED_Reflect
#include <Reflect.h>
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_Type
#include <Type.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_ds_BalancedTree
#include <haxe/ds/BalancedTree.h>
#endif
#ifndef INCLUDED_haxe_ds_EnumValueMap
#include <haxe/ds/EnumValueMap.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_079f71771048e957_31_new,"haxe.ds.EnumValueMap","new",0x9ce29655,"haxe.ds.EnumValueMap.new","C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx",31,0x67888762)
HX_LOCAL_STACK_FRAME(_hx_pos_079f71771048e957_33_compare,"haxe.ds.EnumValueMap","compare",0x806a7d1a,"haxe.ds.EnumValueMap.compare","C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx",33,0x67888762)
HX_LOCAL_STACK_FRAME(_hx_pos_079f71771048e957_42_compareArgs,"haxe.ds.EnumValueMap","compareArgs",0x37a5cb97,"haxe.ds.EnumValueMap.compareArgs","C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx",42,0x67888762)
HX_LOCAL_STACK_FRAME(_hx_pos_079f71771048e957_53_compareArg,"haxe.ds.EnumValueMap","compareArg",0xcee2e55c,"haxe.ds.EnumValueMap.compareArg","C:\\HaxeToolkit\\haxe\\std/haxe/ds/EnumValueMap.hx",53,0x67888762)
namespace haxe{
namespace ds{
void EnumValueMap_obj::__construct(){
HX_STACKFRAME(&_hx_pos_079f71771048e957_31_new)
HXDLIN( 31) super::__construct();
}
Dynamic EnumValueMap_obj::__CreateEmpty() { return new EnumValueMap_obj; }
void *EnumValueMap_obj::_hx_vtable = 0;
Dynamic EnumValueMap_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< EnumValueMap_obj > _hx_result = new EnumValueMap_obj();
_hx_result->__construct();
return _hx_result;
}
bool EnumValueMap_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x04042deb) {
return inClassId==(int)0x00000001 || inClassId==(int)0x04042deb;
} else {
return inClassId==(int)0x13b42f39;
}
}
static ::haxe::IMap_obj _hx_haxe_ds_EnumValueMap__hx_haxe_IMap= {
( ::Dynamic (hx::Object::*)( ::Dynamic))&::haxe::ds::EnumValueMap_obj::get,
( void (hx::Object::*)( ::Dynamic, ::Dynamic))&::haxe::ds::EnumValueMap_obj::set_41d0cb46,
( bool (hx::Object::*)( ::Dynamic))&::haxe::ds::EnumValueMap_obj::exists,
( bool (hx::Object::*)( ::Dynamic))&::haxe::ds::EnumValueMap_obj::remove,
};
void EnumValueMap_obj::set_41d0cb46( ::Dynamic k, ::Dynamic v) {
set(k,v);
}
void *EnumValueMap_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0x09c2bd39: return &_hx_haxe_ds_EnumValueMap__hx_haxe_IMap;
}
return super::_hx_getInterface(inHash);
}
int EnumValueMap_obj::compare( ::Dynamic _tmp_k1, ::Dynamic _tmp_k2){
HX_STACKFRAME(&_hx_pos_079f71771048e957_33_compare)
HXLINE( 34) ::Dynamic k1 = _tmp_k1;
HXDLIN( 34) ::Dynamic k2 = _tmp_k2;
HXDLIN( 34) int d = _hx_getEnumValueIndex(k1);
HXDLIN( 34) int d1 = (d - _hx_getEnumValueIndex(k2));
HXLINE( 35) if ((d1 != (int)0)) {
HXLINE( 35) return d1;
}
HXLINE( 36) ::cpp::VirtualArray p1 = ::Type_obj::enumParameters(k1);
HXLINE( 37) ::cpp::VirtualArray p2 = ::Type_obj::enumParameters(k2);
HXLINE( 38) bool _hx_tmp;
HXDLIN( 38) if ((p1->get_length() == (int)0)) {
HXLINE( 38) _hx_tmp = (p2->get_length() == (int)0);
}
else {
HXLINE( 38) _hx_tmp = false;
}
HXDLIN( 38) if (_hx_tmp) {
HXLINE( 38) return (int)0;
}
HXLINE( 39) return this->compareArgs(p1,p2);
}
int EnumValueMap_obj::compareArgs(::cpp::VirtualArray a1,::cpp::VirtualArray a2){
HX_STACKFRAME(&_hx_pos_079f71771048e957_42_compareArgs)
HXLINE( 43) int ld = (a1->get_length() - a2->get_length());
HXLINE( 44) if ((ld != (int)0)) {
HXLINE( 44) return ld;
}
HXLINE( 45) {
HXLINE( 45) int _g1 = (int)0;
HXDLIN( 45) int _g = a1->get_length();
HXDLIN( 45) while((_g1 < _g)){
HXLINE( 45) _g1 = (_g1 + (int)1);
HXDLIN( 45) int i = (_g1 - (int)1);
HXLINE( 46) int d = this->compareArg(a1->__get(i),a2->__get(i));
HXLINE( 47) if ((d != (int)0)) {
HXLINE( 47) return d;
}
}
}
HXLINE( 49) return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC2(EnumValueMap_obj,compareArgs,return )
int EnumValueMap_obj::compareArg( ::Dynamic v1, ::Dynamic v2){
HX_STACKFRAME(&_hx_pos_079f71771048e957_53_compareArg)
HXDLIN( 53) bool _hx_tmp;
HXDLIN( 53) if (::Reflect_obj::isEnumValue(v1)) {
HXDLIN( 53) _hx_tmp = ::Reflect_obj::isEnumValue(v2);
}
else {
HXDLIN( 53) _hx_tmp = false;
}
HXDLIN( 53) if (_hx_tmp) {
HXLINE( 54) return this->compare(v1,v2);
}
else {
HXLINE( 55) bool _hx_tmp1;
HXDLIN( 55) if (::Std_obj::is(v1,hx::ArrayBase::__mClass)) {
HXLINE( 55) _hx_tmp1 = ::Std_obj::is(v2,hx::ArrayBase::__mClass);
}
else {
HXLINE( 55) _hx_tmp1 = false;
}
HXDLIN( 55) if (_hx_tmp1) {
HXLINE( 56) return this->compareArgs(( (::cpp::VirtualArray)(v1) ),( (::cpp::VirtualArray)(v2) ));
}
else {
HXLINE( 58) return ::Reflect_obj::compare(v1,v2);
}
}
HXLINE( 53) return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC2(EnumValueMap_obj,compareArg,return )
hx::ObjectPtr< EnumValueMap_obj > EnumValueMap_obj::__new() {
hx::ObjectPtr< EnumValueMap_obj > __this = new EnumValueMap_obj();
__this->__construct();
return __this;
}
hx::ObjectPtr< EnumValueMap_obj > EnumValueMap_obj::__alloc(hx::Ctx *_hx_ctx) {
EnumValueMap_obj *__this = (EnumValueMap_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(EnumValueMap_obj), true, "haxe.ds.EnumValueMap"));
*(void **)__this = EnumValueMap_obj::_hx_vtable;
__this->__construct();
return __this;
}
EnumValueMap_obj::EnumValueMap_obj()
{
}
hx::Val EnumValueMap_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 7:
if (HX_FIELD_EQ(inName,"compare") ) { return hx::Val( compare_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"compareArg") ) { return hx::Val( compareArg_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"compareArgs") ) { return hx::Val( compareArgs_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
#if HXCPP_SCRIPTABLE
static hx::StorageInfo *EnumValueMap_obj_sMemberStorageInfo = 0;
static hx::StaticInfo *EnumValueMap_obj_sStaticStorageInfo = 0;
#endif
static ::String EnumValueMap_obj_sMemberFields[] = {
HX_HCSTRING("compare","\xa5","\x18","\x69","\x83"),
HX_HCSTRING("compareArgs","\xa2","\x88","\x40","\xb6"),
HX_HCSTRING("compareArg","\xb1","\xd2","\x97","\x0e"),
::String(null()) };
static void EnumValueMap_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(EnumValueMap_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void EnumValueMap_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(EnumValueMap_obj::__mClass,"__mClass");
};
#endif
hx::Class EnumValueMap_obj::__mClass;
void EnumValueMap_obj::__register()
{
hx::Object *dummy = new EnumValueMap_obj;
EnumValueMap_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("haxe.ds.EnumValueMap","\xe3","\xc7","\x41","\x58");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = EnumValueMap_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(EnumValueMap_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< EnumValueMap_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = EnumValueMap_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = EnumValueMap_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = EnumValueMap_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace haxe
} // end namespace ds
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/permissions/chrome_api_permissions.h"
#include "chrome/common/extensions/permissions/api_permission.h"
#include "chrome/common/extensions/permissions/api_permission_set.h"
#include "chrome/common/extensions/permissions/bluetooth_device_permission.h"
#include "chrome/common/extensions/permissions/media_galleries_permission.h"
#include "chrome/common/extensions/permissions/permission_message.h"
#include "chrome/common/extensions/permissions/permissions_info.h"
#include "chrome/common/extensions/permissions/socket_permission.h"
#include "chrome/common/extensions/permissions/usb_device_permission.h"
#include "grit/generated_resources.h"
namespace extensions {
namespace {
const char kOldUnlimitedStoragePermission[] = "unlimited_storage";
const char kWindowsPermission[] = "windows";
template<typename T> APIPermission* CreateAPIPermission(
const APIPermissionInfo* permission) {
return new T(permission);
}
} // namespace
std::vector<APIPermissionInfo*> ChromeAPIPermissions::GetAllPermissions()
const {
struct PermissionRegistration {
APIPermission::ID id;
const char* name;
int flags;
int l10n_message_id;
PermissionMessage::ID message_id;
APIPermissionInfo::APIPermissionConstructor constructor;
} PermissionsToRegister[] = {
// Register permissions for all extension types.
{ APIPermission::kBackground, "background" },
{ APIPermission::kClipboardRead, "clipboardRead",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD,
PermissionMessage::kClipboard },
{ APIPermission::kClipboardWrite, "clipboardWrite" },
{ APIPermission::kDeclarativeContent, "declarativeContent" },
{ APIPermission::kDeclarativeWebRequest, "declarativeWebRequest" },
{ APIPermission::kDownloads, "downloads", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS,
PermissionMessage::kDownloads },
{ APIPermission::kIdentity, "identity" },
{ APIPermission::kExperimental, "experimental",
APIPermissionInfo::kFlagCannotBeOptional },
// NOTE(kalman): this is provided by a manifest property but needs to
// appear in the install permission dialogue, so we need a fake
// permission for it. See http://crbug.com/247857.
{ APIPermission::kWebConnectable, "webConnectable",
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_WEB_CONNECTABLE,
PermissionMessage::kWebConnectable},
{ APIPermission::kGeolocation, "geolocation",
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION,
PermissionMessage::kGeolocation },
{ APIPermission::kNotification, "notifications" },
{ APIPermission::kScreensaver, "screensaver" },
{ APIPermission::kUnlimitedStorage, "unlimitedStorage",
APIPermissionInfo::kFlagCannotBeOptional },
// Register extension permissions.
{ APIPermission::kActiveTab, "activeTab" },
{ APIPermission::kAdView, "adview" },
{ APIPermission::kAlarms, "alarms" },
{ APIPermission::kBookmark, "bookmarks", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS,
PermissionMessage::kBookmarks },
{ APIPermission::kBrowsingData, "browsingData" },
{ APIPermission::kContentSettings, "contentSettings",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS,
PermissionMessage::kContentSettings },
{ APIPermission::kContextMenus, "contextMenus" },
{ APIPermission::kCookie, "cookies" },
{ APIPermission::kFileBrowserHandler, "fileBrowserHandler",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kFontSettings, "fontSettings",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kHistory, "history", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,
PermissionMessage::kBrowsingHistory },
{ APIPermission::kIdle, "idle" },
{ APIPermission::kInput, "input", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_INPUT,
PermissionMessage::kInput },
{ APIPermission::kLocation, "location",
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION,
PermissionMessage::kGeolocation },
{ APIPermission::kManagement, "management", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT,
PermissionMessage::kManagement },
{ APIPermission::kNativeMessaging, "nativeMessaging",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_NATIVE_MESSAGING,
PermissionMessage::kNativeMessaging },
{ APIPermission::kPower, "power", },
{ APIPermission::kPrivacy, "privacy", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_PRIVACY,
PermissionMessage::kPrivacy },
{ APIPermission::kSessionRestore, "sessionRestore" },
{ APIPermission::kStorage, "storage" },
{ APIPermission::kSyncFileSystem, "syncFileSystem",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_SYNCFILESYSTEM,
PermissionMessage::kSyncFileSystem },
{ APIPermission::kTab, "tabs", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_TABS,
PermissionMessage::kTabs },
{ APIPermission::kTopSites, "topSites", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,
PermissionMessage::kBrowsingHistory },
{ APIPermission::kTts, "tts", 0, APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kTtsEngine, "ttsEngine",
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE,
PermissionMessage::kTtsEngine },
{ APIPermission::kWebNavigation, "webNavigation",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs },
{ APIPermission::kWebRequest, "webRequest" },
{ APIPermission::kWebRequestBlocking, "webRequestBlocking" },
{ APIPermission::kWebView, "webview",
APIPermissionInfo::kFlagCannotBeOptional },
// Register private permissions.
{ APIPermission::kActivityLogPrivate, "activityLogPrivate",
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_ACTIVITY_LOG_PRIVATE,
PermissionMessage::kActivityLogPrivate },
{ APIPermission::kAutoTestPrivate, "autotestPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kBookmarkManagerPrivate, "bookmarkManagerPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kChromeosInfoPrivate, "chromeosInfoPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kCommandLinePrivate, "commandLinePrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kDeveloperPrivate, "developerPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kDiagnostics, "diagnostics",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kDial, "dial", APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kDownloadsInternal, "downloadsInternal" },
{ APIPermission::kFileBrowserHandlerInternal, "fileBrowserHandlerInternal",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kFileBrowserPrivate, "fileBrowserPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kIdentityPrivate, "identityPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kNetworkingPrivate, "networkingPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kMediaPlayerPrivate, "mediaPlayerPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kMetricsPrivate, "metricsPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kMusicManagerPrivate, "musicManagerPrivate",
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_MUSIC_MANAGER_PRIVATE,
PermissionMessage::kMusicManagerPrivate },
{ APIPermission::kPreferencesPrivate, "preferencesPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kSystemPrivate, "systemPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kCloudPrintPrivate, "cloudPrintPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kInputMethodPrivate, "inputMethodPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kEchoPrivate, "echoPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kFeedbackPrivate, "feedbackPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kRtcPrivate, "rtcPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kTerminalPrivate, "terminalPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kWallpaperPrivate, "wallpaperPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kWebRequestInternal, "webRequestInternal" },
{ APIPermission::kWebSocketProxyPrivate, "webSocketProxyPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kWebstorePrivate, "webstorePrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kMediaGalleriesPrivate, "mediaGalleriesPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kStreamsPrivate, "streamsPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kEnterprisePlatformKeysPrivate,
"enterprise.platformKeysPrivate",
APIPermissionInfo::kFlagCannotBeOptional },
// Full url access permissions.
{ APIPermission::kDebugger, "debugger",
APIPermissionInfo::kFlagImpliesFullURLAccess |
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_DEBUGGER,
PermissionMessage::kDebugger },
{ APIPermission::kDevtools, "devtools",
APIPermissionInfo::kFlagImpliesFullURLAccess |
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kPageCapture, "pageCapture",
APIPermissionInfo::kFlagImpliesFullURLAccess },
{ APIPermission::kTabCapture, "tabCapture",
APIPermissionInfo::kFlagImpliesFullURLAccess },
{ APIPermission::kPlugin, "plugin",
APIPermissionInfo::kFlagImpliesFullURLAccess |
APIPermissionInfo::kFlagImpliesFullAccess |
APIPermissionInfo::kFlagCannotBeOptional,
IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS,
PermissionMessage::kFullAccess },
{ APIPermission::kProxy, "proxy",
APIPermissionInfo::kFlagImpliesFullURLAccess |
APIPermissionInfo::kFlagCannotBeOptional },
// Platform-app permissions.
{ APIPermission::kSerial, "serial", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_SERIAL,
PermissionMessage::kSerial },
// Because warning messages for the "socket" permission vary based on the
// permissions parameters, no message ID or message text is specified here.
// The message ID and text used will be determined at run-time in the
// |SocketPermission| class.
{ APIPermission::kSocket, "socket",
APIPermissionInfo::kFlagCannotBeOptional, 0,
PermissionMessage::kNone, &CreateAPIPermission<SocketPermission> },
{ APIPermission::kAppCurrentWindowInternal, "app.currentWindowInternal" },
{ APIPermission::kAppRuntime, "app.runtime" },
{ APIPermission::kAppWindow, "app.window" },
{ APIPermission::kAudioCapture, "audioCapture",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE,
PermissionMessage::kAudioCapture },
{ APIPermission::kVideoCapture, "videoCapture",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE,
PermissionMessage::kVideoCapture },
// The permission string for "fileSystem" is only shown when "write" is
// present. Read-only access is only granted after the user has been shown
// a file chooser dialog and selected a file. Selecting the file is
// considered consent to read it.
{ APIPermission::kFileSystem, "fileSystem" },
{ APIPermission::kFileSystemRetainFiles, "fileSystem.retainFiles" },
{ APIPermission::kFileSystemWrite, "fileSystem.write",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE,
PermissionMessage::kFileSystemWrite },
// Because warning messages for the "mediaGalleries" permission vary based
// on the permissions parameters, no message ID or message text is
// specified here.
// The message ID and text used will be determined at run-time in the
// |MediaGalleriesPermission| class.
{ APIPermission::kMediaGalleries, "mediaGalleries",
APIPermissionInfo::kFlagNone, 0,
PermissionMessage::kNone,
&CreateAPIPermission<MediaGalleriesPermission> },
{ APIPermission::kPushMessaging, "pushMessaging",
APIPermissionInfo::kFlagCannotBeOptional },
{ APIPermission::kBluetooth, "bluetooth", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_BLUETOOTH,
PermissionMessage::kBluetooth },
{ APIPermission::kBluetoothDevice, "bluetoothDevices",
APIPermissionInfo::kFlagNone, 0, PermissionMessage::kNone,
&CreateAPIPermission<BluetoothDevicePermission> },
{ APIPermission::kUsb, "usb", APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_USB,
PermissionMessage::kUsb },
{ APIPermission::kUsbDevice, "usbDevices",
APIPermissionInfo::kFlagNone, 0, PermissionMessage::kNone,
&CreateAPIPermission<UsbDevicePermission> },
{ APIPermission::kSystemIndicator, "systemIndicator",
APIPermissionInfo::kFlagNone,
IDS_EXTENSION_PROMPT_WARNING_SYSTEM_INDICATOR,
PermissionMessage::kSystemIndicator },
{ APIPermission::kSystemInfoCpu, "systemInfo.cpu" },
{ APIPermission::kSystemInfoMemory, "systemInfo.memory" },
{ APIPermission::kSystemInfoDisplay, "systemInfo.display" },
{ APIPermission::kPointerLock, "pointerLock" },
{ APIPermission::kFullscreen, "fullscreen" },
{ APIPermission::kAudio, "audio" },
};
std::vector<APIPermissionInfo*> permissions;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) {
const PermissionRegistration& pr = PermissionsToRegister[i];
permissions.push_back(new APIPermissionInfo(
pr.id, pr.name, pr.l10n_message_id,
pr.message_id ? pr.message_id : PermissionMessage::kNone,
pr.flags,
pr.constructor));
}
return permissions;
}
std::vector<PermissionsInfo::AliasInfo> ChromeAPIPermissions::GetAllAliases()
const {
// Register aliases.
std::vector<PermissionsInfo::AliasInfo> aliases;
aliases.push_back(PermissionsInfo::AliasInfo(
"unlimitedStorage", kOldUnlimitedStoragePermission));
aliases.push_back(PermissionsInfo::AliasInfo(
"tabs", kWindowsPermission));
return aliases;
}
} // namespace extensions
|
#ifndef INC_METTLE_SUITE_MAKE_SUITE_HPP
#define INC_METTLE_SUITE_MAKE_SUITE_HPP
#include <algorithm>
#include <array>
#include <cstdint>
#include <functional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "attributes.hpp"
#include "compiled_suite.hpp"
#include "factory.hpp"
#include "detail/test_caller.hpp"
#include "../output.hpp"
namespace mettle {
namespace detail {
template<typename T>
constexpr const T& max(const T& lhs, const T& rhs)
{
return lhs >= rhs ? lhs : rhs;
}
template<typename T>
std::string annotate_type(const std::string &s) {
return s + " (" + type_name<T>() + ")";
}
template<typename Tuple>
struct compiled_subsuite_helper;
template<typename ...T>
struct compiled_subsuite_helper<std::tuple<T...>> {
using type = compiled_suite<void(T&...)>;
};
}
template<typename Tuple>
using compiled_subsuite = typename detail::compiled_subsuite_helper<Tuple>
::type;
template<typename Factory, typename ParentFixture, typename ...Fixture>
class subsuite_builder;
template<typename ParentFixture, typename ...Fixture, typename Factory,
typename F>
compiled_subsuite<ParentFixture>
make_subsuite(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f);
template<typename ParentFixture, typename ...Fixture, typename Factory,
typename F>
inline compiled_subsuite<ParentFixture>
make_subsuite(const std::string &name, Factory &&factory, const F &f) {
return make_subsuite<ParentFixture, Fixture...>(
name, {}, std::forward<Factory>(factory), f
);
}
template<typename ParentFixture, typename ...Fixture, typename F>
inline compiled_subsuite<ParentFixture>
make_subsuite(const std::string &name, const attributes &attrs, const F &f) {
return make_subsuite<ParentFixture, Fixture...>(name, attrs, auto_factory, f);
}
template<typename ParentFixture, typename ...Fixture, typename F>
inline compiled_subsuite<ParentFixture>
make_subsuite(const std::string &name, const F &f) {
return make_subsuite<ParentFixture, Fixture...>(name, auto_factory, f);
}
template<typename ParentFixture, typename Factory, typename F>
std::array<compiled_subsuite<ParentFixture>, 1>
make_subsuites(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
return {{ make_subsuite<ParentFixture>(
name, attrs, std::forward<Factory>(factory), f
) }};
}
template<typename ParentFixture, typename Fixture, typename Factory, typename F>
std::array<compiled_subsuite<ParentFixture>, 1>
make_subsuites(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
return {{ make_subsuite<ParentFixture, Fixture>(
name, attrs, std::forward<Factory>(factory), f
) }};
}
template<typename ParentFixture, typename First, typename Second,
typename ...Rest, typename Factory, typename F>
std::array<compiled_subsuite<ParentFixture>, sizeof...(Rest) + 2>
make_subsuites(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
using detail::annotate_type;
return {{
make_subsuite<ParentFixture, First>(
annotate_type<First>(name), attrs, factory, f
),
make_subsuite<ParentFixture, Second>(
annotate_type<Second>(name), attrs, factory, f
),
make_subsuite<ParentFixture, Rest>(
annotate_type<Rest>(name), attrs, factory, f
)...
}};
}
template<typename ParentFixture, typename ...Fixture, typename Factory,
typename F>
inline std::array<compiled_subsuite<ParentFixture>,
detail::max(sizeof...(Fixture), std::size_t(1))>
make_subsuites(const std::string &name, Factory &&factory, const F &f) {
return make_subsuites<ParentFixture, Fixture...>(
name, {}, std::forward<Factory>(factory), f
);
}
template<typename ParentFixture, typename ...Fixture, typename F>
inline std::array<compiled_subsuite<ParentFixture>,
detail::max(sizeof...(Fixture), std::size_t(1))>
make_subsuites(const std::string &name, const attributes &attrs, const F &f) {
return make_subsuites<ParentFixture, Fixture...>(
name, attrs, auto_factory, f
);
}
template<typename ParentFixture, typename ...Fixture, typename F>
inline std::array<compiled_subsuite<ParentFixture>,
detail::max(sizeof...(Fixture), std::size_t(1))>
make_subsuites(const std::string &name, const F &f) {
return make_subsuites<ParentFixture, Fixture...>(name, auto_factory, f);
}
template<typename ...T>
class suite_builder_base {
public:
using tuple_type = std::tuple<T...>;
using function_type = std::function<void(T&...)>;
suite_builder_base(std::string name, attributes attrs)
: name_(std::move(name)), attrs_(std::move(attrs)) {}
suite_builder_base(const suite_builder_base &) = delete;
suite_builder_base & operator =(const suite_builder_base &) = delete;
void setup(function_type f) {
setup_ = std::move(f);
}
void teardown(function_type f) {
teardown_ = std::move(f);
}
void test(std::string name, function_type f) {
tests_.push_back({std::move(name), std::move(f), {}});
}
void test(std::string name, attributes attrs, function_type f) {
tests_.push_back({
std::move(name), std::move(f), std::move(attrs)
});
}
void subsuite(compiled_suite<void(T&...)> subsuite) {
subsuites_.push_back(std::move(subsuite));
}
template<typename Subsuites>
void subsuite(Subsuites &&subsuites) {
for(auto &&i : subsuites)
subsuites_.push_back(detail::forward_if<Subsuites>(i));
}
template<typename ...Fixture, typename ...Args>
void subsuite(const std::string &name, const attributes &attrs,
Args &&...args) {
subsuite(make_subsuites<tuple_type, Fixture...>(
name, attrs, std::forward<Args>(args)...
));
}
template<typename ...Fixture, typename ...Args>
void subsuite(const std::string &name, Args &&...args) {
subsuite(make_subsuites<tuple_type, Fixture...>(
name, std::forward<Args>(args)...
));
}
protected:
struct test_info {
std::string name;
function_type function;
attributes attrs;
};
std::string name_;
attributes attrs_;
function_type setup_, teardown_;
std::vector<test_info> tests_;
std::vector<compiled_suite<void(T&...)>> subsuites_;
};
namespace detail {
template<typename ParentFixture, typename OutChild>
struct suite_builder_base_helper;
template<typename ...Parent, typename OutChild>
struct suite_builder_base_helper<std::tuple<Parent...>, OutChild> {
using type = suite_builder_base<Parent..., OutChild>;
};
template<typename ...Parent>
struct suite_builder_base_helper<std::tuple<Parent...>, void> {
using type = suite_builder_base<Parent...>;
};
}
template<typename Factory, typename Parent, typename ...InChild>
struct suite_builder_base_type {
using type = typename detail::suite_builder_base_helper<
Parent, detail::transform_fixture_t<Factory, InChild...>
>::type;
};
template<typename Factory, typename Parent, typename ...InChild>
using suite_builder_base_t = typename suite_builder_base_type<
Factory, Parent, InChild...
>::type;
template<typename Factory, typename ParentFixture, typename ...Fixture>
class subsuite_builder
: public suite_builder_base_t<Factory, ParentFixture, Fixture...> {
private:
static_assert(sizeof...(Fixture) < 2, "only specify one fixture at a time!");
using base = suite_builder_base_t<Factory, ParentFixture, Fixture...>;
public:
using factory_type = Factory;
using fixture_type = detail::first_t<Fixture...>;
using compiled_suite_type = compiled_subsuite<ParentFixture>;
subsuite_builder(const std::string &name, const attributes &attrs,
Factory factory)
: base(name, attrs), factory_(factory) {}
compiled_suite_type finalize() {
return compiled_suite_type(
std::move(base::name_), std::move(base::tests_),
std::move(base::subsuites_), std::move(base::attrs_),
std::bind(&subsuite_builder::wrap_test, this, std::placeholders::_1)
);
}
private:
auto wrap_test(typename base::function_type test) {
return detail::test_caller<factory_type, ParentFixture, Fixture...>{
factory_, base::setup_, base::teardown_, std::move(test)
};
}
factory_type factory_;
};
template<typename Exception, typename Factory, typename ...T>
class suite_builder : public suite_builder_base_t<Factory, std::tuple<>, T...> {
private:
static_assert(sizeof...(T) < 2, "only specify one fixture at a time!");
using base = suite_builder_base_t<Factory, std::tuple<>, T...>;
public:
using exception_type = Exception;
using factory_type = Factory;
using fixture_type = detail::first_t<T...>;
suite_builder(const std::string &name, const attributes &attrs,
Factory factory)
: base(name, attrs), factory_(factory) {}
runnable_suite finalize() {
return runnable_suite(
std::move(base::name_), std::move(base::tests_),
std::move(base::subsuites_), std::move(base::attrs_),
std::bind(&suite_builder::wrap_test, this, std::placeholders::_1)
);
}
private:
auto wrap_test(typename base::function_type test) {
return [
test_function = detail::test_caller<factory_type, std::tuple<>, T...>{
factory_, base::setup_, base::teardown_, std::move(test)
}
]() mutable -> test_result {
bool passed = false;
std::string message;
try {
test_function();
passed = true;
}
catch(const exception_type &e) {
message = e.what();
}
catch(const std::exception &e) {
message = std::string("Uncaught exception: ") + to_printable(e);
}
catch(...) {
message = "Unknown exception";
}
return { passed, message };
};
}
factory_type factory_;
};
template<typename Exception, typename ...Fixture, typename Factory, typename F>
runnable_suite
make_basic_suite(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
using FactoryValue = typename std::remove_reference<Factory>::type;
suite_builder<Exception, FactoryValue, Fixture...> builder(
name, attrs, std::forward<Factory>(factory)
);
f(builder);
return builder.finalize();
}
template<typename Exception, typename ...Fixture, typename Factory, typename F>
inline runnable_suite
make_basic_suite(const std::string &name, Factory &&factory, const F &f) {
return make_basic_suite<Exception, Fixture...>(
name, {}, std::forward<Factory>(factory), f
);
}
template<typename Exception, typename ...Fixture, typename F>
inline runnable_suite
make_basic_suite(const std::string &name, const attributes &attrs, const F &f) {
return make_basic_suite<Exception, Fixture...>(name, attrs, auto_factory, f);
}
template<typename Exception, typename ...Fixture, typename F>
inline runnable_suite
make_basic_suite(const std::string &name, const F &f) {
return make_basic_suite<Exception, Fixture...>(name, auto_factory, f);
}
template<typename Exception, typename Factory, typename F>
std::array<runnable_suite, 1>
make_basic_suites(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
return {{ make_basic_suite<Exception>(
name, attrs, std::forward<Factory>(factory), f
) }};
}
template<typename Exception, typename Fixture, typename Factory, typename F>
std::array<runnable_suite, 1>
make_basic_suites(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
return {{ make_basic_suite<Exception, Fixture>(
name, attrs, std::forward<Factory>(factory), f
) }};
}
template<typename Exception, typename First, typename Second,
typename ...Rest, typename Factory, typename F>
std::array<runnable_suite, sizeof...(Rest) + 2>
make_basic_suites(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
using detail::annotate_type;
return {{
make_basic_suite<Exception, First>(
annotate_type<First>(name), attrs, factory, f
),
make_basic_suite<Exception, Second>(
annotate_type<Second>(name), attrs, factory, f
),
make_basic_suite<Exception, Rest>(
annotate_type<Rest>(name), attrs, factory, f
)...
}};
}
template<typename Exception, typename ...Fixture, typename Factory, typename F>
inline std::array<runnable_suite, detail::max(sizeof...(Fixture), std::size_t(1))>
make_basic_suites(const std::string &name, Factory &&factory, const F &f) {
return make_basic_suites<Exception, Fixture...>(
name, {}, std::forward<Factory>(factory), f
);
}
template<typename Exception, typename ...Fixture, typename F>
inline std::array<runnable_suite, detail::max(sizeof...(Fixture), std::size_t(1))>
make_basic_suites(const std::string &name, const attributes &attrs,
const F &f) {
return make_basic_suites<Exception, Fixture...>(name, attrs, auto_factory, f);
}
template<typename Exception, typename ...Fixture, typename F>
inline std::array<runnable_suite, detail::max(sizeof...(Fixture), std::size_t(1))>
make_basic_suites(const std::string &name, const F &f) {
return make_basic_suites<Exception, Fixture...>(name, auto_factory, f);
}
template<typename ParentFixture, typename ...Fixture, typename Factory,
typename F>
compiled_subsuite<ParentFixture>
make_subsuite(const std::string &name, const attributes &attrs,
Factory &&factory, const F &f) {
using FactoryValue = typename std::remove_reference<Factory>::type;
subsuite_builder<FactoryValue, ParentFixture, Fixture...> builder(
name, attrs, std::forward<Factory>(factory)
);
f(builder);
return builder.finalize();
}
template<typename ...Fixture, typename Parent, typename ...Args>
inline compiled_subsuite<typename Parent::tuple_type>
make_subsuite(const Parent &, const std::string &name, const attributes &attrs,
Args &&...args) {
return make_subsuite<typename Parent::tuple_type, Fixture...>(
name, attrs, std::forward<Args>(args)...
);
}
template<typename ...Fixture, typename Parent, typename ...Args>
inline compiled_subsuite<typename Parent::tuple_type>
make_subsuite(const Parent &, const std::string &name, Args &&...args) {
return make_subsuite<typename Parent::tuple_type, Fixture...>(
name, std::forward<Args>(args)...
);
}
template<typename ...Fixture, typename Parent, typename ...Args>
inline std::array<compiled_subsuite<typename Parent::tuple_type>,
detail::max(sizeof...(Fixture), std::size_t(1))>
make_subsuites(const Parent &, const std::string &name, const attributes &attrs,
Args &&...args) {
return make_subsuites<typename Parent::tuple_type, Fixture...>(
name, attrs, std::forward<Args>(args)...
);
}
template<typename ...Fixture, typename Parent, typename ...Args>
inline std::array<compiled_subsuite<typename Parent::tuple_type>,
detail::max(sizeof...(Fixture), std::size_t(1))>
make_subsuites(const Parent &, const std::string &name, Args &&...args) {
return make_subsuites<typename Parent::tuple_type, Fixture...>(
name, std::forward<Args>(args)...
);
}
template<typename ...Fixture, typename Parent, typename ...Args>
inline void
subsuite(Parent &builder, const std::string &name, const attributes &attrs,
Args &&...args) {
builder.template subsuite<Fixture...>(
name, attrs, std::forward<Args>(args)...
);
}
template<typename ...Fixture, typename Parent, typename ...Args>
inline void
subsuite(Parent &builder, const std::string &name, Args &&...args) {
builder.template subsuite<Fixture...>(name, std::forward<Args>(args)...);
}
template<typename T>
struct fixture_type {
using type = typename std::remove_reference_t<T>::fixture_type;
};
template<typename T>
using fixture_type_t = typename fixture_type<T>::type;
} // namespace mettle
#endif
|
/*
859. Buddy Strings
Problem
Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
Example 1:
Input: A = "ab", B = "ba"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.
Example 2:
Input: A = "ab", B = "ab"
Output: false
Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.
Example 3:
Input: A = "aa", B = "aa"
Output: true
Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.
Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example 5:
Input: A = "", B = "aa"
Output: false
Approach:
1- Count subscripts of characters in the character strings A and B that do not match.
2- When the number of unmatched subscripts is not equal to 0 or 2, B cannot be obtained from A.
3- When the number of unmatched subscripts is equal to 0, the characters in A and B are exactly the same, and there are also repeated characters in A.
4 -When the number of unmatched subscripts is equal to 2, it is judged whether they match after exchanging two pairs of characters.
*/
class Solution {
public:
bool buddyStrings(const string & a, const string & b) {
if (a.size() != b.size()) return false;
vector < int > index_of_mismatch;
for (int i = 0; i < a.size(); i++)
if (a[i] != b[i]) {
index_of_mismatch.push_back(i);
if (2 < index_of_mismatch.size()) return false;
}
if (index_of_mismatch.size() == 0) {
return set < char > (a.begin(), a.end()).size() < a.size();
} else if (index_of_mismatch.size() == 2) {
return a[index_of_mismatch[0]] == b[index_of_mismatch[1]] &&
a[index_of_mismatch[1]] == b[index_of_mismatch[0]];
}
return false;
}
};
|
//
// Created by connor on 7/18/18.
//
#include "WebsocketImpl.h"
namespace Sova
{
WebsocketImpl::WebsocketImpl(Websocket* wrapperWebsocket, Ref <String> address)
{
this->wrapperWebsocket = wrapperWebsocket;
this->webSocketClient.onMessage([&](Oryol::String msg) {
this->wrapperWebsocket->receiveMessage(msg.AsCStr(), msg.Length());
});
this->webSocketClient.onError([&](Oryol::String msg) {
this->wrapperWebsocket->receiveError(msg.AsCStr());
});
this->webSocketClient.onOpen([&]() {
this->wrapperWebsocket->receiveOpen();
});
this->webSocketClient.onClose([&](Oryol::String msg) {
this->wrapperWebsocket->receiveClose(msg.AsCStr());
});
this->webSocketClient.connect(address->AsCStr());
}
void WebsocketImpl::update()
{
this->webSocketClient.update();
}
void WebsocketImpl::send(Oryol::String message)
{
this->webSocketClient.send(message);
}
void WebsocketImpl::close()
{
this->webSocketClient.close();
}
int WebsocketImpl::getReadyState() {
return this->webSocketClient.getReadyState();
}
void WebsocketImpl::setEscapeCharacter(char c) {
this->webSocketClient.setEscapeCharacter(c);
}
}
|
#include "camera.h"
#include "keyboard.h"
#include "common/math.h"
#include <QMouseEvent>
#include <QWheelEvent>
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
namespace gnssShadowing {
namespace gui {
Camera::Camera(Keyboard& keyboard, float x, float y, float zoom) :
m_keyboard(keyboard),
m_x(x),
m_y(y),
m_zoom(zoom),
m_last_x(0),
m_last_y(0),
m_dragging(false),
m_pitch(-60),
m_yaw(180),
m_rotationGain(0.1)
{}
Camera::~Camera()
{}
void Camera::setProjection(int display_width, int display_height)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
int x_min, x_max, y_min, y_max;
x_min = 0 -(display_width/2);
y_min = 0 -(display_height/2);
x_max = x_min + display_width;
y_max = y_min + display_height;
glOrtho(x_min,x_max,y_min,y_max,-1280,1280);
}
void Camera::setView()
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glScalef(m_zoom, m_zoom, 1);
glTranslatef(-m_x,-m_y,0);
glRotatef(m_pitch,1,0,0);
glRotatef(m_yaw,0,0,1);
}
void Camera::mousePressEvent(QMouseEvent *event)
{
Qt::MouseButtons buttons = event->buttons();
m_last_x = event->x();
m_last_y = event->y();
m_dragging = true;
m_dx_filtered = m_dy_filtered = 0;
}
void Camera::mouseReleaseEvent(QMouseEvent *event)
{
m_dragging = false;
}
void Camera::mouseMoveEvent(QMouseEvent *event)
{
if (m_dragging)
{
Qt::MouseButtons buttons = event->buttons();
int dx = event->x() - m_last_x;
int dy = event->y() - m_last_y;
if (buttons & Qt::LeftButton)
{
m_x -= dx / m_zoom;
m_y -= (-dy) / m_zoom; // -dy because image y-axis is inverse to world y-axis
}
else if (buttons & Qt::RightButton)
{
m_dx_filtered = dx*m_rotationGain+(1-m_rotationGain)*m_dx_filtered;
m_dy_filtered = dy*m_rotationGain+(1-m_rotationGain)*m_dy_filtered;
m_yaw += m_dx_filtered;
m_pitch += m_dy_filtered;
}
m_last_x = event->x();
m_last_y = event->y();
}
}
void Camera::wheelEvent(QWheelEvent *event)
{
// QWheelEvent.angleDelta().y() Returns the distance that the wheel is rotated, in eighths of a degree.
float deltaDeg = ((float)event->angleDelta().y())/8.;
//float z_per_deg = 1 / 15.
if (deltaDeg > 0)
{
m_zoom *= 1.1;
}
else if (deltaDeg < 0)
{
m_zoom *= 0.9;
}
}
} // namespace gui
} // namespace gnssShadowing
|
///*|-----------------------------------------------------------------------------
// *| This source code is provided under the Apache 2.0 license --
// *| and is provided AS IS with no warranty or guarantee of fit for purpose. --
// *| See the project's LICENSE.md for details. --
// *| Copyright (C) 2019 Refinitiv. All rights reserved. --
///*|-----------------------------------------------------------------------------
//APIQA this file is QATools standalone. See qa_readme.txt for details about this tool.
#include "IProvider.h"
using namespace thomsonreuters::ema::access;
using namespace thomsonreuters::ema::rdm;
using namespace std;
UInt64 itemHandle = 0;
UInt32 fragmentationSize = 9600;
DataDictionary dataDictionary;
RefreshMsg refreshMsg;
Series series;
Int32 currentValue;
bool result;
void AppClient::processLoginRequest( const ReqMsg& reqMsg, const OmmProviderEvent& event )
{
event.getProvider().submit( refreshMsg.clear().domainType(MMT_LOGIN).name(reqMsg.getName()).nameType(USER_NAME).complete().
attrib( ElementList().complete() ).solicited( true ).state( OmmState::OpenEnum, OmmState::OkEnum, OmmState::NoneEnum, "Login accepted" ) ,
event.getHandle() );
}
void AppClient::processMarketPriceRequest( const ReqMsg& reqMsg, const OmmProviderEvent& event )
{
if ( itemHandle != 0 )
{
processInvalidItemRequest( reqMsg, event );
return;
}
event.getProvider().submit( refreshMsg.clear().name(reqMsg.getName()).serviceName(reqMsg.getServiceName()).solicited(true).
state( OmmState::OpenEnum, OmmState::OkEnum, OmmState::NoneEnum, "Refresh Completed" ).
payload( FieldList().
addReal( 22, 3990, OmmReal::ExponentNeg2Enum ).
addReal( 25, 3994, OmmReal::ExponentNeg2Enum ).
addReal( 30, 9, OmmReal::Exponent0Enum ).
addReal( 31, 19, OmmReal::Exponent0Enum ).
complete() ).
complete(), event.getHandle() );
itemHandle = event.getHandle();
}
void AppClient::processDictionaryRequest(const ReqMsg& reqMsg, const OmmProviderEvent& event)
{
result = false;
refreshMsg.clear().clearCache( true );
if ( reqMsg.getName() == "RWFFld" )
{
currentValue = dataDictionary.getMinFid();
//APIQA
fragmentationSize = 9600;
while ( !result )
{
fragmentationSize = fragmentationSize + 10000;
result = dataDictionary.encodeFieldDictionary( series, currentValue, reqMsg.getFilter(), fragmentationSize );
// END APIQA
event.getProvider().submit( refreshMsg.name( reqMsg.getName() ).serviceName( reqMsg.getServiceName() ).domainType( MMT_DICTIONARY ).
filter( reqMsg.getFilter() ).payload( series ).complete( result ).solicited( true ), event.getHandle() );
refreshMsg.clear();
}
}
else if ( reqMsg.getName() == "RWFEnum" )
{
currentValue = 0;
//APIQA
fragmentationSize = 9600;
while ( !result )
{
fragmentationSize = fragmentationSize + 10000;
result = dataDictionary.encodeEnumTypeDictionary( series, currentValue, reqMsg.getFilter(), fragmentationSize );
//END APIQA
event.getProvider().submit( refreshMsg.name( reqMsg.getName() ).serviceName( reqMsg.getServiceName() ).domainType( MMT_DICTIONARY ).
filter( reqMsg.getFilter() ).payload( series ).complete( result ).solicited( true ), event.getHandle() );
refreshMsg.clear();
}
}
}
void AppClient::processInvalidItemRequest(const ReqMsg& reqMsg, const OmmProviderEvent& event)
{
event.getProvider().submit( StatusMsg().name( reqMsg.getName() ).serviceName( reqMsg.getServiceName() ).
domainType( reqMsg.getDomainType() ).
state( OmmState::ClosedEnum, OmmState::SuspectEnum, OmmState::NotFoundEnum, "Item not found" ),
event.getHandle() );
}
void AppClient::onReqMsg( const ReqMsg& reqMsg, const OmmProviderEvent& event )
{
switch (reqMsg.getDomainType())
{
case MMT_LOGIN:
processLoginRequest(reqMsg, event);
break;
case MMT_MARKET_PRICE:
processMarketPriceRequest(reqMsg, event);
break;
case MMT_DICTIONARY:
processDictionaryRequest(reqMsg, event);
break;
default:
processInvalidItemRequest(reqMsg, event);
break;
}
}
void AppClient::onReissue(const ReqMsg& reqMsg, const OmmProviderEvent& event)
{
switch (reqMsg.getDomainType())
{
case MMT_DICTIONARY:
processDictionaryRequest(reqMsg, event);
break;
default:
processInvalidItemRequest(reqMsg, event);
break;
}
}
int main( int argc, char* argv[] )
{
try
{
AppClient appClient;
dataDictionary.loadFieldDictionary( "RDMFieldDictionary" );
dataDictionary.loadEnumTypeDictionary( "enumtype.def" );
OmmProvider provider( OmmIProviderConfig().adminControlDictionary( OmmIProviderConfig::UserControlEnum ), appClient );
while ( itemHandle == 0 ) sleep( 1000 );
for (Int32 i = 0; i < 60; i++)
{
provider.submit( UpdateMsg().payload( FieldList().
addReal( 22, 3391 + i, OmmReal::ExponentNeg2Enum ).
addReal( 30, 10 + i, OmmReal::Exponent0Enum ).
complete() ), itemHandle );
sleep( 1000 );
}
}
catch ( const OmmException& excp )
{
cout << excp << endl;
}
return 0;
}
//END APIQA
|
//
// TestApp.cpp
//
// $Id: //poco/1.4/Foundation/testsuite/src/TestApp.cpp#2 $
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#if defined(_WIN32)
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include <string>
#include <iostream>
#include <cstdlib>
#include <csignal>
int main(int argc, char** argv)
{
if (argc > 1)
{
std::string arg(argv[1]);
if (arg == "-hello")
{
std::cout << "Hello, world!";
}
else if (arg == "-count")
{
int n = 0;
int c = std::cin.get();
while (c != -1) { ++n; c = std::cin.get(); }
return n;
}
else if (arg == "-env")
{
const char* s = std::getenv("TESTENV");
if (s)
{
std::cout << s;
return 0;
}
else return 1;
}
else if (arg == "-raise-int")
{
std::signal(SIGINT, SIG_DFL);
std::raise(SIGINT);
}
else if (arg == "-echo-args")
{
for (int i = 2; i < argc; ++i)
{
std::cout << argv[i] << std::endl;
}
}
}
return argc - 1;
}
|
#include "world.h"
#include "room.h"
#include "exit.h"
#include "player.h"
#include "npc.h"
#include "item.h"
World::World()
{
// Rooms
Room* const cell = new Room(*this, "Player Cell", "You find yourself inside a very small cell. There is a bed tucked in the corner.");
Item* const player_bed = new Item(*this, *cell, ItemType::Furniture, "Bed", "Your bed. It's a simple wooden bed with very little padding.", 60, 1.0f, 0, true, nullptr);
Item* const envelope = new Item(*this, *player_bed, ItemType::Pickable, "Envelope", "A letter envelope.", 20, 1.0f, 5, true, nullptr);
Item* const letter = new Item(*this, *envelope, ItemType::Pickable, "Letter", "\"I'll be waiting outside for you. Hurry up and win the fight!\"\n - Amor", 20, 1.0f, 5, false, nullptr);
Room* const corridor = new Room(*this, "Jail Corridor", "The corridor extends to the east and west. There are cells to the north and south.");
Room* const other_cell = new Room(*this, "Empty Cell", "The cell is very similar to the other one. The bed is broken and a plank with nails rests on the ground.");
Item* const broken_bed = new Item(*this, *other_cell, ItemType::Furniture, "Broken bed", "The remains of a wooden bed. Looks like a heavy fight happened.", 0, 1.0f, 0, true, nullptr);
Item* const board = new Item(*this, *broken_bed, ItemType::Pickable, "Board", "This board broke off from the broken bed.", 30, 1.0f, 15, false, nullptr);
Room* const arena_lounge = new Room(*this, "Arena Lounge", "You find yourself at the arena lounge. You can see the light coming from the arena.");
Item* const banana_peel = new Item(*this, *arena_lounge, ItemType::Pickable, "Banana Peel", "A banana peel.", 20, 1.0f, 5, false, nullptr);
Room* const office = new Room(*this, "Office", "You are in your slavemaster Porcius' office. Porcius is distracted looking at some documents away from the door.");
NPC* const porcius = new NPC(*this, *office, NPCType::Porcius, "Porcius", "Your slavemaster is extremely fat and ugly. His face resembles a pig.", 30, 1.0f);
Item* const porcius_head = new Item(*this, *porcius, ItemType::BodyPart, "Porcius Head", "Porcius' head.", 60, 2.0f, 10, false, nullptr);
Item* const porcius_right_eye = new Item(*this, *porcius_head, ItemType::BodyPart, "Porcius Right Eye", "Porcius' right eye.", 10, 1.0f, 10, false, nullptr);
Item* const porcius_left_eye = new Item(*this, *porcius_head, ItemType::BodyPart, "Porcius Left Eye", "Porcius' left eye.", 10, 1.0f, 10, false, nullptr);
Item* const porcius_right_arm = new Item(*this, *porcius, ItemType::BodyPart, "Porcius Right Arm", "Porcius' right arm.", 15, 1.0f, 10, false, nullptr);
Item* const porcius_right_hand = new Item(*this, *porcius_right_arm, ItemType::BodyPart, "Porcius Right Hand", "Porcius' right hand.", 15, 1.0f, 10, true, nullptr);
Item* const porcius_left_arm = new Item(*this, *porcius, ItemType::BodyPart, "Porcius Left Arm", "Porcius' left arm.", 15, 1.0f, 10, false, nullptr);
Item* const porcius_left_hand = new Item(*this, *porcius_left_arm, ItemType::BodyPart, "Porcius Left Hand", "Porcius' left hand.", 15, 1.0f, 10, true, nullptr);
Item* const porcius_right_leg = new Item(*this, *porcius, ItemType::BodyPart, "Porcius Right Leg", "Porcius' right leg.", 15, 1.0f, 10, false, nullptr);
Item* const porcius_right_foot = new Item(*this, *porcius_right_leg, ItemType::BodyPart, "Porcius Right Foot", "Porcius' right foot.", 15, 1.0f, 10, false, nullptr);
Item* const porcius_left_leg = new Item(*this, *porcius, ItemType::BodyPart, "Porcius Left Leg", "Porcius' left leg.", 15, 1.0f, 10, false, nullptr);
Item* const porcius_left_foot = new Item(*this, *porcius_left_leg, ItemType::BodyPart, "Porcius Left Foot", "Porcius' left foot.", 15, 1.0f, 10, false, nullptr);
Item* const dagger = new Item(*this, *porcius_right_hand, ItemType::Pickable, "Dagger", "Porcius' dagger. It's decorated with gems of multiple colors.", 40, 1.0f, 20, false, nullptr);
Item* const desk_key = new Item(*this, *porcius_right_leg, ItemType::Pickable, "Desk Key", "It opens the desk in Porcius' office.", 60, 1.0f, 10, false, nullptr);
Item* const desk = new Item(*this, *office, ItemType::Furniture, "Desk", "A wooden desk. There are multiple drawers.", 150, 1.0f, 0, true, desk_key);
Item* const armory_key = new Item(*this, *desk, ItemType::Pickable, "Armory Key", "The key that opens the armory door.", 60, 1.0f, 10, false, nullptr);
Room* const armory = new Room(*this, "Armory", "The armory is enormous. There are a lot of weapons to pick from.");
Item* const sword = new Item(*this, *armory, ItemType::Pickable, "Sword", "Metal sword.", 60, 1.0f, 30, false, nullptr);
Item* const mace = new Item(*this, *armory, ItemType::Pickable, "Mace", "Metal mace.", 60, 1.0f, 30, false, nullptr);
Item* const spear = new Item(*this, *armory, ItemType::Pickable, "Spear", "Metal spear.", 60, 1.0f, 30, false, nullptr);
Room* const arena = new Room(*this, "Arena", "The arena is filled with sand and blood stains. The public cheers for Kroz, who is smirking at you.");
kroz = new NPC(*this, *arena, NPCType::Kroz, "Kroz", "He's about two heads taller than you. You can feel a great sense of danger.", 100, 1.0f);
Item* const kroz_head = new Item(*this, *kroz, ItemType::BodyPart, "Kroz Head", "Kroz's head.", 200, 2.0f, 10, false, nullptr);
Item* const kroz_right_eye = new Item(*this, *kroz_head, ItemType::BodyPart, "Kroz Right Eye", "Kroz's right eye.", 30, 1.0f, 10, false, nullptr);
Item* const kroz_left_eye = new Item(*this, *kroz_head, ItemType::BodyPart, "Kroz Left Eye", "Kroz's left eye.", 30, 1.0f, 10, false, nullptr);
Item* const kroz_right_arm = new Item(*this, *kroz, ItemType::BodyPart, "Kroz Right Arm", "Kroz's right arm.", 30, 1.0f, 10, false, nullptr);
Item* const kroz_right_hand = new Item(*this, *kroz_right_arm, ItemType::BodyPart, "Kroz Right Hand", "Kroz's right hand.", 30, 1.0f, 10, true, nullptr);
Item* const kroz_left_arm = new Item(*this, *kroz, ItemType::BodyPart, "Kroz Left Arm", "Kroz's left arm.", 30, 1.0f, 10, false, nullptr);
Item* const kroz_left_hand = new Item(*this, *kroz_left_arm, ItemType::BodyPart, "Kroz Left Hand", "Kroz's left hand.", 30, 1.0f, 10, true, nullptr);
Item* const kroz_right_leg = new Item(*this, *kroz, ItemType::BodyPart, "Kroz Right Leg", "Kroz's right leg.", 30, 1.0f, 10, false, nullptr);
Item* const kroz_right_foot = new Item(*this, *kroz_right_leg, ItemType::BodyPart, "Kroz Right Foot", "Kroz's right foot.", 30, 1.0f, 10, false, nullptr);
Item* const kroz_left_leg = new Item(*this, *kroz, ItemType::BodyPart, "Kroz Left Leg", "Kroz's left leg.", 30, 1.0f, 10, false, nullptr);
Item* const kroz_left_foot = new Item(*this, *kroz_left_leg, ItemType::BodyPart, "Kroz Left Foot", "Kroz's left foot.", 30, 1.0f, 10, false, nullptr);
Item* const axe = new Item(*this, *kroz_right_hand, ItemType::Pickable, "Axe", "Kroz's Axe. It's taller than you.", 60, 1.0f, 30, false, nullptr);
Item* const morning_star = new Item(*this, *kroz_left_hand, ItemType::Pickable, "Morning Star", "Kroz's Morning Star. A huge metal mace with spikes.", 60, 1.0f, 30, false, nullptr);
// Exits
Exit* const cell_exit = new Exit(*this, "Player Cell Door", "Door made of vertical metal bars.", 300, 1.0f, *cell, *corridor, Direction::North, nullptr);
Exit* const other_cell_exit = new Exit(*this, "Empty Cell Door", "Door made of vertical metal bars.", 300, 1.0f, *other_cell, *corridor, Direction::South, nullptr);
Exit* const arena_lounge_corridor_exit = new Exit(*this, "Lounge Door", "Simple wooden door.", 200, 1.0f, *arena_lounge, *corridor, Direction::East, nullptr);
Exit* const office_exit = new Exit(*this, "Office Door", "Simple wooden door.", 200, 1.0f, *office, *corridor, Direction::West, nullptr);
Exit* const armory_exit = new Exit(*this, "Armory Door", "Full metal door with a keylock.", 300, 1.0f, *armory, *arena_lounge, Direction::North, armory_key);
Exit* const arena_lounge_arena_exit = new Exit(*this, "Arena Entrance", "Very large wooden door.", 200, 1.0f, *arena_lounge, *arena, Direction::North, nullptr);
// Player
player = new Player(*this, *cell, "Player", "You look fine.", 75, 1.0f);
Item* const player_head = new Item(*this, *player, ItemType::BodyPart, "Player Head", "Your head.", 150, 1.0f, 10, false, nullptr);
Item* const player_right_eye = new Item(*this, *player_head, ItemType::BodyPart, "Player Right Eye", "Your right eye.", 30, 1.0f, 10, false, nullptr);
Item* const player_left_eye = new Item(*this, *player_head, ItemType::BodyPart, "Player Left Eye", "Your left eye.", 30, 1.0f, 10, false, nullptr);
Item* const player_right_arm = new Item(*this, *player, ItemType::BodyPart, "Player Right Arm", "Your right arm.", 40, 1.0f, 10, false, nullptr);
Item* const player_right_hand = new Item(*this, *player_right_arm, ItemType::BodyPart, "Player Right Hand", "Your right hand.", 30, 1.0f, 10, true, nullptr);
Item* const player_left_arm = new Item(*this, *player, ItemType::BodyPart, "Player Left Arm", "Your left arm.", 40, 1.0f, 10, false, nullptr);
Item* const player_left_hand = new Item(*this, *player_left_arm, ItemType::BodyPart, "Player Left Hand", "Your left hand.", 30, 1.0f, 10, true, nullptr);
Item* const player_right_leg = new Item(*this, *player, ItemType::BodyPart, "Player Right Leg", "Your right leg.", 40, 1.0f, 10, false, nullptr);
Item* const player_right_foot = new Item(*this, *player_right_leg, ItemType::BodyPart, "Player Right Foot", "Your right foot.", 30, 1.0f, 10, false, nullptr);
Item* const player_left_leg = new Item(*this, *player, ItemType::BodyPart, "Player Left Leg", "Your left leg.", 40, 1.0f, 10, false, nullptr);
Item* const player_left_foot = new Item(*this, *player_left_leg, ItemType::BodyPart, "Player Left Foot", "Your left foot.", 30, 1.0f, 10, false, nullptr);
}
World::~World()
{
for (Entity* const entity : entities)
{
delete entity;
}
}
bool World::Tick(const std::vector<std::string>& tokens)
{
const bool should_update = ParseCommand(tokens);
if (should_update)
{
for (Entity* const entity : entities)
{
entity->Update();
}
}
if (kroz->health == 0)
{
std::cout << "\n";
std::cout << "Congratulations! You have achieved freedom!\n";
std::cout << "\n";
return true;
}
if (player->health == 0)
{
std::cout << "\n";
std::cout << "You lose.\n";
std::cout << "\n";
return true;
}
return false;
}
bool World::ParseCommand(const std::vector<std::string>& tokens)
{
if (tokens.size() >= 1) {
if (tokens[0] == "help")
{
std::cout << "Commands:\n";
std::cout << " help - Shows this information.\n";
std::cout << " examine [object] - Examine something. If written with no arguments it examines the current room.\n";
std::cout << " go <direction> - Move towards a direction.\n";
std::cout << " take <object> - Picks up an item.\n";
std::cout << " drop <object> - Drops an item.\n";
std::cout << " open <object> - Uses a key in your inventory to open an object.\n";
std::cout << " put <object> in <object> - Puts an item inside an object.\n";
std::cout << " hit <object> with <object> - Hits something with the given object.\n";
std::cout << "Objects:\n";
std::cout << " Anything with a name counts as an object.\n";
std::cout << " Body parts and exits also count as objects.\n";
std::cout << " You have to be explicit when giving the name of an object or it won't be recognized.\n";
std::cout << "Directions:\n";
std::cout << " The only accepted directions are north, south, east and west.\n";
std::cout << "Combat:\n";
std::cout << " Different objects deal different amounts of damage.\n";
std::cout << " Remember you can choose body parts as a target.\n";
std::cout << " Body parts can be severed when hit, dropping to the floor.\n";
std::cout << " You can hit the body of a creature by attaking it directly.\n";
return false;
}
else if (tokens[0] == "examine")
{
const std::string name = JoinTokens(tokens, 1, tokens.size());
if (player->OnExamine(name))
{
return false;
}
else
{
std::cout << "The thing you tried to examine doesn't exist.\n";
return false;
}
}
else if (tokens[0] == "go")
{
const Direction direction = GetDirectionFromName(tokens[1]);
if (direction != Direction::Unknown)
{
player->OnGo(direction);
return false;
}
else
{
std::cout << "That direction is not a valid one.\n";
return false;
}
}
else if (tokens[0] == "take")
{
const std::string name = JoinTokens(tokens, 1, tokens.size());
if (player->OnTake(name))
{
return true;
}
else
{
return false;
}
}
else if (tokens[0] == "drop")
{
const std::string name = JoinTokens(tokens, 1, tokens.size());
if (player->OnDrop(name))
{
return true;
}
else
{
return false;
}
}
else if (tokens[0] == "put")
{
int in_location = -1;
for (int i = 1; i < tokens.size(); i++)
{
if (tokens[i] == "in")
{
in_location = i;
}
}
if (in_location == -1)
{
std::cout << "You have to specify where to put the given item.\n";
return false;
}
const std::string name = JoinTokens(tokens, 1, in_location);
const std::string container_name = JoinTokens(tokens, in_location + 1, tokens.size());
if (player->OnPut(name, container_name))
{
return true;
}
else
{
return false;
}
}
else if (tokens[0] == "hit")
{
int with_location = -1;
for (int i = 1; i < tokens.size(); i++)
{
if (tokens[i] == "with")
{
with_location = i;
}
}
if (with_location == -1)
{
std::cout << "You have to specify what you want to use.\n";
return false;
}
const std::string target_name = JoinTokens(tokens, 1, with_location);
const std::string source_name = JoinTokens(tokens, with_location + 1, tokens.size());
if (player->OnHit(target_name, source_name))
{
return true;
}
else
{
return false;
}
}
else if (tokens[0] == "open")
{
const std::string name = JoinTokens(tokens, 1, tokens.size());
if (player->OnOpen(name))
{
return true;
}
else
{
return false;
}
}
}
std::cout << "I didn't understand what you wanted to do. Write 'help' to view the possible commands.\n";
return false;
}
|
//
// Copyright © 2018 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <memory>
#include <array>
#include <algorithm>
#include <cstring>
#include "armnn/ArmNN.hpp"
#include "armnn/Exceptions.hpp"
#include "armnn/Tensor.hpp"
#include "armnn/INetwork.hpp"
#include "armnnTfParser/ITfParser.hpp"
#include "mnist_loader.hpp"
#define MAX_IMAGES 3000
// Helper function to make input tensors
armnn::InputTensors MakeInputTensors(const std::pair<armnn::LayerBindingId,
armnn::TensorInfo>& input,
const void* inputTensorData)
{
return { { input.first, armnn::ConstTensor(input.second, inputTensorData) } };
}
// Helper function to make output tensors
armnn::OutputTensors MakeOutputTensors(const std::pair<armnn::LayerBindingId,
armnn::TensorInfo>& output,
void* outputTensorData)
{
return { { output.first, armnn::Tensor(output.second, outputTensorData) } };
}
int main(int argc, char** argv)
{
// Default input size is one image
unsigned int nrOfImages = 1;
// Optimisation mode 0 = CPU Reference (unoptimised)
// Optimisation mode 1 = CPU Accelerator
// Optimisation mode 2 = GPU Accelerator
unsigned int optimisationMode = 1;
// Check program arguments
if (argc != 3)
{
std::cout << "Invalid arguments. Exactly 2 arguments required." << std::endl;
std::cout << "Example: ./mnist_tf 1 10" << std::endl;
std::cout << "Optimisation modes: 0 for CpuRef, 1 for CpuAcc, 2 for GpuAcc" << std::endl;
std::cout << "Input size: 1 to 2000 (number of images to predict)" << std::endl;
return 1;
}
// Parse input size option
nrOfImages = std::stoi(argv[2]);
if (!(nrOfImages > 0 && nrOfImages <= MAX_IMAGES))
{
std::cout << "Error: Maximum number of images is " << MAX_IMAGES << std::endl;
return 1;
}
// Parse optimisation mode option
optimisationMode = std::stoi(argv[1]);
if (!(optimisationMode == 0 || optimisationMode == 1 || optimisationMode == 2))
{
std::cout << "Invalid optimisation mode." << std::endl;
return 1;
}
// Import the TensorFlow model. Note: use CreateNetworkFromBinaryFile for .pb files.
armnnTfParser::ITfParserPtr parser = armnnTfParser::ITfParser::Create();
armnn::INetworkPtr network = parser->CreateNetworkFromBinaryFile("model/convol_mnist_tf.pb",
{ {"input_tensor", {nrOfImages, 784, 1, 1}} },
{ "fc2/output_tensor" });
// Find the binding points for the input and output nodes
armnnTfParser::BindingPointInfo inputBindingInfo = parser->GetNetworkInputBindingInfo("input_tensor");
armnnTfParser::BindingPointInfo outputBindingInfo = parser->GetNetworkOutputBindingInfo("fc2/output_tensor");
// Create ArmNN runtime
armnn::IRuntime::CreationOptions options; // default options
options.m_ProfilingOptions.m_EnableProfiling = true;
options.m_ProfilingOptions.m_TimelineEnabled = true;
armnn::IRuntimePtr runtime = armnn::IRuntime::Create(options);
// Optimize the network for a specific runtime compute device, e.g. CpuAcc, GpuAcc
std::cout << "Optimisation mode: ";
armnn::Compute device;
switch(optimisationMode)
{
case 0: device = armnn::Compute::CpuRef; std::cout << "CpuRef" << std::endl; break;
case 1: device = armnn::Compute::CpuAcc; std::cout << "CpuAcc" << std::endl; break;
case 2: device = armnn::Compute::GpuAcc; std::cout << "GpuAcc" << std::endl; break;
}
armnn::IOptimizedNetworkPtr optNet = Optimize(*network, {device}, runtime->GetDeviceSpec());
// Load the optimized network onto the runtime device
armnn::NetworkId networkIdentifier;
runtime->LoadNetwork(networkIdentifier, std::move(optNet));
// Load multiple images from the data directory
std::string dataDir = "data/";
auto input = new float[nrOfImages][g_kMnistImageByteSize];
auto output = new float[nrOfImages][10];
auto labels = new int[nrOfImages];
for (int i = 0; i < nrOfImages; ++i)
{
std::unique_ptr<MnistImage> imgInfo = loadMnistImage(dataDir, i);
if (imgInfo == nullptr)
return 1;
std::memcpy(input[i], imgInfo->image, sizeof(imgInfo->image));
labels[i] = imgInfo->label;
}
// Execute network
armnn::InputTensors inputTensor = MakeInputTensors(inputBindingInfo, &input[0]);
armnn::OutputTensors outputTensor = MakeOutputTensors(outputBindingInfo, &output[0]);
armnn::Status ret = runtime->EnqueueWorkload(networkIdentifier, inputTensor, outputTensor);
// Check output and compute correct predictions
int nrOfCorrectPredictions = 0;
for (int i = 0; i < nrOfImages; ++i)
{
float max = output[i][0];
int label = 0;
for (int j = 0; j < 10; ++j)
{
// Translate 1-hot output to find integer label
if (output[i][j] > max)
{
max = output[i][j];
label = j;
}
}
if (label == labels[i]) nrOfCorrectPredictions++;
std::cout << "#" << i+1 << " | Predicted: " << label << " Actual: " << labels[i] << std::endl;
}
std::cout << "Prediction accuracy: " << (float)nrOfCorrectPredictions/nrOfImages*100 << "%";
std::cout << std::endl;
delete[] input;
delete[] output;
delete[] labels;
return 0;
}
|
#include "parser.h"
#include <wizard_parser/parser/Parser.h>
#include <wizard_parser/node/Node.h>
#include <algorithm>
#include <numeric>
using namespace thewizardplusplus::wizard_parser::parser;
using namespace thewizardplusplus::wizard_parser::node;
namespace {
Parser CreateGrammar(void) {
const auto expression = dummy();
const auto statement_list_copy = dummy();
WP_RULE(keywords)
word(
"NULL"_t
| "and"_t
| "break"_t
| "continue"_t
| "do"_t
| "else"_t
| "end"_t
| "function"_t
| "if"_t
| "let"_t
| "new"_t
| "not"_t
| "or"_t
| "return"_t
| "structure"_t
| "then"_t
| "while"_t
)
WP_END
WP_RULE(null_definition) hide("NULL"_t) WP_END
WP_RULE(number)
disable_separation(
lexeme(
'\''_s >> (('\\'_s >> any()) | (any() - '\''_s)) >> '\''_s
)
)
| disable_separation(lexeme(+digit() >> !('.'_s >> +digit())))
WP_END
WP_RULE(identifier)
disable_separation(lexeme((letter() | '_'_s) >> *word()) - keywords)
WP_END
WP_RULE(string_definition)
lexeme(
disable_separation(
hide('"'_s)
>> *(('\\'_s >> any()) | (any() - '"'_s))
>> hide('"'_s)
)
)
WP_END
WP_RULE(array_listed_definition)
hide('['_s) >> !list(expression, hide(','_s)) >> hide(']'_s)
WP_END
WP_RULE(function_call)
identifier
>> hide('('_s) >> !list(expression, hide(','_s)) >> hide(')'_s)
WP_END
WP_RULE(atom)
null_definition
| number
| identifier
| array_listed_definition
| string_definition
| function_call
| hide('('_s) >> expression >> hide(')'_s)
WP_END
WP_RULE(array_sized_definition)
hide(word("new"_t)) >> hide(word("array"_t)) >> hide('('_s)
>> expression
>> hide(')'_s)
WP_END
WP_RULE(item_access) hide('['_s) >> expression >> hide(']'_s) WP_END
WP_RULE(field_access) hide('.'_s) >> identifier WP_END
WP_RULE(accessor) atom >> *(item_access | field_access) WP_END
WP_RULE(unary)
(word("new"_t) >> identifier)
| array_sized_definition
| (*('-'_s | word("not"_t)) >> accessor)
WP_END
WP_RULE(product) list(unary, '*'_s | '/'_s | '%'_s) WP_END
WP_RULE(sum) list(product, '+'_s | '-'_s) WP_END
WP_RULE(comparison) list(sum, '<'_s | "<="_t | '>'_s | ">="_t) WP_END
WP_RULE(equality) list(comparison, "=="_t | "/="_t) WP_END
WP_RULE(conjunction) list(equality, hide(word("and"_t))) WP_END
WP_RULE(disjunction) list(conjunction, hide(word("or"_t))) WP_END
assign(expression, disjunction);
WP_RULE(variable_definition)
hide(*space())
>> hide(word("let"_t)) >> identifier >> hide('='_s) >> expression
WP_END
WP_RULE(assignment) expression >> hide('='_s) >> expression WP_END
WP_RULE(condition)
hide(*space())
>> hide(word("if"_t)) >> expression >> hide(word("then"_t))
>> statement_list_copy
>> *(hide(word("else"_t))
>> hide(word("if"_t))
>> expression
>> hide(word("then"_t))
>> statement_list_copy)
>> !(hide(word("else"_t))
>> statement_list_copy)
>> hide(word("end"_t))
>> hide(*space())
WP_END
WP_RULE(loop)
hide(*space())
>> hide(word("while"_t)) >> expression >> hide(word("do"_t))
>> statement_list_copy
>> hide(word("end"_t))
>> hide(*space())
WP_END
WP_RULE(loop_continue)
hide(*space())
>> hide(word("continue"_t))
>> hide(*space())
WP_END
WP_RULE(loop_break)
hide(*space())
>> hide(word("break"_t))
>> hide(*space())
WP_END
WP_RULE(function_return)
hide(*space())
>> hide(word("return"_t)) >> (!expression | hide(*space()))
WP_END
WP_RULE(statement)
variable_definition
| assignment
| condition
| loop
| loop_continue
| loop_break
| function_return
| expression
WP_END
WP_RULE(statement_list) +statement WP_END
assign(statement_list_copy, statement_list);
WP_RULE(structure_field_declaration)
hide(*space()) >> identifier >> hide(*space())
WP_END
WP_RULE(structure_declaration)
hide(*space())
>> hide(word("structure"_t))
>> +structure_field_declaration
>> hide(word("end"_t))
>> hide(*space())
WP_END
WP_RULE(function_declaration)
hide(*space())
>> hide(word("function"_t))
>> identifier
>> hide('('_s)
>> !list(identifier, hide(','_s))
>> hide(')'_s)
>> statement_list_copy
>> hide(word("end"_t))
>> hide(*space())
WP_END
WP_RULE(program)
+(variable_definition | structure_declaration | function_declaration)
WP_END
return separation(hide(*space()), program >> end());
}
Node SimplifyAst(const Node& node) {
auto children = NodeGroup();
std::transform(
node.children.begin(),
node.children.end(),
std::back_inserter(children),
[=] (const Node& node) {
return SimplifyAst(node);
}
);
auto simplified_node = Node{node.name, node.value, children};
if (node.name == "disjunction" || node.name == "conjunction") {
const auto second_child = children.back();
if (
second_child.name.empty()
&& second_child.value.empty()
&& second_child.children.size() > 1
) {
simplified_node = std::accumulate(
second_child.children.begin(),
second_child.children.end(),
children.front(),
[=] (const Node& simplified_node, const Node& child) {
return Node{node.name, "", {simplified_node, child}};
}
);
}
} else if (
node.name == "equality"
|| node.name == "comparison"
|| node.name == "sum"
|| node.name == "product"
) {
const auto second_child = children.back();
const auto first_subchild = second_child.children.front();
if (!first_subchild.value.empty()) {
simplified_node = Node{
node.name,
first_subchild.value,
{children.front(), second_child.children.back()}
};
} else {
simplified_node = std::accumulate(
second_child.children.begin(),
second_child.children.end(),
children.front(),
[=] (const Node& simplified_node, const Node& child) {
return Node{
node.name,
child.children.front().value,
{simplified_node, child.children.back()}
};
}
);
}
} else if (node.name == "accessor") {
const auto second_child = children.back();
if (second_child.name.empty()) {
simplified_node = std::accumulate(
second_child.children.begin(),
second_child.children.end(),
children.front(),
[=] (const Node& simplified_node, const Node& child) {
return Node{node.name, "", {simplified_node, child}};
}
);
}
} else if (node.name == "unary") {
const auto first_child = children.front();
if (first_child.value != "new" && first_child.children.size() == 0) {
simplified_node = Node{
node.name,
"",
{{"", "", {first_child}}, children.back()}
};
}
} else if (node.name == "array_listed_definition") {
if (children.size() == 2) {
const auto second_child = children.back();
if (
second_child.name.empty()
&& second_child.value.empty()
&& second_child.children.size() > 1
) {
auto new_children = NodeGroup();
new_children.push_back(children.front());
std::copy(
second_child.children.begin(),
second_child.children.end(),
std::back_inserter(new_children)
);
simplified_node = Node{node.name, "", new_children};
}
}
} else if (node.name == "function_call") {
const auto first_child = children.front();
if (children.size() == 1) {
simplified_node = Node{node.name, first_child.value, {}};
} else if (children.size() == 2) {
const auto second_child = children.back();
if (
!second_child.name.empty()
|| !second_child.value.empty()
|| second_child.children.size() < 2
) {
simplified_node = Node{
node.name,
first_child.value,
{second_child}
};
} else {
const auto first_subchild = second_child.children.front();
const auto second_subchild = second_child.children.back();
if (
!second_subchild.name.empty()
|| !second_subchild.value.empty()
|| second_subchild.children.size() < 2
) {
simplified_node = Node{
node.name,
first_child.value,
{first_subchild, second_subchild}
};
} else {
auto new_children = NodeGroup();
new_children.push_back(first_subchild);
std::copy(
second_subchild.children.begin(),
second_subchild.children.end(),
std::back_inserter(new_children)
);
simplified_node = Node{
node.name,
first_child.value,
new_children
};
}
}
}
} else if (node.name == "variable_definition") {
simplified_node = Node{
node.name,
children.front().value,
{children.back()}
};
} else if (node.name == "condition") {
auto new_children = NodeGroup();
const auto first_child = children.front();
if (!first_child.name.empty()) {
new_children.push_back({"", "", children});
} else {
const auto second_child = children.back();
if (second_child.name.empty()) {
new_children.push_back(first_child);
auto subchild = second_child.children.begin();
if (!subchild->name.empty()) {
new_children.push_back(second_child);
} else {
while (subchild != second_child.children.end()) {
new_children.push_back(*subchild);
subchild++;
};
}
} else {
const auto first_subchild = first_child.children.front();
if (!first_subchild.name.empty()) {
new_children.push_back(first_child);
} else {
new_children.push_back(first_subchild);
const auto second_subchild = first_child.children.back();
auto subsubchild = second_subchild.children.begin();
if (!subsubchild->name.empty()) {
new_children.push_back(second_subchild);
} else {
while (subsubchild != second_subchild.children.end()) {
new_children.push_back(*subsubchild);
subsubchild++;
};
}
}
new_children.push_back(second_child);
}
}
simplified_node = Node{node.name, "", new_children};
} else if (node.name == "statement_list") {
const auto second_child = children.back();
if (
second_child.name.empty()
&& second_child.value.empty()
&& second_child.children.size() > 1
) {
auto new_children = NodeGroup();
new_children.push_back(children.front());
std::copy(
second_child.children.begin(),
second_child.children.end(),
std::back_inserter(new_children)
);
simplified_node = Node{node.name, "", new_children};
}
} else if (node.name == "program") {
const auto second_child = children.back();
if (
second_child.name.empty()
&& second_child.value.empty()
&& second_child.children.size() > 1
) {
auto new_children = NodeGroup();
new_children.push_back(children.front());
std::copy(
second_child.children.begin(),
second_child.children.end(),
std::back_inserter(new_children)
);
simplified_node = Node{node.name, "", new_children};
}
} else if (node.name == "structure_declaration") {
const auto second_child = children.back();
if (
!second_child.name.empty()
|| !second_child.value.empty()
|| second_child.children.size() < 2
) {
simplified_node = Node{
node.name,
children.front().value,
{second_child}
};
} else {
const auto second_subchild = second_child.children.back();
if (
!second_subchild.name.empty()
|| !second_subchild.value.empty()
|| second_subchild.children.size() < 2
) {
simplified_node = Node{
node.name,
children.front().value,
second_child.children
};
} else {
auto new_children = NodeGroup();
new_children.push_back(second_child.children.front());
std::copy(
second_subchild.children.begin(),
second_subchild.children.end(),
std::back_inserter(new_children)
);
simplified_node = Node{
node.name,
children.front().value,
new_children
};
}
}
} else if (node.name == "function_declaration") {
const auto first_child = children.front();
const auto second_child = children.back();
if (
!first_child.name.empty()
|| !first_child.value.empty()
|| first_child.children.size() < 2
) {
simplified_node = Node{
node.name,
first_child.value,
{Node(), second_child}
};
} else {
const auto first_subchild = first_child.children.front();
const auto second_subchild = first_child.children.back();
if (
!second_subchild.name.empty()
|| !second_subchild.value.empty()
|| second_subchild.children.size() < 2
) {
simplified_node = Node{
node.name,
first_subchild.value,
{{"", "", {second_subchild}}, second_child}
};
} else {
const auto second_subsubchild = second_subchild.children.back();
if (
!second_subsubchild.name.empty()
|| !second_subsubchild.value.empty()
|| second_subsubchild.children.size() < 2
) {
simplified_node = Node{
node.name,
first_subchild.value,
{{"", "", second_subchild.children}, second_child}
};
} else {
auto new_children = NodeGroup();
new_children.push_back(second_subchild.children.front());
std::copy(
second_subsubchild.children.begin(),
second_subsubchild.children.end(),
std::back_inserter(new_children)
);
simplified_node = Node{
node.name,
first_subchild.value,
{{"", "", new_children}, second_child}
};
}
}
}
}
return simplified_node;
}
}
namespace thewizardplusplus {
namespace wizard_basic_3 {
namespace parser {
auto Parse(const std::string& code) -> wizard_parser::node::Node {
const auto grammar = CreateGrammar();
const auto ast = parse(
grammar,
code,
SimplifyLevel::AST,
{
"array_listed_definition",
"function_call",
"array_sized_definition",
"item_access",
"field_access",
"function_return",
"statement_list",
"program"
}
);
return SimplifyAst(ast);
}
}
}
}
|
#include "responsedirectory.h"
#include "mime.h"
#include <QDir>
#include <QFileInfoList>
#include <QTextStream>
#include <QByteArray>
#include <QBuffer>
ResponseDirectory::ResponseDirectory(QTcpSocket * socket, QMap<QString, QString> & header, QString dir_name, QString url_path):
Response(socket, 200, header),
m_dir_name(dir_name),
m_url_path(url_path)
{
}
void ResponseDirectory::response()
{
QDir dir(m_dir_name);
if (!dir.isReadable())
return; //TODO error
QByteArray buffer;
QBuffer qbuffer(&buffer);
qbuffer.open(QIODevice::WriteOnly);
QTextStream sbuffer(&qbuffer);
sbuffer << "<html><head><title>"
<< m_url_path
<< "</title></head><body><h1>"
<< m_url_path
<< "</h1><hr/><table><tr>"
"<td>Filename</td>"
"<td>Size</td>"
"</tr>";
dir.setFilter(QDir::Dirs|QDir::Files);
dir.setSorting(QDir::DirsFirst|QDir::Name);
QFileInfoList file_list = dir.entryInfoList();
for (QFileInfoList::Iterator i = file_list.begin(); i != file_list.end(); ++i)
{
if (i->isDir())
{
sbuffer << QString("<tr><td><a href='%1/'>%2/</a></td><td>-</td></tr>")
.arg(m_url_path + i->fileName())
.arg(i->fileName());
}
else
{
sbuffer << QString("<tr><td><a href='%1'>%2</a></td><td>%3</td></tr>")
.arg(m_url_path + i->fileName())
.arg(i->fileName())
.arg(i->size());
}
}
sbuffer << "</table><hr/>"
<< APPLICATION_IDENTIFIER
<< "</body></html>";
sbuffer.flush();
m_header["Content-Type"] = Mime::instance().getMimeType("htm");
m_header["Content-Length"] = QString("%1").arg(buffer.length());
responseHeader();
m_socket->write(buffer);
}
|
/*
* libjingle
* Copyright 2005 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/session/media/channelmanager.h"
#include "talk/session/media/mediamonitor.h"
#include "webrtc/base/common.h"
namespace cricket {
enum {
MSG_MONITOR_POLL = 1,
MSG_MONITOR_START = 2,
MSG_MONITOR_STOP = 3,
MSG_MONITOR_SIGNAL = 4
};
MediaMonitor::MediaMonitor(rtc::Thread* worker_thread,
rtc::Thread* monitor_thread)
: worker_thread_(worker_thread),
monitor_thread_(monitor_thread), monitoring_(false), rate_(0) {
}
MediaMonitor::~MediaMonitor() {
monitoring_ = false;
monitor_thread_->Clear(this);
worker_thread_->Clear(this);
}
void MediaMonitor::Start(uint32_t milliseconds) {
rate_ = milliseconds;
if (rate_ < 100)
rate_ = 100;
worker_thread_->Post(this, MSG_MONITOR_START);
}
void MediaMonitor::Stop() {
worker_thread_->Post(this, MSG_MONITOR_STOP);
rate_ = 0;
}
void MediaMonitor::OnMessage(rtc::Message* message) {
rtc::CritScope cs(&crit_);
switch (message->message_id) {
case MSG_MONITOR_START:
ASSERT(rtc::Thread::Current() == worker_thread_);
if (!monitoring_) {
monitoring_ = true;
PollMediaChannel();
}
break;
case MSG_MONITOR_STOP:
ASSERT(rtc::Thread::Current() == worker_thread_);
if (monitoring_) {
monitoring_ = false;
worker_thread_->Clear(this);
}
break;
case MSG_MONITOR_POLL:
ASSERT(rtc::Thread::Current() == worker_thread_);
PollMediaChannel();
break;
case MSG_MONITOR_SIGNAL:
ASSERT(rtc::Thread::Current() == monitor_thread_);
Update();
break;
}
}
void MediaMonitor::PollMediaChannel() {
rtc::CritScope cs(&crit_);
ASSERT(rtc::Thread::Current() == worker_thread_);
GetStats();
// Signal the monitoring thread, start another poll timer
monitor_thread_->Post(this, MSG_MONITOR_SIGNAL);
worker_thread_->PostDelayed(rate_, this, MSG_MONITOR_POLL);
}
}
|
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_GENERATOR_GENERATE_FUNCTIONS_HPP
#define SPROUT_GENERATOR_GENERATE_FUNCTIONS_HPP
#include <sprout/config.hpp>
#include <sprout/generator/next_value.hpp>
#endif // #ifndef SPROUT_GENERATOR_GENERATE_FUNCTIONS_HPP
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "CryLegacy_precompiled.h"
#include "FlowSystem.h"
#include <CryAction.h>
#include "FlowGraph.h"
#include "FlowInitManager.h"
#include <FlowSystem/Nodes/FlowBaseNode.h>
#include "Nodes/FlowLogNode.h"
#include "Nodes/FlowStartNode.h"
#include "Nodes/FlowTrackEventNode.h"
#include "Nodes/FlowDelayNode.h"
#include "Nodes/FlowScriptedNode.h"
#include "Nodes/FlowCompositeNode.h"
#include "Nodes/FlowTimeNode.h"
#include "Nodes/FlowEntityNode.h"
#include "Inspectors/FlowInspectorDefault.h"
#include "Modules/ModuleManager.h"
#include "PersistentDebug.h"
#include "AnimationGraph/DebugHistory.h"
#include "ITimer.h"
#include "TimeOfDayScheduler.h"
#include "VisualLog/VisualLog.h"
#include "CryPath.h"
#include <MathConversion.h>
#define BLACKLIST_FILE_PATH "Libs/FlowNodes/FlownodeBlacklist.xml"
#define GRAPH_RESERVED_CAPACITY 8
#ifndef _RELEASE
#define SHOW_FG_CRITICAL_LOADING_ERROR_ON_SCREEN
#endif
#ifndef _RELEASE
CFlowSystem::TSFGProfile CFlowSystem::FGProfile;
#endif //_RELEASE
//////////////////////////////////////////////////////////////////////////
string GetEntityFlowNodeName(const IEntityClass& entityClass)
{
string entityPrefixStr = "entity:";
return string(entityPrefixStr + entityClass.GetName());
}
template <class T>
class CAutoFlowFactory
: public IFlowNodeFactory
{
public:
CAutoFlowFactory()
: m_refs(0) {}
void AddRef() { m_refs++; }
void Release()
{
if (0 == --m_refs)
{
delete this;
}
}
IFlowNodePtr Create(IFlowNode::SActivationInfo* pActInfo) { return new T(pActInfo); }
void GetMemoryUsage(ICrySizer* s) const
{
SIZER_SUBCOMPONENT_NAME(s, "CAutoFlowFactory");
s->Add(*this);
}
void Reset() {}
private:
int m_refs;
};
template <class T>
class CSingletonFlowFactory
: public IFlowNodeFactory
{
public:
CSingletonFlowFactory()
: m_refs(0) {m_pInstance = new T(); }
void AddRef() { m_refs++; }
void Release()
{
if (0 == --m_refs)
{
delete this;
}
}
void GetMemoryUsage(ICrySizer* s) const
{
SIZER_SUBCOMPONENT_NAME(s, "CSingletonFlowFactory");
s->Add(*this);
s->AddObject(m_pInstance);
}
IFlowNodePtr Create(IFlowNode::SActivationInfo* pActInfo)
{
return m_pInstance;
}
void Reset() {}
private:
IFlowNodePtr m_pInstance;
int m_refs;
};
FlowEntityType GetFlowEntityTypeFromFlowEntityId(FlowEntityId id)
{
if (id == FlowEntityId::s_invalidFlowEntityID)
{
return FlowEntityType::Invalid;
}
else
{
return IsLegacyEntityId(id) ? FlowEntityType::Legacy : FlowEntityType::Component;
}
}
// FlowSystem Container
void CFlowSystemContainer::AddItem(TFlowInputData item)
{
m_container.push_back(item);
}
void CFlowSystemContainer::AddItemUnique(TFlowInputData item)
{
if (std::find(m_container.begin(), m_container.end(), item) == m_container.end())
{
m_container.push_back(item);
}
}
void CFlowSystemContainer::RemoveItem(TFlowInputData item)
{
m_container.erase(std::remove(m_container.begin(), m_container.end(), item), m_container.end());
}
TFlowInputData CFlowSystemContainer::GetItem(int i)
{
return m_container[i];
}
void CFlowSystemContainer::RemoveItemAt(int i)
{
m_container.erase(m_container.begin() + i);
}
void CFlowSystemContainer::Clear()
{
m_container.clear();
}
int CFlowSystemContainer::GetItemCount() const
{
return m_container.size();
}
void CFlowSystemContainer::GetMemoryUsage(ICrySizer* s) const
{
if (GetItemCount() > 0)
{
s->Add(&m_container[0], m_container.capacity());
}
s->Add(m_container);
}
void CFlowSystemContainer::Serialize(TSerialize ser)
{
int count = m_container.size();
ser.Value("count", count);
if (ser.IsWriting())
{
for (int i = 0; i < count; i++)
{
ser.BeginGroup("ContainerInfo");
m_container[i].Serialize(ser);
ser.EndGroup();
}
}
else
{
for (int i = 0; i < count; i++)
{
ser.BeginGroup("ContainerInfo");
TFlowInputData data;
data.Serialize(ser);
m_container.push_back(data);
ser.EndGroup();
}
}
}
CFlowSystem::CFlowSystem()
: m_bInspectingEnabled(false)
, m_needToUpdateForwardings(false)
, m_criticalLoadingErrorHappened(false)
, m_graphs(GRAPH_RESERVED_CAPACITY)
, m_nextFlowGraphId(0)
, m_pModuleManager(NULL)
, m_blacklistNode(NULL)
, m_nextNodeTypeID(InvalidFlowNodeTypeId)
{
LoadBlacklistedFlownodeXML();
gEnv->pEntitySystem->GetClassRegistry()->RegisterListener(this);
gEnv->pSystem->GetISystemEventDispatcher()->RegisterListener(this);
}
void CFlowSystem::PreInit()
{
m_flowInitManager.reset(new FlowInitManager);
m_pModuleManager = new CFlowGraphModuleManager();
RegisterAllNodeTypes();
m_pDefaultInspector = new CFlowInspectorDefault(this);
RegisterInspector(m_pDefaultInspector, 0);
EnableInspecting(false);
}
CFlowSystem::~CFlowSystem()
{
gEnv->pEntitySystem->GetClassRegistry()->UnregisterListener(this);
gEnv->pSystem->GetISystemEventDispatcher()->RemoveListener(this);
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
itGraph->NotifyFlowSystemDestroyed();
}
SAFE_DELETE(m_pModuleManager);
}
void CFlowSystem::Release()
{
UnregisterInspector(m_pDefaultInspector, 0);
if (m_pModuleManager)
{
m_pModuleManager->Shutdown();
}
delete this;
}
IFlowGraphPtr CFlowSystem::CreateFlowGraph()
{
return new CFlowGraph(this);
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::ReloadAllNodeTypes()
{
if (gEnv->IsEditor())
{
RegisterAllNodeTypes();
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::RegisterAllNodeTypes()
{
// Load UI initialization data from json
m_flowInitManager->LoadInitData();
// clear node types
m_typeNameToIdMap.clear();
m_typeRegistryVec.clear();
// reset TypeIDs
m_freeNodeTypeIDs.clear();
m_nextNodeTypeID = InvalidFlowNodeTypeId;
// register all types
TFlowNodeTypeId typeId = RegisterType("InvalidType", 0);
assert (typeId == InvalidFlowNodeTypeId);
RegisterType("Debug:Log", new CSingletonFlowFactory<CFlowLogNode>());
RegisterType("Game:Start", new CAutoFlowFactory<CFlowStartNode>());
RegisterType("TrackEvent", new CAutoFlowFactory<CFlowTrackEventNode>());
RegisterAutoTypes();
LoadExtensions("Libs/FlowNodes");
// register game specific flownodes
gEnv->pGame->RegisterGameFlowNodes();
// register entity type flownodes after the game
RegisterEntityTypes();
#ifndef AZ_MONOLITHIC_BUILD
// Last chance for engine modules and gems to register nodes before flow modules get loaded
GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_FLOW_SYSTEM_REGISTER_EXTERNAL_NODES, 0, 0);
#endif // AZ_MONOLITHIC_BUILD
// this has to come after all other nodes are reloaded
// as it will trigger the editor to reload the fg classes!
GetModuleManager()->ScanForModules(); // reload all modules (since they need to register the start and end node types)
}
void CFlowSystem::LoadExtensions(string path)
{
ICryPak* pCryPak = gEnv->pCryPak;
_finddata_t fd;
char filename[_MAX_PATH];
path.TrimRight("/\\");
string search = path + "/*.node";
intptr_t handle = pCryPak->FindFirst(search.c_str(), &fd);
if (handle != -1)
{
int res = 0;
TPendingComposites pendingComposites;
do
{
cry_strcpy(filename, path.c_str());
cry_strcat(filename, "/");
cry_strcat(filename, fd.name);
XmlNodeRef root = GetISystem()->LoadXmlFromFile(filename);
if (root)
{
LoadExtensionFromXml(root, &pendingComposites);
}
res = pCryPak->FindNext(handle, &fd);
}
while (res >= 0);
LoadComposites(&pendingComposites);
pCryPak->FindClose(handle);
}
}
void CFlowSystem::LoadExtensionFromXml(XmlNodeRef nodeParent, TPendingComposites* pComposites)
{
XmlNodeRef node;
int nChildren = nodeParent->getChildCount();
int iChild;
// run for nodeParent, and any children it contains
for (iChild = -1, node = nodeParent;; )
{
const char* tag = node->getTag();
if (!tag || !*tag)
{
return;
}
// Multiple components may be contained within a <NodeList> </NodeList> pair
if ((0 == strcmp("NodeList", tag)) || (0 == strcmp("/NodeList", tag)))
{
// a list node, do nothing.
// if root level, will advance to child below
}
else
{
const char* name = node->getAttr("name");
if (!name || !*name)
{
return;
}
if (0 == strcmp("Script", tag))
{
const char* path = node->getAttr("script");
if (!path || !*path)
{
return;
}
CFlowScriptedNodeFactoryPtr pFactory = new CFlowScriptedNodeFactory();
if (pFactory->Init(path, name))
{
RegisterType(name, &*pFactory);
}
}
else if (0 == strcmp("SimpleScript", tag))
{
const char* path = node->getAttr("script");
if (!path || !*path)
{
return;
}
CFlowSimpleScriptedNodeFactoryPtr pFactory = new CFlowSimpleScriptedNodeFactory();
if (pFactory->Init(path, name))
{
RegisterType(name, &*pFactory);
}
}
else if (0 == strcmp("Composite", tag))
{
pComposites->push(node);
}
}
if (++iChild >= nChildren)
{
break;
}
node = nodeParent->getChild(iChild);
}
}
void CFlowSystem::LoadComposites(TPendingComposites* pComposites)
{
size_t failCount = 0;
while (!pComposites->empty() && failCount < pComposites->size())
{
CFlowCompositeNodeFactoryPtr pFactory = new CFlowCompositeNodeFactory();
switch (pFactory->Init(pComposites->front(), this))
{
case CFlowCompositeNodeFactory::eIR_Failed:
GameWarning("Failed to load composite due to invalid data: %s", pComposites->front()->getAttr("name"));
pComposites->pop();
failCount = 0;
break;
case CFlowCompositeNodeFactory::eIR_Ok:
RegisterType(pComposites->front()->getAttr("name"), &*pFactory);
pComposites->pop();
failCount = 0;
break;
case CFlowCompositeNodeFactory::eIR_NotYet:
pComposites->push(pComposites->front());
pComposites->pop();
failCount++;
break;
}
}
while (!pComposites->empty())
{
GameWarning("Failed to load composite due to failed dependency: %s", pComposites->front()->getAttr("name"));
pComposites->pop();
}
}
void CFlowSystem::OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam)
{
switch (event)
{
case ESYSTEM_EVENT_GAME_MODE_SWITCH_START:
{
// If went to editor mode then uninitialize
bool inGame = (wparam != 0U);
if (!inGame)
{
Uninitialize();
}
break;
}
case ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED:
{
// If AI/Physics turned off then uninitialize
bool simulationEnabled = static_cast<uint32>(wparam) == 0;
if (simulationEnabled)
{
Uninitialize();
}
break;
}
}
}
class CFlowSystem::CNodeTypeIterator
: public IFlowNodeTypeIterator
{
public:
CNodeTypeIterator(CFlowSystem* pImpl)
: m_nRefs(0)
, m_pImpl(pImpl)
, m_iter(pImpl->m_typeRegistryVec.begin())
{
assert (m_iter != m_pImpl->m_typeRegistryVec.end());
++m_iter;
m_id = InvalidFlowNodeTypeId;
assert (m_id == 0);
}
void AddRef()
{
++m_nRefs;
}
void Release()
{
if (0 == --m_nRefs)
{
delete this;
}
}
bool Next(SNodeType& nodeType)
{
while (m_iter != m_pImpl->m_typeRegistryVec.end() && !_stricmp(m_iter->name, ""))
{
++m_id;
++m_iter;
}
if (m_iter == m_pImpl->m_typeRegistryVec.end())
{
return false;
}
nodeType.typeId = ++m_id;
nodeType.typeName = m_iter->name;
++m_iter;
return true;
}
private:
int m_nRefs;
TFlowNodeTypeId m_id;
CFlowSystem* m_pImpl;
std::vector<STypeInfo>::iterator m_iter;
};
IFlowNodeTypeIteratorPtr CFlowSystem::CreateNodeTypeIterator()
{
return new CNodeTypeIterator(this);
}
TFlowNodeTypeId CFlowSystem::GenerateNodeTypeID()
{
if (!m_freeNodeTypeIDs.empty())
{
TFlowNodeTypeId typeID = m_freeNodeTypeIDs.back();
m_freeNodeTypeIDs.pop_back();
return typeID;
}
if (m_nextNodeTypeID > CFlowData::TYPE_MAX_COUNT)
{
CryWarning(VALIDATOR_MODULE_FLOWGRAPH, VALIDATOR_ERROR, "CFlowSystem::GenerateNodeTypeID: Reached maximum amount of NodeTypes: Limit=%d", CFlowData::TYPE_MAX_COUNT);
return InvalidFlowNodeTypeId;
}
return m_nextNodeTypeID++;
}
void CFlowSystem::RegisterNodeInfo(const char* type, IFlowNodeFactoryPtr factory)
{
m_flowInitManager->RegisterNodeInfo(type);
}
TFlowNodeTypeId CFlowSystem::RegisterType(const char* type, IFlowNodeFactoryPtr factory)
{
if (!BlacklistedFlownode(&type))
{
return InvalidFlowNodeTypeId;
}
string typeName = type;
const TTypeNameToIdMap::const_iterator iter = m_typeNameToIdMap.find(typeName);
if (iter == m_typeNameToIdMap.end())
{
const TFlowNodeTypeId nTypeId = GenerateNodeTypeID();
if ((nTypeId == InvalidFlowNodeTypeId) && typeName.compareNoCase("InvalidType"))
{
return nTypeId;
}
m_typeNameToIdMap[typeName] = nTypeId;
STypeInfo typeInfo(typeName, factory);
if (nTypeId >= m_typeRegistryVec.size())
{
m_typeRegistryVec.push_back(typeInfo);
}
else
{
m_typeRegistryVec[nTypeId] = typeInfo;
}
RegisterNodeInfo(typeName, factory);
return nTypeId;
}
else
{
// overriding
TFlowNodeTypeId nTypeId = iter->second;
if (!factory->AllowOverride())
{
CryFatalError("CFlowSystem::RegisterType: Type '%s' Id=%u already registered. Overriding not allowed by node factory.", type, nTypeId);
}
assert (nTypeId < m_typeRegistryVec.size());
STypeInfo& typeInfo = m_typeRegistryVec[nTypeId];
typeInfo.factory = factory;
return nTypeId;
}
}
bool CFlowSystem::UnregisterType(const char* typeName)
{
const TTypeNameToIdMap::iterator iter = m_typeNameToIdMap.find(typeName);
if (iter != m_typeNameToIdMap.end())
{
const TFlowNodeTypeId typeID = iter->second;
m_freeNodeTypeIDs.push_back(typeID);
m_typeRegistryVec[typeID] = STypeInfo();
m_typeNameToIdMap.erase(iter);
return true;
}
return false;
}
IFlowNodePtr CFlowSystem::CreateNodeOfType(IFlowNode::SActivationInfo* pActInfo, TFlowNodeTypeId typeId)
{
assert (typeId < m_typeRegistryVec.size());
if (typeId >= m_typeRegistryVec.size())
{
return 0;
}
const STypeInfo& type = m_typeRegistryVec[typeId];
IFlowNodeFactory* pFactory = type.factory;
if (pFactory)
{
return pFactory->Create(pActInfo);
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::Update()
{
#ifdef SHOW_FG_CRITICAL_LOADING_ERROR_ON_SCREEN
if (m_criticalLoadingErrorHappened && !gEnv->IsEditor())
{
gEnv->pRenderer->Draw2dLabel(10, 30, 2, Col_Red, false, "CRITICAL ERROR. SOME FLOWGRAPHS HAVE BEEN DISCARDED");
gEnv->pRenderer->Draw2dLabel(10, 50, 2, Col_Red, false, "LEVEL LOGIC COULD BE DAMAGED. check log for more info.");
}
#endif
{
FRAME_PROFILER("CFlowSystem::ForeignSystemUpdate", gEnv->pSystem, PROFILE_ACTION);
// These things need to be updated in game mode and ai/physics mode
CCryAction::GetCryAction()->GetPersistentDebug()->Update(gEnv->pTimer->GetFrameTime());
CDebugHistoryManager::RenderAll();
CCryAction::GetCryAction()->GetTimeOfDayScheduler()->Update();
CCryAction::GetCryAction()->GetVisualLog()->Update();
}
{
FRAME_PROFILER("CFlowSystem::Update()", gEnv->pSystem, PROFILE_ACTION);
if (m_cVars.m_enableUpdates == 0)
{
/*
IRenderer * pRend = gEnv->pRenderer;
float white[4] = {1,1,1,1};
pRend->Draw2dLabel( 10, 100, 2, white, false, "FlowGraphSystem Disabled");
*/
return;
}
if (m_bInspectingEnabled)
{
// call pre updates
// 1. system inspectors
std::for_each (m_systemInspectors.begin(), m_systemInspectors.end(), std::bind2nd (std::mem_fun(&IFlowGraphInspector::PreUpdate), (IFlowGraph*) 0));
// 2. graph inspectors TODO: optimize not to go over all graphs ;-)
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
const std::vector<IFlowGraphInspectorPtr>& graphInspectors (itGraph->GetInspectors());
std::for_each (graphInspectors.begin(), graphInspectors.end(), std::bind2nd (std::mem_fun(&IFlowGraphInspector::PreUpdate), *itGraph));
}
}
UpdateGraphs();
if (m_bInspectingEnabled)
{
// call post updates
// 1. system inspectors
std::for_each (m_systemInspectors.begin(), m_systemInspectors.end(), std::bind2nd (std::mem_fun(&IFlowGraphInspector::PostUpdate), (IFlowGraph*) 0));
// 2. graph inspectors TODO: optimize not to go over all graphs ;-)
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
const std::vector<IFlowGraphInspectorPtr>& graphInspectors (itGraph->GetInspectors());
std::for_each (graphInspectors.begin(), graphInspectors.end(), std::bind2nd (std::mem_fun(&IFlowGraphInspector::PostUpdate), *itGraph));
}
}
}
// end of flow system update: remove module instances which are no longer needed
m_pModuleManager->RemoveCompletedModuleInstances();
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::UpdateGraphs()
{
// Determine if graphs should be updated (Debug control)
bool bUpdateGraphs = true;
PREFAST_SUPPRESS_WARNING(6237);
if (gEnv->IsEditing() && CCryAction::GetCryAction()->IsGameStarted())
{
if (m_cVars.m_enableFlowgraphNodeDebugging == 2)
{
if (m_cVars.m_debugNextStep == 0)
{
bUpdateGraphs = false;
}
else
{
m_cVars.m_debugNextStep = 0;
}
}
}
if (bUpdateGraphs)
{
if (m_needToUpdateForwardings)
{
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
itGraph->UpdateForwardings();
}
m_needToUpdateForwardings = false;
}
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
itGraph->Update();
}
}
#ifndef _RELEASE
if (m_cVars.m_profile != 0)
{
IRenderer* pRend = gEnv->pRenderer;
float white[4] = {1, 1, 1, 1};
pRend->Draw2dLabel(10, 100, 2, white, false, "Number of Flow Graphs Updated: %d", FGProfile.graphsUpdated);
pRend->Draw2dLabel(10, 120, 2, white, false, "Number of Flow Graph Nodes Updated: %d", FGProfile.nodeUpdates);
pRend->Draw2dLabel(10, 140, 2, white, false, "Number of Flow Graph Nodes Activated: %d", FGProfile.nodeActivations);
}
FGProfile.Reset();
#endif //_RELEASE
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::Reset(bool unload)
{
m_needToUpdateForwardings = true; // does not hurt, and it prevents a potentially bad situation in save/load.
if (!unload)
{
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
itGraph->InitializeValues();
}
}
else
{
m_pModuleManager->ClearModules();
if (!m_graphs.Empty())
{
m_graphs.Clear(true);
}
for (std::vector<STypeInfo>::iterator it = m_typeRegistryVec.begin(), itEnd = m_typeRegistryVec.end(); it != itEnd; ++it)
{
if (it->factory.get())
{
it->factory->Reset();
}
}
}
// Clean up the containers
m_FlowSystemContainers.clear();
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::Init()
{
if (gEnv->pEntitySystem)
{
gEnv->pEntitySystem->AddSink(this, IEntitySystem::OnReused | IEntitySystem::OnSpawn, 0);
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::Shutdown()
{
if (gEnv->pEntitySystem)
{
gEnv->pEntitySystem->RemoveSink(this);
}
}
void CFlowSystem::Uninitialize()
{
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
itGraph->Uninitialize();
}
}
//////////////////////////////////////////////////////////////////////////
TFlowGraphId CFlowSystem::RegisterGraph(IFlowGraphPtr pGraph, const char* debugName)
{
return RegisterGraph(static_cast<CFlowGraph*>(pGraph.get()), debugName);
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::UnregisterGraph(IFlowGraphPtr pGraph)
{
UnregisterGraph(static_cast<CFlowGraph*>(pGraph.get()));
}
//////////////////////////////////////////////////////////////////////////
TFlowGraphId CFlowSystem::RegisterGraph(CFlowGraphBase* pGraph, const char* debugName)
{
m_graphs.Add(pGraph, debugName);
return m_nextFlowGraphId++;
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::UnregisterGraph(CFlowGraphBase* pGraph)
{
m_graphs.Remove(pGraph);
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::LoadBlacklistedFlownodeXML()
{
if (!m_blacklistNode)
{
const string filename = BLACKLIST_FILE_PATH;
m_blacklistNode = gEnv->pSystem->LoadXmlFromFile(filename);
}
}
//////////////////////////////////////////////////////////////////////////
bool CFlowSystem::BlacklistedFlownode(const char** nodeName)
{
if (m_blacklistNode)
{
int childCount = m_blacklistNode->getChildCount();
const char* attrKey;
const char* attrValue;
for (int n = 0; n < childCount; ++n)
{
XmlNodeRef child = m_blacklistNode->getChild(n);
if (!child->getAttributeByIndex(0, &attrKey, &attrValue))
{
continue;
}
if (!_stricmp(attrValue, *nodeName))
{
//replace name
int numAttr = child->getNumAttributes();
if (numAttr == 2 && child->getAttributeByIndex(1, &attrKey, &attrValue))
{
*nodeName = attrValue;
break;
}
//remove class
return false;
}
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::RegisterAutoTypes()
{
//////////////////////////////////////////////////////////////////////////
CAutoRegFlowNodeBase* pFactory = CAutoRegFlowNodeBase::m_pFirst;
while (pFactory)
{
RegisterType(pFactory->m_sClassName, pFactory);
if (pFactory->m_sAlias1)
{
RegisterType(pFactory->m_sAlias1, pFactory);
}
if (pFactory->m_sAlias2)
{
RegisterType(pFactory->m_sAlias2, pFactory);
}
pFactory = pFactory->m_pNext;
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::RegisterEntityTypes()
{
// Register all entity class from entities registry.
// Each entity class is registered as a flow type entity:ClassName, ex: entity:ProximityTrigger
IEntityClassRegistry* pClassRegistry = gEnv->pEntitySystem->GetClassRegistry();
IEntityClass* pEntityClass = 0;
pClassRegistry->IteratorMoveFirst();
while (pEntityClass = pClassRegistry->IteratorNext())
{
TryToRegisterEntityClass(pEntityClass);
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::TryToRegisterEntityClass(IEntityClass* entityClass)
{
if (!entityClass)
{
return;
}
string classname = GetEntityFlowNodeName(*entityClass);
INDENT_LOG_DURING_SCOPE(true, "Flow system is registering entity type '%s'", classname.c_str());
// if the entity lua script does not have input/outputs defined, and there is already an FG node defined for that entity in c++, do not register the empty lua one
// GetEventCount initializes the script system.
if (entityClass->GetEventCount() == 0 && GetTypeId(classname) != InvalidFlowNodeTypeId)
{
return;
}
RegisterType(classname, new CFlowEntityClass(entityClass));
}
//////////////////////////////////////////////////////////////////////////
const CFlowSystem::STypeInfo& CFlowSystem::GetTypeInfo(TFlowNodeTypeId typeId) const
{
assert (typeId < m_typeRegistryVec.size());
if (typeId < m_typeRegistryVec.size())
{
return m_typeRegistryVec[typeId];
}
return m_typeRegistryVec[InvalidFlowNodeTypeId];
}
//////////////////////////////////////////////////////////////////////////
string CFlowSystem::GetClassTagFromUIName(const string& uiName) const
{
return m_flowInitManager->GetClassTagFromUIName(AZStd::string(uiName.c_str())).c_str();
}
string CFlowSystem::GetUINameFromClassTag(const string& classTag) const
{
return m_flowInitManager->GetUINameFromClassTag(AZStd::string(classTag.c_str())).c_str();
}
//////////////////////////////////////////////////////////////////////////
const char* CFlowSystem::GetTypeName(TFlowNodeTypeId typeId)
{
assert (typeId < m_typeRegistryVec.size());
if (typeId < m_typeRegistryVec.size())
{
return m_typeRegistryVec[typeId].name.c_str();
}
return "";
}
//////////////////////////////////////////////////////////////////////////
TFlowNodeTypeId CFlowSystem::GetTypeId(const char* typeName)
{
return stl::find_in_map(m_typeNameToIdMap, GetClassTagFromUIName(CONST_TEMP_STRING(typeName)), InvalidFlowNodeTypeId);
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::RegisterInspector(IFlowGraphInspectorPtr pInspector, IFlowGraphPtr pGraph)
{
if (pGraph == 0)
{
stl::push_back_unique(m_systemInspectors, pInspector);
}
else
{
CFlowGraphBase* pCGraph = (CFlowGraphBase*)pGraph.get();
if (pCGraph && m_graphs.Contains(pCGraph))
{
pCGraph->RegisterInspector(pInspector);
}
else
{
GameWarning("CFlowSystem::RegisterInspector: Unknown graph 0x%p", (IFlowGraph*)pGraph);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::UnregisterInspector(IFlowGraphInspectorPtr pInspector, IFlowGraphPtr pGraph)
{
if (pGraph == 0)
{
stl::find_and_erase(m_systemInspectors, pInspector);
}
else
{
CFlowGraphBase* pCGraph = (CFlowGraphBase*)pGraph.get();
if (pCGraph && m_graphs.Contains(pCGraph))
{
pCGraph->UnregisterInspector(pInspector);
}
else
{
GameWarning("CFlowSystem::UnregisterInspector: Unknown graph 0x%p", (IFlowGraph*)pGraph);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::NotifyFlow(CFlowGraphBase* pGraph, const SFlowAddress from, const SFlowAddress to)
{
if (!m_bInspectingEnabled)
{
return;
}
if (!m_systemInspectors.empty())
{
std::vector<IFlowGraphInspectorPtr>::iterator iter (m_systemInspectors.begin());
while (iter != m_systemInspectors.end())
{
(*iter)->NotifyFlow(pGraph, from, to);
++iter;
}
}
const std::vector<IFlowGraphInspectorPtr>& graphInspectors (pGraph->GetInspectors());
if (!graphInspectors.empty())
{
std::vector<IFlowGraphInspectorPtr>::const_iterator iter (graphInspectors.begin());
while (iter != graphInspectors.end())
{
(*iter)->NotifyFlow(pGraph, from, to);
++iter;
}
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::NotifyProcessEvent(CFlowGraphBase* pGraph, IFlowNode::EFlowEvent event, IFlowNode::SActivationInfo* pActInfo, IFlowNode* pImpl)
{
if (!m_bInspectingEnabled)
{
return;
}
}
//////////////////////////////////////////////////////////////////////////
IFlowGraph* CFlowSystem::GetGraphById(TFlowGraphId graphId)
{
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
CFlowGraphBase* pFlowGraph = *itGraph;
if (pFlowGraph->GetGraphId() == graphId)
{
return pFlowGraph;
}
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::GetMemoryUsage(ICrySizer* pSizer) const
{
SIZER_SUBCOMPONENT_NAME(pSizer, "FlowSystem");
pSizer->AddObject(this, sizeof(*this));
{
SIZER_SUBCOMPONENT_NAME(pSizer, "Factories");
{
SIZER_SUBCOMPONENT_NAME(pSizer, "FactoriesLookup");
pSizer->AddObject(m_typeNameToIdMap);
pSizer->AddObject(m_typeRegistryVec);
}
}
{
SIZER_SUBCOMPONENT_NAME(pSizer, "Inspectors");
pSizer->AddObject(m_systemInspectors);
}
if (!m_graphs.Empty())
{
SIZER_SUBCOMPONENT_NAME(pSizer, "Graphs");
pSizer->AddObject(&m_graphs, m_graphs.MemSize());
}
if (!m_FlowSystemContainers.empty())
{
SIZER_SUBCOMPONENT_NAME(pSizer, "Containers");
for (TFlowSystemContainerMap::const_iterator it = m_FlowSystemContainers.begin(); it != m_FlowSystemContainers.end(); ++it)
{
(*it).second->GetMemoryUsage(pSizer);
}
pSizer->AddObject(&(*m_FlowSystemContainers.begin()), m_FlowSystemContainers.size() * (sizeof(CFlowSystemContainer) + sizeof(TFlowSystemContainerId)));
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::OnReused(IEntity* pEntity, SEntitySpawnParams& params)
{
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
itGraph->OnEntityReused(pEntity, params);
}
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::OnEntityClassRegistryEvent(EEntityClassRegistryEvent event, const IEntityClass* pEntityClass)
{
// IEntityClass has some getter functions (ex: IEntityClass::GetEventCount())
// that trigger a lazy load; therefore the functions are non-const.
// The flow system needs to call these getters so we need to cast
// away the const here.
// A better solution would be to make the getters const by marking
// the lazily loaded data in IEntityClass as mutable.
IEntityClass* pNonConstEntityClass = const_cast<IEntityClass*>(pEntityClass);
TryToRegisterEntityClass(pNonConstEntityClass);
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::OnEntityIdChanged(FlowEntityId oldId, FlowEntityId newId)
{
for (TGraphs::Notifier itGraph(m_graphs); itGraph.IsValid(); itGraph.Next())
{
itGraph->OnEntityIdChanged(oldId, newId);
}
}
//////////////////////////////////////////////////////////////////////////
bool CFlowSystem::CreateContainer(TFlowSystemContainerId id)
{
if (m_FlowSystemContainers.find(id) != m_FlowSystemContainers.end())
{
return false;
}
IFlowSystemContainerPtr container(new CFlowSystemContainer);
m_FlowSystemContainers.insert(std::make_pair(id, container));
return true;
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::DeleteContainer(TFlowSystemContainerId id)
{
std::map<TFlowSystemContainerId, IFlowSystemContainerPtr>::iterator it = m_FlowSystemContainers.find(id);
if (it != m_FlowSystemContainers.end())
{
m_FlowSystemContainers.erase(it);
}
}
//////////////////////////////////////////////////////////////////////////
IFlowSystemContainerPtr CFlowSystem::GetContainer(TFlowSystemContainerId id)
{
return m_FlowSystemContainers[id];
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::OnSpawn(IEntity* pEntity, SEntitySpawnParams& params)
{
// this should be a more generic test: maybe an entity flag "CAN_FORWARD_FLOWGRAPHS", or something similar
if ((pEntity->GetFlags() & ENTITY_FLAG_HAS_AI) != 0)
{
m_needToUpdateForwardings = true;
}
}
//////////////////////////////////////////////////////////////////////////
IFlowGraphModuleManager* CFlowSystem::GetIModuleManager()
{
return m_pModuleManager;
}
//////////////////////////////////////////////////////////////////////////
void CFlowSystem::Serialize(TSerialize ser)
{
int count = m_FlowSystemContainers.size();
ser.Value("ContainerCount", count);
if (ser.IsWriting())
{
TFlowSystemContainerMap::iterator it = m_FlowSystemContainers.begin();
while (it != m_FlowSystemContainers.end())
{
ser.BeginGroup("Containers");
TFlowSystemContainerId id = (*it).first;
ser.Value("key", id);
(*it).second->Serialize(ser);
ser.EndGroup();
++it;
}
}
else
{
int id;
for (int i = 0; i < count; i++)
{
ser.BeginGroup("Containers");
ser.Value("key", id);
if (CreateContainer(id))
{
IFlowSystemContainerPtr container = GetContainer(id);
if (container)
{
container->Serialize(ser);
}
else
{
CryWarning(VALIDATOR_MODULE_FLOWGRAPH, VALIDATOR_ERROR, "CFlowSystem::Serialize: Could not create or get container with ID from save file - container not restored");
}
}
ser.EndGroup();
}
}
}
|
/*
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.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 "TestExecutor.h"
using namespace std;
namespace folly {
TestExecutor::TestExecutor(size_t numThreads) {
const auto kWorkers = std::max(size_t(1), numThreads);
for (auto idx = 0u; idx < kWorkers; ++idx) {
workers_.emplace_back([this] {
while (true) {
Func work;
{
unique_lock<mutex> lk(m_);
cv_.wait(lk, [this] { return !workItems_.empty(); });
work = std::move(workItems_.front());
workItems_.pop();
}
if (!work) {
break;
}
work();
}
});
}
}
TestExecutor::~TestExecutor() {
for (auto& worker : workers_) {
(void)worker;
addImpl({});
}
for (auto& worker : workers_) {
worker.join();
}
}
void TestExecutor::add(Func f) {
if (f) {
addImpl(std::move(f));
}
}
size_t TestExecutor::numThreads() const {
return workers_.size();
}
void TestExecutor::addImpl(Func f) {
{
lock_guard<mutex> g(m_);
workItems_.push(std::move(f));
}
cv_.notify_one();
}
} // namespace folly
|
//
// socket_base.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include "asio/socket_base.hpp"
#include "asio/io_context.hpp"
#include "asio/ip/tcp.hpp"
#include "asio/ip/udp.hpp"
#include "unit_test.hpp"
//------------------------------------------------------------------------------
// socket_base_compile test
// ~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that all nested classes, enums and constants in
// socket_base compile and link correctly. Runtime failures are ignored.
namespace socket_base_compile {
void test()
{
using namespace asio;
namespace ip = asio::ip;
try
{
io_context ioc;
ip::tcp::socket sock(ioc);
char buf[1024];
// shutdown_type enumeration.
sock.shutdown(socket_base::shutdown_receive);
sock.shutdown(socket_base::shutdown_send);
sock.shutdown(socket_base::shutdown_both);
// message_flags constants.
sock.receive(buffer(buf), socket_base::message_peek);
sock.receive(buffer(buf), socket_base::message_out_of_band);
sock.send(buffer(buf), socket_base::message_do_not_route);
// broadcast class.
socket_base::broadcast broadcast1(true);
sock.set_option(broadcast1);
socket_base::broadcast broadcast2;
sock.get_option(broadcast2);
broadcast1 = true;
(void)static_cast<bool>(broadcast1);
(void)static_cast<bool>(!broadcast1);
(void)static_cast<bool>(broadcast1.value());
// debug class.
socket_base::debug debug1(true);
sock.set_option(debug1);
socket_base::debug debug2;
sock.get_option(debug2);
debug1 = true;
(void)static_cast<bool>(debug1);
(void)static_cast<bool>(!debug1);
(void)static_cast<bool>(debug1.value());
// do_not_route class.
socket_base::do_not_route do_not_route1(true);
sock.set_option(do_not_route1);
socket_base::do_not_route do_not_route2;
sock.get_option(do_not_route2);
do_not_route1 = true;
(void)static_cast<bool>(do_not_route1);
(void)static_cast<bool>(!do_not_route1);
(void)static_cast<bool>(do_not_route1.value());
// keep_alive class.
socket_base::keep_alive keep_alive1(true);
sock.set_option(keep_alive1);
socket_base::keep_alive keep_alive2;
sock.get_option(keep_alive2);
keep_alive1 = true;
(void)static_cast<bool>(keep_alive1);
(void)static_cast<bool>(!keep_alive1);
(void)static_cast<bool>(keep_alive1.value());
// send_buffer_size class.
socket_base::send_buffer_size send_buffer_size1(1024);
sock.set_option(send_buffer_size1);
socket_base::send_buffer_size send_buffer_size2;
sock.get_option(send_buffer_size2);
send_buffer_size1 = 1;
(void)static_cast<int>(send_buffer_size1.value());
// send_low_watermark class.
socket_base::send_low_watermark send_low_watermark1(128);
sock.set_option(send_low_watermark1);
socket_base::send_low_watermark send_low_watermark2;
sock.get_option(send_low_watermark2);
send_low_watermark1 = 1;
(void)static_cast<int>(send_low_watermark1.value());
// receive_buffer_size class.
socket_base::receive_buffer_size receive_buffer_size1(1024);
sock.set_option(receive_buffer_size1);
socket_base::receive_buffer_size receive_buffer_size2;
sock.get_option(receive_buffer_size2);
receive_buffer_size1 = 1;
(void)static_cast<int>(receive_buffer_size1.value());
// receive_low_watermark class.
socket_base::receive_low_watermark receive_low_watermark1(128);
sock.set_option(receive_low_watermark1);
socket_base::receive_low_watermark receive_low_watermark2;
sock.get_option(receive_low_watermark2);
receive_low_watermark1 = 1;
(void)static_cast<int>(receive_low_watermark1.value());
// reuse_address class.
socket_base::reuse_address reuse_address1(true);
sock.set_option(reuse_address1);
socket_base::reuse_address reuse_address2;
sock.get_option(reuse_address2);
reuse_address1 = true;
(void)static_cast<bool>(reuse_address1);
(void)static_cast<bool>(!reuse_address1);
(void)static_cast<bool>(reuse_address1.value());
// linger class.
socket_base::linger linger1(true, 30);
sock.set_option(linger1);
socket_base::linger linger2;
sock.get_option(linger2);
linger1.enabled(true);
(void)static_cast<bool>(linger1.enabled());
linger1.timeout(1);
(void)static_cast<int>(linger1.timeout());
// enable_connection_aborted class.
socket_base::enable_connection_aborted enable_connection_aborted1(true);
sock.set_option(enable_connection_aborted1);
socket_base::enable_connection_aborted enable_connection_aborted2;
sock.get_option(enable_connection_aborted2);
enable_connection_aborted1 = true;
(void)static_cast<bool>(enable_connection_aborted1);
(void)static_cast<bool>(!enable_connection_aborted1);
(void)static_cast<bool>(enable_connection_aborted1.value());
// bytes_readable class.
socket_base::bytes_readable bytes_readable;
sock.io_control(bytes_readable);
std::size_t bytes = bytes_readable.get();
(void)bytes;
}
catch (std::exception&)
{
}
}
} // namespace socket_base_compile
//------------------------------------------------------------------------------
// socket_base_runtime test
// ~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks the runtime operation of the socket options and I/O
// control commands defined in socket_base.
namespace socket_base_runtime {
void test()
{
using namespace asio;
namespace ip = asio::ip;
io_context ioc;
ip::udp::socket udp_sock(ioc, ip::udp::v4());
ip::tcp::socket tcp_sock(ioc, ip::tcp::v4());
ip::tcp::acceptor tcp_acceptor(ioc, ip::tcp::v4());
asio::error_code ec;
// broadcast class.
socket_base::broadcast broadcast1(true);
ASIO_CHECK(broadcast1.value());
ASIO_CHECK(static_cast<bool>(broadcast1));
ASIO_CHECK(!!broadcast1);
udp_sock.set_option(broadcast1, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::broadcast broadcast2;
udp_sock.get_option(broadcast2, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(broadcast2.value());
ASIO_CHECK(static_cast<bool>(broadcast2));
ASIO_CHECK(!!broadcast2);
socket_base::broadcast broadcast3(false);
ASIO_CHECK(!broadcast3.value());
ASIO_CHECK(!static_cast<bool>(broadcast3));
ASIO_CHECK(!broadcast3);
udp_sock.set_option(broadcast3, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::broadcast broadcast4;
udp_sock.get_option(broadcast4, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(!broadcast4.value());
ASIO_CHECK(!static_cast<bool>(broadcast4));
ASIO_CHECK(!broadcast4);
// debug class.
socket_base::debug debug1(true);
ASIO_CHECK(debug1.value());
ASIO_CHECK(static_cast<bool>(debug1));
ASIO_CHECK(!!debug1);
udp_sock.set_option(debug1, ec);
#if defined(__linux__)
// On Linux, only root can set SO_DEBUG.
bool not_root = (ec == asio::error::access_denied);
ASIO_CHECK(!ec || not_root);
ASIO_WARN_MESSAGE(!ec, "Must be root to set debug socket option");
#else // defined(__linux__)
# if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
# else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
#endif // defined(__linux__)
socket_base::debug debug2;
udp_sock.get_option(debug2, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# if defined(__linux__)
ASIO_CHECK(debug2.value() || not_root);
ASIO_CHECK(static_cast<bool>(debug2) || not_root);
ASIO_CHECK(!!debug2 || not_root);
# else // defined(__linux__)
ASIO_CHECK(debug2.value());
ASIO_CHECK(static_cast<bool>(debug2));
ASIO_CHECK(!!debug2);
# endif // defined(__linux__)
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
socket_base::debug debug3(false);
ASIO_CHECK(!debug3.value());
ASIO_CHECK(!static_cast<bool>(debug3));
ASIO_CHECK(!debug3);
udp_sock.set_option(debug3, ec);
#if defined(__linux__)
ASIO_CHECK(!ec || not_root);
#else // defined(__linux__)
# if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
# else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
#endif // defined(__linux__)
socket_base::debug debug4;
udp_sock.get_option(debug4, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
# if defined(__linux__)
ASIO_CHECK(!debug4.value() || not_root);
ASIO_CHECK(!static_cast<bool>(debug4) || not_root);
ASIO_CHECK(!debug4 || not_root);
# else // defined(__linux__)
ASIO_CHECK(!debug4.value());
ASIO_CHECK(!static_cast<bool>(debug4));
ASIO_CHECK(!debug4);
# endif // defined(__linux__)
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
// do_not_route class.
socket_base::do_not_route do_not_route1(true);
ASIO_CHECK(do_not_route1.value());
ASIO_CHECK(static_cast<bool>(do_not_route1));
ASIO_CHECK(!!do_not_route1);
udp_sock.set_option(do_not_route1, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
socket_base::do_not_route do_not_route2;
udp_sock.get_option(do_not_route2, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(do_not_route2.value());
ASIO_CHECK(static_cast<bool>(do_not_route2));
ASIO_CHECK(!!do_not_route2);
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
socket_base::do_not_route do_not_route3(false);
ASIO_CHECK(!do_not_route3.value());
ASIO_CHECK(!static_cast<bool>(do_not_route3));
ASIO_CHECK(!do_not_route3);
udp_sock.set_option(do_not_route3, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
socket_base::do_not_route do_not_route4;
udp_sock.get_option(do_not_route4, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(!do_not_route4.value());
ASIO_CHECK(!static_cast<bool>(do_not_route4));
ASIO_CHECK(!do_not_route4);
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
// keep_alive class.
socket_base::keep_alive keep_alive1(true);
ASIO_CHECK(keep_alive1.value());
ASIO_CHECK(static_cast<bool>(keep_alive1));
ASIO_CHECK(!!keep_alive1);
tcp_sock.set_option(keep_alive1, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::keep_alive keep_alive2;
tcp_sock.get_option(keep_alive2, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(keep_alive2.value());
ASIO_CHECK(static_cast<bool>(keep_alive2));
ASIO_CHECK(!!keep_alive2);
socket_base::keep_alive keep_alive3(false);
ASIO_CHECK(!keep_alive3.value());
ASIO_CHECK(!static_cast<bool>(keep_alive3));
ASIO_CHECK(!keep_alive3);
tcp_sock.set_option(keep_alive3, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::keep_alive keep_alive4;
tcp_sock.get_option(keep_alive4, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(!keep_alive4.value());
ASIO_CHECK(!static_cast<bool>(keep_alive4));
ASIO_CHECK(!keep_alive4);
// send_buffer_size class.
socket_base::send_buffer_size send_buffer_size1(4096);
ASIO_CHECK(send_buffer_size1.value() == 4096);
tcp_sock.set_option(send_buffer_size1, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::send_buffer_size send_buffer_size2;
tcp_sock.get_option(send_buffer_size2, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(send_buffer_size2.value() == 4096);
socket_base::send_buffer_size send_buffer_size3(16384);
ASIO_CHECK(send_buffer_size3.value() == 16384);
tcp_sock.set_option(send_buffer_size3, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::send_buffer_size send_buffer_size4;
tcp_sock.get_option(send_buffer_size4, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(send_buffer_size4.value() == 16384);
// send_low_watermark class.
socket_base::send_low_watermark send_low_watermark1(4096);
ASIO_CHECK(send_low_watermark1.value() == 4096);
tcp_sock.set_option(send_low_watermark1, ec);
#if defined(WIN32) || defined(__linux__) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows, Linux or Solaris.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::send_low_watermark send_low_watermark2;
tcp_sock.get_option(send_low_watermark2, ec);
#if defined(WIN32) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows or Solaris.
#elif defined(__linux__)
ASIO_CHECK(!ec); // Not supported on Linux but can get value.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(send_low_watermark2.value() == 4096);
#endif
socket_base::send_low_watermark send_low_watermark3(8192);
ASIO_CHECK(send_low_watermark3.value() == 8192);
tcp_sock.set_option(send_low_watermark3, ec);
#if defined(WIN32) || defined(__linux__) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows, Linux or Solaris.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::send_low_watermark send_low_watermark4;
tcp_sock.get_option(send_low_watermark4, ec);
#if defined(WIN32) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows or Solaris.
#elif defined(__linux__)
ASIO_CHECK(!ec); // Not supported on Linux but can get value.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(send_low_watermark4.value() == 8192);
#endif
// receive_buffer_size class.
socket_base::receive_buffer_size receive_buffer_size1(4096);
ASIO_CHECK(receive_buffer_size1.value() == 4096);
tcp_sock.set_option(receive_buffer_size1, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
socket_base::receive_buffer_size receive_buffer_size2;
tcp_sock.get_option(receive_buffer_size2, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK(!ec); // Not supported under Windows CE but can get value.
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(receive_buffer_size2.value() == 4096);
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
socket_base::receive_buffer_size receive_buffer_size3(16384);
ASIO_CHECK(receive_buffer_size3.value() == 16384);
tcp_sock.set_option(receive_buffer_size3, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
// Option is not supported under Windows CE.
ASIO_CHECK_MESSAGE(ec == asio::error::no_protocol_option,
ec.value() << ", " << ec.message());
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
socket_base::receive_buffer_size receive_buffer_size4;
tcp_sock.get_option(receive_buffer_size4, ec);
#if defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK(!ec); // Not supported under Windows CE but can get value.
#else // defined(ASIO_WINDOWS) && defined(UNDER_CE)
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(receive_buffer_size4.value() == 16384);
#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE)
// receive_low_watermark class.
socket_base::receive_low_watermark receive_low_watermark1(4096);
ASIO_CHECK(receive_low_watermark1.value() == 4096);
tcp_sock.set_option(receive_low_watermark1, ec);
#if defined(WIN32) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::receive_low_watermark receive_low_watermark2;
tcp_sock.get_option(receive_low_watermark2, ec);
#if defined(WIN32) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(receive_low_watermark2.value() == 4096);
#endif
socket_base::receive_low_watermark receive_low_watermark3(8192);
ASIO_CHECK(receive_low_watermark3.value() == 8192);
tcp_sock.set_option(receive_low_watermark3, ec);
#if defined(WIN32) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
#endif
socket_base::receive_low_watermark receive_low_watermark4;
tcp_sock.get_option(receive_low_watermark4, ec);
#if defined(WIN32) || defined(__sun)
ASIO_CHECK(!!ec); // Not supported on Windows or Solaris.
#else
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(receive_low_watermark4.value() == 8192);
#endif
// reuse_address class.
socket_base::reuse_address reuse_address1(true);
ASIO_CHECK(reuse_address1.value());
ASIO_CHECK(static_cast<bool>(reuse_address1));
ASIO_CHECK(!!reuse_address1);
udp_sock.set_option(reuse_address1, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::reuse_address reuse_address2;
udp_sock.get_option(reuse_address2, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(reuse_address2.value());
ASIO_CHECK(static_cast<bool>(reuse_address2));
ASIO_CHECK(!!reuse_address2);
socket_base::reuse_address reuse_address3(false);
ASIO_CHECK(!reuse_address3.value());
ASIO_CHECK(!static_cast<bool>(reuse_address3));
ASIO_CHECK(!reuse_address3);
udp_sock.set_option(reuse_address3, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::reuse_address reuse_address4;
udp_sock.get_option(reuse_address4, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(!reuse_address4.value());
ASIO_CHECK(!static_cast<bool>(reuse_address4));
ASIO_CHECK(!reuse_address4);
// linger class.
socket_base::linger linger1(true, 60);
ASIO_CHECK(linger1.enabled());
ASIO_CHECK(linger1.timeout() == 60);
tcp_sock.set_option(linger1, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::linger linger2;
tcp_sock.get_option(linger2, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(linger2.enabled());
ASIO_CHECK(linger2.timeout() == 60);
socket_base::linger linger3(false, 0);
ASIO_CHECK(!linger3.enabled());
ASIO_CHECK(linger3.timeout() == 0);
tcp_sock.set_option(linger3, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::linger linger4;
tcp_sock.get_option(linger4, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(!linger4.enabled());
// enable_connection_aborted class.
socket_base::enable_connection_aborted enable_connection_aborted1(true);
ASIO_CHECK(enable_connection_aborted1.value());
ASIO_CHECK(static_cast<bool>(enable_connection_aborted1));
ASIO_CHECK(!!enable_connection_aborted1);
tcp_acceptor.set_option(enable_connection_aborted1, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::enable_connection_aborted enable_connection_aborted2;
tcp_acceptor.get_option(enable_connection_aborted2, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(enable_connection_aborted2.value());
ASIO_CHECK(static_cast<bool>(enable_connection_aborted2));
ASIO_CHECK(!!enable_connection_aborted2);
socket_base::enable_connection_aborted enable_connection_aborted3(false);
ASIO_CHECK(!enable_connection_aborted3.value());
ASIO_CHECK(!static_cast<bool>(enable_connection_aborted3));
ASIO_CHECK(!enable_connection_aborted3);
tcp_acceptor.set_option(enable_connection_aborted3, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
socket_base::enable_connection_aborted enable_connection_aborted4;
tcp_acceptor.get_option(enable_connection_aborted4, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
ASIO_CHECK(!enable_connection_aborted4.value());
ASIO_CHECK(!static_cast<bool>(enable_connection_aborted4));
ASIO_CHECK(!enable_connection_aborted4);
// bytes_readable class.
socket_base::bytes_readable bytes_readable;
udp_sock.io_control(bytes_readable, ec);
ASIO_CHECK_MESSAGE(!ec, ec.value() << ", " << ec.message());
}
} // namespace socket_base_runtime
//------------------------------------------------------------------------------
ASIO_TEST_SUITE
(
"socket_base",
ASIO_TEST_CASE(socket_base_compile::test)
ASIO_TEST_CASE(socket_base_runtime::test)
)
|
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dali/operators/geometry/affine_transforms/transform_base_op.h"
#include "dali/pipeline/data/views.h"
namespace dali {
DALI_SCHEMA(transforms__Scale)
.DocStr(R"code(Produces a scale affine transform matrix.
If another transform matrix is passed as an input, the operator applies scaling to the matrix provided.
.. note::
The output of this operator can be fed directly to ``CoordTransform`` and ``WarpAffine`` operators.
)code")
.AddArg(
"scale",
R"code(The scale factor, per dimension.
The number of dimensions of the transform is inferred from this argument.)code",
DALI_FLOAT_VEC, true)
.AddOptionalArg<std::vector<float>>(
"center",
R"code(The center of the scale operation.
If provided, the number of elements should match the one of ``scale`` argument.)code",
nullptr, true)
.AddOptionalArg<int>(
"ndim",
R"code(Number of dimensions.
It should be provided when the number of dimensions can't be inferred. For example,
when `scale` is a scalar value and there's no input transform.
)code",
nullptr, false)
.NumInput(0, 1)
.NumOutput(1)
.AddParent("TransformAttr");
/**
* @brief Scale transformation.
*/
class TransformScaleCPU
: public TransformBaseOp<CPUBackend, TransformScaleCPU> {
public:
using SupportedDims = dims<1, 2, 3, 4, 5, 6>;
explicit TransformScaleCPU(const OpSpec &spec) :
TransformBaseOp<CPUBackend, TransformScaleCPU>(spec),
scale_("scale", spec),
center_("center", spec) {
assert(scale_.IsDefined());
if (spec.HasArgument("ndim"))
ndim_arg_ = spec.GetArgument<int>("ndim");
}
template <typename T, int mat_dim>
void DefineTransforms(span<affine_mat_t<T, mat_dim>> matrices) {
constexpr int ndim = mat_dim - 1;
assert(matrices.size() <= static_cast<int>(scale_.size()));
for (int i = 0; i < matrices.size(); i++) {
auto &mat = matrices[i];
auto scale = as_vec<ndim>(scale_[i]);
mat = affine_mat_t<T, mat_dim>::identity();
for (int d = 0; d < ndim; d++) {
mat(d, d) = scale[d];
}
if (center_.IsDefined()) {
auto center = center_[i].data;
for (int d = 0; d < ndim; d++) {
mat(d, ndim) = center[d] * (T(1) - scale[d]);
}
}
}
}
void ProcessArgs(const OpSpec &spec, const workspace_t<CPUBackend> &ws) {
assert(scale_.IsDefined());
scale_.Acquire(spec, ws, nsamples_, true);
int scale_ndim = scale_[0].num_elements();
if (scale_ndim > 1) {
ndim_ = scale_ndim;
} else if (has_input_) {
ndim_ = input_transform_ndim(ws);
} else if (ndim_arg_ > 0) {
ndim_ = ndim_arg_;
} else {
ndim_ = 1;
}
if (center_.IsDefined()) {
center_.Acquire(spec, ws, nsamples_, TensorShape<1>{ndim_});
}
}
bool IsConstantTransform() const {
return !scale_.IsArgInput() && !center_.IsArgInput();
}
private:
ArgValue<float, 1> scale_;
ArgValue<float, 1> center_;
int ndim_arg_ = -1;
};
DALI_REGISTER_OPERATOR(transforms__Scale, TransformScaleCPU, CPU);
} // namespace dali
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/prerender/prerender_dispatcher.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace prerender {
class PrerenderDispatcherTest : public testing::Test {
public:
PrerenderDispatcherTest() {}
bool is_prerender_url(const GURL& url) const {
return prerender_dispatcher_.IsPrerenderURL(url);
}
const PrerenderDispatcher::PrerenderMap& urls() const {
return prerender_dispatcher_.prerender_urls_;
}
void AddURL(const GURL& url) { prerender_dispatcher_.OnAddPrerenderURL(url); }
void RemoveURL(const GURL& url) {
prerender_dispatcher_.OnRemovePrerenderURL(url);
}
int GetCountForURL(const GURL& url) const {
PrerenderDispatcher::PrerenderMap::const_iterator entry = urls().find(url);
if (entry == urls().end())
return 0;
EXPECT_GT(entry->second, 0);
return entry->second;
}
private:
PrerenderDispatcher prerender_dispatcher_;
DISALLOW_COPY_AND_ASSIGN(PrerenderDispatcherTest);
};
TEST_F(PrerenderDispatcherTest, PrerenderDispatcherEmpty) {
EXPECT_EQ(0U, urls().size());
}
TEST_F(PrerenderDispatcherTest, PrerenderDispatcherSingleAdd) {
GURL foo_url = GURL("http://foo.com");
EXPECT_FALSE(is_prerender_url(foo_url));
AddURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
EXPECT_EQ(1, GetCountForURL(foo_url));
}
TEST_F(PrerenderDispatcherTest, PrerenderDispatcherMultipleAdd) {
GURL foo_url = GURL("http://foo.com");
GURL bar_url = GURL("http://bar.com");
EXPECT_FALSE(is_prerender_url(foo_url));
EXPECT_FALSE(is_prerender_url(bar_url));
AddURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
EXPECT_FALSE(is_prerender_url(bar_url));
AddURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
EXPECT_FALSE(is_prerender_url(bar_url));
EXPECT_EQ(2, GetCountForURL(foo_url));
AddURL(bar_url);
EXPECT_TRUE(is_prerender_url(foo_url));
EXPECT_TRUE(is_prerender_url(bar_url));
EXPECT_EQ(2, GetCountForURL(foo_url));
EXPECT_EQ(1, GetCountForURL(bar_url));
}
TEST_F(PrerenderDispatcherTest, PrerenderDispatcherSingleRemove) {
GURL foo_url = GURL("http://foo.com");
EXPECT_FALSE(is_prerender_url(foo_url));
AddURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
RemoveURL(foo_url);
EXPECT_FALSE(is_prerender_url(foo_url));
EXPECT_EQ(0, GetCountForURL(foo_url));
}
TEST_F(PrerenderDispatcherTest, PrerenderDispatcherMultipleRemove) {
GURL foo_url = GURL("http://foo.com");
EXPECT_FALSE(is_prerender_url(foo_url));
AddURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
AddURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
EXPECT_EQ(2, GetCountForURL(foo_url));
RemoveURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
EXPECT_EQ(1, GetCountForURL(foo_url));
RemoveURL(foo_url);
EXPECT_FALSE(is_prerender_url(foo_url));
EXPECT_EQ(0, GetCountForURL(foo_url));
}
TEST_F(PrerenderDispatcherTest, PrerenderDispatcherRemoveWithoutAdd) {
GURL foo_url = GURL("http://foo.com");
EXPECT_FALSE(is_prerender_url(foo_url));
RemoveURL(foo_url);
EXPECT_FALSE(is_prerender_url(foo_url));
EXPECT_EQ(0, GetCountForURL(foo_url));
}
TEST_F(PrerenderDispatcherTest, PrerenderDispatcherRemoveTooMany) {
GURL foo_url = GURL("http://foo.com");
EXPECT_FALSE(is_prerender_url(foo_url));
AddURL(foo_url);
EXPECT_TRUE(is_prerender_url(foo_url));
RemoveURL(foo_url);
EXPECT_FALSE(is_prerender_url(foo_url));
RemoveURL(foo_url);
EXPECT_FALSE(is_prerender_url(foo_url));
EXPECT_EQ(0, GetCountForURL(foo_url));
}
} // end namespace prerender
|
/*
* Toolchain.cpp
* Copyright 2021 ItJustWorksTM
*
* 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 <SMCE/Toolchain.hpp>
#include <fstream>
#include <string>
#include <system_error>
#include <boost/predef.h>
#include <boost/process.hpp>
#if BOOST_OS_WINDOWS
# include <boost/process/windows.hpp>
#endif
#include <SMCE/PluginManifest.hpp>
#include <SMCE/SMCE_iface.h>
#include <SMCE/Sketch.hpp>
#include <SMCE/SketchConf.hpp>
#include <SMCE/internal/BoardDeviceSpecification.hpp>
#include <SMCE/internal/utils.hpp>
using namespace std::literals;
namespace bp = boost::process;
namespace smce {
namespace detail {
struct toolchain_error_category : public std::error_category {
public:
const char* name() const noexcept override { return "smce.toolchain"; }
std::string message(int ev) const override {
switch (static_cast<toolchain_error>(ev)) {
case toolchain_error::resdir_absent:
return "Resource directory does not exist";
case toolchain_error::resdir_empty:
return "Resource directory empty";
case toolchain_error::resdir_file:
return "Resource directory is a file";
case toolchain_error::cmake_not_found:
return "CMake not found in PATH";
case toolchain_error::cmake_unknown_output:
return "CMake output unrecognized";
case toolchain_error::invalid_plugin_name:
return "Plugin name is \".\", \"..\", or contains a forward slash";
case toolchain_error::sketch_invalid:
return "Sketch path is invalid";
case toolchain_error::configure_failed:
return "CMake configure failed";
case toolchain_error::build_failed:
return "CMake build failed";
default:
return "smce.toolchain error";
}
}
std::error_condition default_error_condition(int ev) const noexcept override {
return std::error_condition{ev, *this};
}
bool equivalent(int ev, const std::error_condition& condition) const noexcept override {
return condition.value() == ev && &condition.category() == this;
}
bool equivalent(const std::error_code& error, int ev) const noexcept override {
return error.value() == ev && &error.category() == this;
}
};
const std::error_category& get_exec_ctx_error_category() noexcept {
static const toolchain_error_category cat{};
return cat;
}
} // namespace detail
std::error_code make_error_code(toolchain_error ev) noexcept {
return std::error_code{static_cast<std::underlying_type<toolchain_error>::type>(ev),
detail::get_exec_ctx_error_category()};
}
struct ProcessedLibs {
std::string pp_remote_arg = "-DPREPROC_REMOTE_LIBS=";
};
ProcessedLibs process_libraries(const SketchConfig& skonf) noexcept {
ProcessedLibs ret;
for (const auto& lib : skonf.legacy_preproc_libs) {
ret.pp_remote_arg += lib.name;
if (!lib.version.empty())
ret.pp_remote_arg += '@' + lib.version;
ret.pp_remote_arg += ';';
}
if (ret.pp_remote_arg.back() == ';')
ret.pp_remote_arg.pop_back();
return ret;
}
SMCE_INTERNAL std::error_code write_manifests(const SketchConfig& skonf, const stdfs::path& tmpdir) {
const auto manifests_dir = tmpdir / "manifests";
{
std::error_code ec;
stdfs::create_directory(manifests_dir, ec);
if (ec)
return ec;
}
for (const auto& pm : skonf.plugins) {
if (pm.name == "." || pm.name == ".." || pm.name.find('/') != std::string::npos)
return toolchain_error::invalid_plugin_name;
if (const auto ec = write_manifest(pm, manifests_dir / (pm.name + ".cmake")))
return ec;
}
return {};
}
SMCE_INTERNAL void write_devices_specs(const SketchConfig& skonf, const stdfs::path& tmpdir) {
std::ofstream f{tmpdir / "Devices.cmake"};
f << "# HSD generated\ninclude (BindGen)\n";
for (const auto& e : skonf.genbind_devices)
f << "smce_bindgen_sketch (" << e.get().full_string << ")\n";
}
Toolchain::Toolchain(stdfs::path resources_dir) noexcept : m_res_dir{std::move(resources_dir)} {
m_build_log.reserve(4096);
}
std::error_code Toolchain::do_configure(Sketch& sketch) noexcept {
const auto sketch_hexid = sketch.m_uuid.to_hex();
sketch.m_tmpdir = this->m_res_dir / "tmp" / sketch_hexid;
{
std::error_code ec;
stdfs::create_directories(sketch.m_tmpdir, ec);
if (ec)
return ec;
}
#if !BOOST_OS_WINDOWS
const char* const generator_override = std::getenv("CMAKE_GENERATOR");
const char* const generator =
generator_override ? generator_override : (!bp::search_path("ninja").empty() ? "Ninja" : "");
#endif
write_devices_specs(sketch.m_conf, sketch.m_tmpdir);
if (const auto ec = write_manifests(sketch.m_conf, sketch.m_tmpdir))
return ec;
ProcessedLibs libs = process_libraries(sketch.m_conf);
namespace bp = boost::process;
bp::ipstream cmake_conf_out;
// clang-format off
auto cmake_config = bp::child{
m_cmake_path,
#if !BOOST_OS_WINDOWS
bp::env["CMAKE_GENERATOR"] = generator,
#endif
"-DSMCE_DIR=" + m_res_dir.string(),
"-DSKETCH_HEXID=" + sketch_hexid,
"-DSKETCH_FQBN=" + sketch.m_conf.fqbn,
"-DSKETCH_PATH=" + stdfs::absolute(sketch.m_source).generic_string(),
std::move(libs.pp_remote_arg),
"-P",
m_res_dir.string() + "/RtResources/SMCE/share/CMake/Scripts/ConfigureSketch.cmake",
(bp::std_out & bp::std_err) > cmake_conf_out
#if BOOST_OS_WINDOWS
, bp::windows::create_no_window
#endif
};
// clang-format on
{
std::string line;
while (std::getline(cmake_conf_out, line)) {
if (line.starts_with("-- SMCE: ")) {
line.erase(0, line.find_first_of('"') + 1);
line.pop_back();
sketch.m_executable = std::move(line);
break;
}
[[maybe_unused]] std::lock_guard lk{m_build_log_mtx};
(m_build_log += line) += '\n';
}
}
cmake_config.join();
if (cmake_config.native_exit_code() != 0)
return toolchain_error::configure_failed;
return {};
}
std::error_code Toolchain::do_build(Sketch& sketch) noexcept {
bp::ipstream cmake_build_out;
// clang-format off
auto cmake_build = bp::child{
#if BOOST_OS_WINDOWS
bp::env["MSBUILDDISABLENODEREUSE"] = "1", // MSBuild "feature" which uses your child processes as potential deamons, forever
#endif
m_cmake_path,
"--build", (sketch.m_tmpdir / "build").string(),
"--config", "Release",
(bp::std_out & bp::std_err) > cmake_build_out
#if BOOST_OS_WINDOWS
, bp::windows::create_no_window
#endif
};
// clang-format on
for (std::string line; std::getline(cmake_build_out, line);) {
[[maybe_unused]] std::lock_guard lk{m_build_log_mtx};
(m_build_log += line) += '\n';
}
cmake_build.join();
if (cmake_build.native_exit_code() != 0)
return toolchain_error::build_failed;
std::error_code ec;
const bool binary_exists = stdfs::exists(sketch.m_executable, ec);
if (ec)
return ec;
if (!binary_exists)
return toolchain_error::build_failed;
return {};
}
[[nodiscard]] std::error_code Toolchain::check_suitable_environment() noexcept {
if (std::error_code ec; !stdfs::exists(m_res_dir, ec))
return toolchain_error::resdir_absent;
else if (ec)
return ec;
if (std::error_code ec; !stdfs::is_directory(m_res_dir, ec))
return toolchain_error::resdir_file;
else if (ec)
return ec;
if (std::error_code ec; stdfs::is_empty(m_res_dir, ec))
return toolchain_error::resdir_empty;
else if (ec)
return ec;
if (m_cmake_path != "cmake") {
if (std::error_code ec; stdfs::is_empty(m_cmake_path, ec))
return toolchain_error::cmake_not_found;
else if (ec)
return ec;
} else {
m_cmake_path = bp::search_path(m_cmake_path).string();
if (m_cmake_path.empty())
return toolchain_error::cmake_not_found;
}
bp::ipstream cmake_out;
// clang-format off
const int cmres = bp::system(
m_cmake_path,
"--version",
bp::std_out > cmake_out
#if BOOST_OS_WINDOWS
, bp::windows::create_no_window
#endif
);
// clang-format on
if (cmres != 0)
return toolchain_error::cmake_failing;
std::string line;
std::getline(cmake_out, line);
if (!line.starts_with("cmake"))
return toolchain_error::cmake_unknown_output;
return {};
}
std::error_code Toolchain::compile(Sketch& sketch) noexcept {
sketch.m_built = false;
std::error_code ec;
const bool source_exists = stdfs::exists(sketch.m_source, ec);
if (ec)
return ec;
if (!source_exists)
return toolchain_error::sketch_invalid;
if (sketch.m_conf.fqbn.empty())
return toolchain_error::sketch_invalid;
ec = do_configure(sketch);
if (ec)
return ec;
ec = do_build(sketch);
if (ec)
return ec;
sketch.m_built = true;
return {};
}
} // namespace smce
|
#ifndef GEAROENIX_DX11_SHADER_DEPTH_POSITION_HPP
#define GEAROENIX_DX11_SHADER_DEPTH_POSITION_HPP
#include "../../core/gx-cr-build-configuration.hpp"
#ifdef GX_USE_DIRECTX11
#include "../../render/material/gx-rnd-mat-depth.hpp"
#include "dx11-shader.hpp"
namespace gearoenix {
namespace dx11 {
namespace buffer {
class Uniform;
}
namespace pipeline {
class Pipeline;
}
namespace shader {
class Depth : public Shader {
public:
class Resources : public render::material::Depth::Resources {
public:
Resources(Engine* e, pipeline::Pipeline* pip, buffer::Uniform* u);
void bind();
};
protected:
public:
Depth(core::Id my_id, Engine* eng, core::sync::EndCaller<core::sync::EndCallerIgnore> end);
~Depth();
void use();
const std::vector<render::shader::stage::Id>& get_stages_ids() const;
};
}
}
}
#endif
#endif
|
//
// Created by Zach Lee on 2021/9/25.
//
#include <RHI/Vulkan/VulkanDriver.h>
#include <RHI/Vulkan/VulkanShader.h>
#include <RHI/Vulkan/VulkanAdapater.h>
namespace Explosion::RHI {
VulkanShader::VulkanShader(VulkanDriver& driver, Config config)
: Shader(config), driver(driver), device(*driver.GetDevice()), shaderModule(VK_NULL_HANDLE)
{
CreateShader();
}
VulkanShader::~VulkanShader()
{
DestroyShader();
}
const VkShaderModule& VulkanShader::GetShaderModule() const
{
return shaderModule;
}
VkShaderStageFlagBits VulkanShader::GetShaderStage() const
{
return VkConvert<ShaderStageBits, VkShaderStageFlagBits>(config.stage);
}
void VulkanShader::CreateShader()
{
VkShaderModuleCreateInfo createInfo {};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.codeSize = config.data.size();
createInfo.pCode = reinterpret_cast<const uint32_t*>(config.data.data());
if (vkCreateShaderModule(device.GetVkDevice(), &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
throw std::runtime_error("failed to create vulkan shader module");
}
}
void VulkanShader::DestroyShader()
{
vkDestroyShaderModule(device.GetVkDevice(), shaderModule, nullptr);
}
}
|
//===- lib/Linker/IRMover.cpp ---------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker/IRMover.h"
#include "LinkDiagnosticInfo.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/GVMaterializer.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/Support/Error.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <utility>
using namespace llvm;
//===----------------------------------------------------------------------===//
// TypeMap implementation.
//===----------------------------------------------------------------------===//
namespace {
class TypeMapTy : public ValueMapTypeRemapper {
/// This is a mapping from a source type to a destination type to use.
DenseMap<Type *, Type *> MappedTypes;
/// When checking to see if two subgraphs are isomorphic, we speculatively
/// add types to MappedTypes, but keep track of them here in case we need to
/// roll back.
SmallVector<Type *, 16> SpeculativeTypes;
SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
/// This is a list of non-opaque structs in the source module that are mapped
/// to an opaque struct in the destination module.
SmallVector<StructType *, 16> SrcDefinitionsToResolve;
/// This is the set of opaque types in the destination modules who are
/// getting a body from the source module.
SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
public:
TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
: DstStructTypesSet(DstStructTypesSet) {}
IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
/// Indicate that the specified type in the destination module is conceptually
/// equivalent to the specified type in the source module.
void addTypeMapping(Type *DstTy, Type *SrcTy);
/// Produce a body for an opaque type in the dest module from a type
/// definition in the source module.
void linkDefinedTypeBodies();
/// Return the mapped type to use for the specified input type from the
/// source module.
Type *get(Type *SrcTy);
Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
FunctionType *get(FunctionType *T) {
return cast<FunctionType>(get((Type *)T));
}
private:
Type *remapType(Type *SrcTy) override { return get(SrcTy); }
bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
};
}
void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
assert(SpeculativeTypes.empty());
assert(SpeculativeDstOpaqueTypes.empty());
// Check to see if these types are recursively isomorphic and establish a
// mapping between them if so.
if (!areTypesIsomorphic(DstTy, SrcTy)) {
// Oops, they aren't isomorphic. Just discard this request by rolling out
// any speculative mappings we've established.
for (Type *Ty : SpeculativeTypes)
MappedTypes.erase(Ty);
SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
SpeculativeDstOpaqueTypes.size());
for (StructType *Ty : SpeculativeDstOpaqueTypes)
DstResolvedOpaqueTypes.erase(Ty);
} else {
for (Type *Ty : SpeculativeTypes)
if (auto *STy = dyn_cast<StructType>(Ty))
if (STy->hasName())
STy->setName("");
}
SpeculativeTypes.clear();
SpeculativeDstOpaqueTypes.clear();
}
/// Recursively walk this pair of types, returning true if they are isomorphic,
/// false if they are not.
bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
// Two types with differing kinds are clearly not isomorphic.
if (DstTy->getTypeID() != SrcTy->getTypeID())
return false;
// If we have an entry in the MappedTypes table, then we have our answer.
Type *&Entry = MappedTypes[SrcTy];
if (Entry)
return Entry == DstTy;
// Two identical types are clearly isomorphic. Remember this
// non-speculatively.
if (DstTy == SrcTy) {
Entry = DstTy;
return true;
}
// Okay, we have two types with identical kinds that we haven't seen before.
// If this is an opaque struct type, special case it.
if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
// Mapping an opaque type to any struct, just keep the dest struct.
if (SSTy->isOpaque()) {
Entry = DstTy;
SpeculativeTypes.push_back(SrcTy);
return true;
}
// Mapping a non-opaque source type to an opaque dest. If this is the first
// type that we're mapping onto this destination type then we succeed. Keep
// the dest, but fill it in later. If this is the second (different) type
// that we're trying to map onto the same opaque type then we fail.
if (cast<StructType>(DstTy)->isOpaque()) {
// We can only map one source type onto the opaque destination type.
if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
return false;
SrcDefinitionsToResolve.push_back(SSTy);
SpeculativeTypes.push_back(SrcTy);
SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Entry = DstTy;
return true;
}
}
// If the number of subtypes disagree between the two types, then we fail.
if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
return false;
// Fail if any of the extra properties (e.g. array size) of the type disagree.
if (isa<IntegerType>(DstTy))
return false; // bitwidth disagrees.
if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
return false;
} else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
return false;
} else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
StructType *SSTy = cast<StructType>(SrcTy);
if (DSTy->isLiteral() != SSTy->isLiteral() ||
DSTy->isPacked() != SSTy->isPacked())
return false;
} else if (auto *DSeqTy = dyn_cast<SequentialType>(DstTy)) {
if (DSeqTy->getNumElements() !=
cast<SequentialType>(SrcTy)->getNumElements())
return false;
}
// Otherwise, we speculate that these two types will line up and recursively
// check the subelements.
Entry = DstTy;
SpeculativeTypes.push_back(SrcTy);
for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
if (!areTypesIsomorphic(DstTy->getContainedType(I),
SrcTy->getContainedType(I)))
return false;
// If everything seems to have lined up, then everything is great.
return true;
}
void TypeMapTy::linkDefinedTypeBodies() {
SmallVector<Type *, 16> Elements;
for (StructType *SrcSTy : SrcDefinitionsToResolve) {
StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
assert(DstSTy->isOpaque());
// Map the body of the source type over to a new body for the dest type.
Elements.resize(SrcSTy->getNumElements());
for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Elements[I] = get(SrcSTy->getElementType(I));
DstSTy->setBody(Elements, SrcSTy->isPacked());
DstStructTypesSet.switchToNonOpaque(DstSTy);
}
SrcDefinitionsToResolve.clear();
DstResolvedOpaqueTypes.clear();
}
void TypeMapTy::finishType(StructType *DTy, StructType *STy,
ArrayRef<Type *> ETypes) {
DTy->setBody(ETypes, STy->isPacked());
// Steal STy's name.
if (STy->hasName()) {
SmallString<16> TmpName = STy->getName();
STy->setName("");
DTy->setName(TmpName);
}
DstStructTypesSet.addNonOpaque(DTy);
}
Type *TypeMapTy::get(Type *Ty) {
SmallPtrSet<StructType *, 8> Visited;
return get(Ty, Visited);
}
Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
// If we already have an entry for this type, return it.
Type **Entry = &MappedTypes[Ty];
if (*Entry)
return *Entry;
// These are types that LLVM itself will unique.
bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
#ifndef NDEBUG
if (!IsUniqued) {
for (auto &Pair : MappedTypes) {
assert(!(Pair.first != Ty && Pair.second == Ty) &&
"mapping to a source type");
}
}
#endif
if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
StructType *DTy = StructType::create(Ty->getContext());
return *Entry = DTy;
}
// If this is not a recursive type, then just map all of the elements and
// then rebuild the type from inside out.
SmallVector<Type *, 4> ElementTypes;
// If there are no element types to map, then the type is itself. This is
// true for the anonymous {} struct, things like 'float', integers, etc.
if (Ty->getNumContainedTypes() == 0 && IsUniqued)
return *Entry = Ty;
// Remap all of the elements, keeping track of whether any of them change.
bool AnyChange = false;
ElementTypes.resize(Ty->getNumContainedTypes());
for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
ElementTypes[I] = get(Ty->getContainedType(I), Visited);
AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
}
// If we found our type while recursively processing stuff, just use it.
Entry = &MappedTypes[Ty];
if (*Entry) {
if (auto *DTy = dyn_cast<StructType>(*Entry)) {
if (DTy->isOpaque()) {
auto *STy = cast<StructType>(Ty);
finishType(DTy, STy, ElementTypes);
}
}
return *Entry;
}
// If all of the element types mapped directly over and the type is not
// a named struct, then the type is usable as-is.
if (!AnyChange && IsUniqued)
return *Entry = Ty;
// Otherwise, rebuild a modified type.
switch (Ty->getTypeID()) {
default:
llvm_unreachable("unknown derived type to remap");
case Type::ArrayTyID:
return *Entry = ArrayType::get(ElementTypes[0],
cast<ArrayType>(Ty)->getNumElements());
case Type::VectorTyID:
return *Entry = VectorType::get(ElementTypes[0],
cast<VectorType>(Ty)->getNumElements());
case Type::PointerTyID:
return *Entry = PointerType::get(ElementTypes[0],
cast<PointerType>(Ty)->getAddressSpace());
case Type::FunctionTyID:
return *Entry = FunctionType::get(ElementTypes[0],
makeArrayRef(ElementTypes).slice(1),
cast<FunctionType>(Ty)->isVarArg());
case Type::StructTyID: {
auto *STy = cast<StructType>(Ty);
bool IsPacked = STy->isPacked();
if (IsUniqued)
return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
// If the type is opaque, we can just use it directly.
if (STy->isOpaque()) {
DstStructTypesSet.addOpaque(STy);
return *Entry = Ty;
}
if (StructType *OldT =
DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
STy->setName("");
return *Entry = OldT;
}
if (!AnyChange) {
DstStructTypesSet.addNonOpaque(STy);
return *Entry = Ty;
}
StructType *DTy = StructType::create(Ty->getContext());
finishType(DTy, STy, ElementTypes);
return *Entry = DTy;
}
}
}
LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
const Twine &Msg)
: DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
//===----------------------------------------------------------------------===//
// IRLinker implementation.
//===----------------------------------------------------------------------===//
namespace {
class IRLinker;
/// Creates prototypes for functions that are lazily linked on the fly. This
/// speeds up linking for modules with many/ lazily linked functions of which
/// few get used.
class GlobalValueMaterializer final : public ValueMaterializer {
IRLinker &TheIRLinker;
public:
GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Value *materialize(Value *V) override;
};
class LocalValueMaterializer final : public ValueMaterializer {
IRLinker &TheIRLinker;
public:
LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Value *materialize(Value *V) override;
};
/// Type of the Metadata map in \a ValueToValueMapTy.
typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
/// This is responsible for keeping track of the state used for moving data
/// from SrcM to DstM.
class IRLinker {
Module &DstM;
std::unique_ptr<Module> SrcM;
/// See IRMover::move().
std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
TypeMapTy TypeMap;
GlobalValueMaterializer GValMaterializer;
LocalValueMaterializer LValMaterializer;
/// A metadata map that's shared between IRLinker instances.
MDMapT &SharedMDs;
/// Mapping of values from what they used to be in Src, to what they are now
/// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
/// due to the use of Value handles which the Linker doesn't actually need,
/// but this allows us to reuse the ValueMapper code.
ValueToValueMapTy ValueMap;
ValueToValueMapTy AliasValueMap;
DenseSet<GlobalValue *> ValuesToLink;
std::vector<GlobalValue *> Worklist;
void maybeAdd(GlobalValue *GV) {
if (ValuesToLink.insert(GV).second)
Worklist.push_back(GV);
}
/// Whether we are importing globals for ThinLTO, as opposed to linking the
/// source module. If this flag is set, it means that we can rely on some
/// other object file to define any non-GlobalValue entities defined by the
/// source module. This currently causes us to not link retained types in
/// debug info metadata and module inline asm.
bool IsPerformingImport;
/// Set to true when all global value body linking is complete (including
/// lazy linking). Used to prevent metadata linking from creating new
/// references.
bool DoneLinkingBodies = false;
/// The Error encountered during materialization. We use an Optional here to
/// avoid needing to manage an unconsumed success value.
Optional<Error> FoundError;
void setError(Error E) {
if (E)
FoundError = std::move(E);
}
/// Most of the errors produced by this module are inconvertible StringErrors.
/// This convenience function lets us return one of those more easily.
Error stringErr(const Twine &T) {
return make_error<StringError>(T, inconvertibleErrorCode());
}
/// Entry point for mapping values and alternate context for mapping aliases.
ValueMapper Mapper;
unsigned AliasMCID;
/// Handles cloning of a global values from the source module into
/// the destination module, including setting the attributes and visibility.
GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
void emitWarning(const Twine &Message) {
SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
}
/// Given a global in the source module, return the global in the
/// destination module that is being linked to, if any.
GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
// If the source has no name it can't link. If it has local linkage,
// there is no name match-up going on.
if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
return nullptr;
// Otherwise see if we have a match in the destination module's symtab.
GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
if (!DGV)
return nullptr;
// If we found a global with the same name in the dest module, but it has
// internal linkage, we are really not doing any linkage here.
if (DGV->hasLocalLinkage())
return nullptr;
// Otherwise, we do in fact link to the destination global.
return DGV;
}
void computeTypeMapping();
Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
const GlobalVariable *SrcGV);
/// Given the GlobaValue \p SGV in the source module, and the matching
/// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
/// into the destination module.
///
/// Note this code may call the client-provided \p AddLazyFor.
bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
Error linkModuleFlagsMetadata();
void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
Error linkFunctionBody(Function &Dst, Function &Src);
void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
/// Functions that take care of cloning a specific global value type
/// into the destination module.
GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
Function *copyFunctionProto(const Function *SF);
GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
/// When importing for ThinLTO, prevent importing of types listed on
/// the DICompileUnit that we don't need a copy of in the importing
/// module.
void prepareCompileUnitsForImport();
void linkNamedMDNodes();
public:
IRLinker(Module &DstM, MDMapT &SharedMDs,
IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
ArrayRef<GlobalValue *> ValuesToLink,
std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
bool IsPerformingImport)
: DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
&GValMaterializer),
AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
&LValMaterializer)) {
ValueMap.getMDMap() = std::move(SharedMDs);
for (GlobalValue *GV : ValuesToLink)
maybeAdd(GV);
if (IsPerformingImport)
prepareCompileUnitsForImport();
}
~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Error run();
Value *materialize(Value *V, bool ForAlias);
};
}
/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
/// table. This is good for all clients except for us. Go through the trouble
/// to force this back.
static void forceRenaming(GlobalValue *GV, StringRef Name) {
// If the global doesn't force its name or if it already has the right name,
// there is nothing for us to do.
if (GV->hasLocalLinkage() || GV->getName() == Name)
return;
Module *M = GV->getParent();
// If there is a conflict, rename the conflict.
if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
GV->takeName(ConflictGV);
ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
} else {
GV->setName(Name); // Force the name back
}
}
Value *GlobalValueMaterializer::materialize(Value *SGV) {
return TheIRLinker.materialize(SGV, false);
}
Value *LocalValueMaterializer::materialize(Value *SGV) {
return TheIRLinker.materialize(SGV, true);
}
Value *IRLinker::materialize(Value *V, bool ForAlias) {
auto *SGV = dyn_cast<GlobalValue>(V);
if (!SGV)
return nullptr;
Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
if (!NewProto) {
setError(NewProto.takeError());
return nullptr;
}
if (!*NewProto)
return nullptr;
GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
if (!New)
return *NewProto;
// If we already created the body, just return.
if (auto *F = dyn_cast<Function>(New)) {
if (!F->isDeclaration())
return New;
} else if (auto *V = dyn_cast<GlobalVariable>(New)) {
if (V->hasInitializer() || V->hasAppendingLinkage())
return New;
} else {
auto *A = cast<GlobalAlias>(New);
if (A->getAliasee())
return New;
}
// When linking a global for an alias, it will always be linked. However we
// need to check if it was not already scheduled to satisfy a reference from a
// regular global value initializer. We know if it has been schedule if the
// "New" GlobalValue that is mapped here for the alias is the same as the one
// already mapped. If there is an entry in the ValueMap but the value is
// different, it means that the value already had a definition in the
// destination module (linkonce for instance), but we need a new definition
// for the alias ("New" will be different.
if (ForAlias && ValueMap.lookup(SGV) == New)
return New;
if (ForAlias || shouldLink(New, *SGV))
setError(linkGlobalValueBody(*New, *SGV));
return New;
}
/// Loop through the global variables in the src module and merge them into the
/// dest module.
GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
// No linking to be performed or linking from the source: simply create an
// identical version of the symbol over in the dest module... the
// initializer will be filled in later by LinkGlobalInits.
GlobalVariable *NewDGV =
new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
SGVar->isConstant(), GlobalValue::ExternalLinkage,
/*init*/ nullptr, SGVar->getName(),
/*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
SGVar->getType()->getAddressSpace());
NewDGV->setAlignment(SGVar->getAlignment());
NewDGV->copyAttributesFrom(SGVar);
return NewDGV;
}
/// Link the function in the source module into the destination module if
/// needed, setting up mapping information.
Function *IRLinker::copyFunctionProto(const Function *SF) {
// If there is no linkage to be performed or we are linking from the source,
// bring SF over.
auto *F =
Function::Create(TypeMap.get(SF->getFunctionType()),
GlobalValue::ExternalLinkage, SF->getName(), &DstM);
F->copyAttributesFrom(SF);
return F;
}
/// Set up prototypes for any aliases that come over from the source module.
GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
// If there is no linkage to be performed or we're linking from the source,
// bring over SGA.
auto *Ty = TypeMap.get(SGA->getValueType());
auto *GA =
GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
GlobalValue::ExternalLinkage, SGA->getName(), &DstM);
GA->copyAttributesFrom(SGA);
return GA;
}
GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
bool ForDefinition) {
GlobalValue *NewGV;
if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
NewGV = copyGlobalVariableProto(SGVar);
} else if (auto *SF = dyn_cast<Function>(SGV)) {
NewGV = copyFunctionProto(SF);
} else {
if (ForDefinition)
NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
else if (SGV->getValueType()->isFunctionTy())
NewGV =
Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
GlobalValue::ExternalLinkage, SGV->getName(), &DstM);
else
NewGV = new GlobalVariable(
DstM, TypeMap.get(SGV->getValueType()),
/*isConstant*/ false, GlobalValue::ExternalLinkage,
/*init*/ nullptr, SGV->getName(),
/*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
SGV->getType()->getAddressSpace());
}
if (ForDefinition)
NewGV->setLinkage(SGV->getLinkage());
else if (SGV->hasExternalWeakLinkage())
NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
// Metadata for global variables and function declarations is copied eagerly.
if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
}
// Remove these copied constants in case this stays a declaration, since
// they point to the source module. If the def is linked the values will
// be mapped in during linkFunctionBody.
if (auto *NewF = dyn_cast<Function>(NewGV)) {
NewF->setPersonalityFn(nullptr);
NewF->setPrefixData(nullptr);
NewF->setPrologueData(nullptr);
}
return NewGV;
}
/// Loop over all of the linked values to compute type mappings. For example,
/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
/// types 'Foo' but one got renamed when the module was loaded into the same
/// LLVMContext.
void IRLinker::computeTypeMapping() {
for (GlobalValue &SGV : SrcM->globals()) {
GlobalValue *DGV = getLinkedToGlobal(&SGV);
if (!DGV)
continue;
if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
continue;
}
// Unify the element type of appending arrays.
ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
}
for (GlobalValue &SGV : *SrcM)
if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
for (GlobalValue &SGV : SrcM->aliases())
if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
// Incorporate types by name, scanning all the types in the source module.
// At this point, the destination module may have a type "%foo = { i32 }" for
// example. When the source module got loaded into the same LLVMContext, if
// it had the same type, it would have been renamed to "%foo.42 = { i32 }".
std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
for (StructType *ST : Types) {
if (!ST->hasName())
continue;
if (TypeMap.DstStructTypesSet.hasType(ST)) {
// This is actually a type from the destination module.
// getIdentifiedStructTypes() can have found it by walking debug info
// metadata nodes, some of which get linked by name when ODR Type Uniquing
// is enabled on the Context, from the source to the destination module.
continue;
}
// Check to see if there is a dot in the name followed by a digit.
size_t DotPos = ST->getName().rfind('.');
if (DotPos == 0 || DotPos == StringRef::npos ||
ST->getName().back() == '.' ||
!isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
continue;
// Check to see if the destination module has a struct with the prefix name.
StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
if (!DST)
continue;
// Don't use it if this actually came from the source module. They're in
// the same LLVMContext after all. Also don't use it unless the type is
// actually used in the destination module. This can happen in situations
// like this:
//
// Module A Module B
// -------- --------
// %Z = type { %A } %B = type { %C.1 }
// %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
// %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
// %C = type { i8* } %B.3 = type { %C.1 }
//
// When we link Module B with Module A, the '%B' in Module B is
// used. However, that would then use '%C.1'. But when we process '%C.1',
// we prefer to take the '%C' version. So we are then left with both
// '%C.1' and '%C' being used for the same types. This leads to some
// variables using one type and some using the other.
if (TypeMap.DstStructTypesSet.hasType(DST))
TypeMap.addTypeMapping(DST, ST);
}
// Now that we have discovered all of the type equivalences, get a body for
// any 'opaque' types in the dest module that are now resolved.
TypeMap.linkDefinedTypeBodies();
}
static void getArrayElements(const Constant *C,
SmallVectorImpl<Constant *> &Dest) {
unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
for (unsigned i = 0; i != NumElements; ++i)
Dest.push_back(C->getAggregateElement(i));
}
/// If there were any appending global variables, link them together now.
Expected<Constant *>
IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
const GlobalVariable *SrcGV) {
Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
->getElementType();
// FIXME: This upgrade is done during linking to support the C API. Once the
// old form is deprecated, we should move this upgrade to
// llvm::UpgradeGlobalVariable() and simplify the logic here and in
// Mapper::mapAppendingVariable() in ValueMapper.cpp.
StringRef Name = SrcGV->getName();
bool IsNewStructor = false;
bool IsOldStructor = false;
if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
if (cast<StructType>(EltTy)->getNumElements() == 3)
IsNewStructor = true;
else
IsOldStructor = true;
}
PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
if (IsOldStructor) {
auto &ST = *cast<StructType>(EltTy);
Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
EltTy = StructType::get(SrcGV->getContext(), Tys, false);
}
uint64_t DstNumElements = 0;
if (DstGV) {
ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
DstNumElements = DstTy->getNumElements();
if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
return stringErr(
"Linking globals named '" + SrcGV->getName() +
"': can only link appending global with another appending "
"global!");
// Check to see that they two arrays agree on type.
if (EltTy != DstTy->getElementType())
return stringErr("Appending variables with different element types!");
if (DstGV->isConstant() != SrcGV->isConstant())
return stringErr("Appending variables linked with different const'ness!");
if (DstGV->getAlignment() != SrcGV->getAlignment())
return stringErr(
"Appending variables with different alignment need to be linked!");
if (DstGV->getVisibility() != SrcGV->getVisibility())
return stringErr(
"Appending variables with different visibility need to be linked!");
if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
return stringErr(
"Appending variables with different unnamed_addr need to be linked!");
if (DstGV->getSection() != SrcGV->getSection())
return stringErr(
"Appending variables with different section name need to be linked!");
}
SmallVector<Constant *, 16> SrcElements;
getArrayElements(SrcGV->getInitializer(), SrcElements);
if (IsNewStructor) {
auto It = remove_if(SrcElements, [this](Constant *E) {
auto *Key =
dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
if (!Key)
return false;
GlobalValue *DGV = getLinkedToGlobal(Key);
return !shouldLink(DGV, *Key);
});
SrcElements.erase(It, SrcElements.end());
}
uint64_t NewSize = DstNumElements + SrcElements.size();
ArrayType *NewType = ArrayType::get(EltTy, NewSize);
// Create the new global variable.
GlobalVariable *NG = new GlobalVariable(
DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
/*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
SrcGV->getType()->getAddressSpace());
NG->copyAttributesFrom(SrcGV);
forceRenaming(NG, SrcGV->getName());
Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Mapper.scheduleMapAppendingVariable(*NG,
DstGV ? DstGV->getInitializer() : nullptr,
IsOldStructor, SrcElements);
// Replace any uses of the two global variables with uses of the new
// global.
if (DstGV) {
DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
DstGV->eraseFromParent();
}
return Ret;
}
bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
return true;
if (DGV && !DGV->isDeclarationForLinker())
return false;
if (SGV.isDeclaration() || DoneLinkingBodies)
return false;
// Callback to the client to give a chance to lazily add the Global to the
// list of value to link.
bool LazilyAdded = false;
AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
maybeAdd(&GV);
LazilyAdded = true;
});
return LazilyAdded;
}
Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
bool ForAlias) {
GlobalValue *DGV = getLinkedToGlobal(SGV);
bool ShouldLink = shouldLink(DGV, *SGV);
// just missing from map
if (ShouldLink) {
auto I = ValueMap.find(SGV);
if (I != ValueMap.end())
return cast<Constant>(I->second);
I = AliasValueMap.find(SGV);
if (I != AliasValueMap.end())
return cast<Constant>(I->second);
}
if (!ShouldLink && ForAlias)
DGV = nullptr;
// Handle the ultra special appending linkage case first.
assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
if (SGV->hasAppendingLinkage())
return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
cast<GlobalVariable>(SGV));
GlobalValue *NewGV;
if (DGV && !ShouldLink) {
NewGV = DGV;
} else {
// If we are done linking global value bodies (i.e. we are performing
// metadata linking), don't link in the global value due to this
// reference, simply map it to null.
if (DoneLinkingBodies)
return nullptr;
NewGV = copyGlobalValueProto(SGV, ShouldLink);
if (ShouldLink || !ForAlias)
forceRenaming(NewGV, SGV->getName());
}
// Overloaded intrinsics have overloaded types names as part of their
// names. If we renamed overloaded types we should rename the intrinsic
// as well.
if (Function *F = dyn_cast<Function>(NewGV))
if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F))
NewGV = Remangled.getValue();
if (ShouldLink || ForAlias) {
if (const Comdat *SC = SGV->getComdat()) {
if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
Comdat *DC = DstM.getOrInsertComdat(SC->getName());
DC->setSelectionKind(SC->getSelectionKind());
GO->setComdat(DC);
}
}
}
if (!ShouldLink && ForAlias)
NewGV->setLinkage(GlobalValue::InternalLinkage);
Constant *C = NewGV;
// Only create a bitcast if necessary. In particular, with
// DebugTypeODRUniquing we may reach metadata in the destination module
// containing a GV from the source module, in which case SGV will be
// the same as DGV and NewGV, and TypeMap.get() will assert since it
// assumes it is being invoked on a type in the source module.
if (DGV && NewGV != SGV)
C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
if (DGV && NewGV != DGV) {
DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
DGV->eraseFromParent();
}
return C;
}
/// Update the initializers in the Dest module now that all globals that may be
/// referenced are in Dest.
void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
// Figure out what the initializer looks like in the dest module.
Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
}
/// Copy the source function over into the dest function and fix up references
/// to values. At this point we know that Dest is an external function, and
/// that Src is not.
Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
assert(Dst.isDeclaration() && !Src.isDeclaration());
// Materialize if needed.
if (Error Err = Src.materialize())
return Err;
// Link in the operands without remapping.
if (Src.hasPrefixData())
Dst.setPrefixData(Src.getPrefixData());
if (Src.hasPrologueData())
Dst.setPrologueData(Src.getPrologueData());
if (Src.hasPersonalityFn())
Dst.setPersonalityFn(Src.getPersonalityFn());
// Copy over the metadata attachments without remapping.
Dst.copyMetadata(&Src, 0);
// Steal arguments and splice the body of Src into Dst.
Dst.stealArgumentListFrom(Src);
Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
// Everything has been moved over. Remap it.
Mapper.scheduleRemapFunction(Dst);
return Error::success();
}
void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
}
Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
if (auto *F = dyn_cast<Function>(&Src))
return linkFunctionBody(cast<Function>(Dst), *F);
if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
return Error::success();
}
linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
return Error::success();
}
void IRLinker::prepareCompileUnitsForImport() {
NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
if (!SrcCompileUnits)
return;
// When importing for ThinLTO, prevent importing of types listed on
// the DICompileUnit that we don't need a copy of in the importing
// module. They will be emitted by the originating module.
for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) {
auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I));
assert(CU && "Expected valid compile unit");
// Enums, macros, and retained types don't need to be listed on the
// imported DICompileUnit. This means they will only be imported
// if reached from the mapped IR. Do this by setting their value map
// entries to nullptr, which will automatically prevent their importing
// when reached from the DICompileUnit during metadata mapping.
ValueMap.MD()[CU->getRawEnumTypes()].reset(nullptr);
ValueMap.MD()[CU->getRawMacros()].reset(nullptr);
ValueMap.MD()[CU->getRawRetainedTypes()].reset(nullptr);
// If we ever start importing global variable defs, we'll need to
// add their DIGlobalVariable to the globals list on the imported
// DICompileUnit. Confirm none are imported, and then we can
// map the list of global variables to nullptr.
assert(none_of(
ValuesToLink,
[](const GlobalValue *GV) { return isa<GlobalVariable>(GV); }) &&
"Unexpected importing of a GlobalVariable definition");
ValueMap.MD()[CU->getRawGlobalVariables()].reset(nullptr);
// Imported entities only need to be mapped in if they have local
// scope, as those might correspond to an imported entity inside a
// function being imported (any locally scoped imported entities that
// don't end up referenced by an imported function will not be emitted
// into the object). Imported entities not in a local scope
// (e.g. on the namespace) only need to be emitted by the originating
// module. Create a list of the locally scoped imported entities, and
// replace the source CUs imported entity list with the new list, so
// only those are mapped in.
// FIXME: Locally-scoped imported entities could be moved to the
// functions they are local to instead of listing them on the CU, and
// we would naturally only link in those needed by function importing.
SmallVector<TrackingMDNodeRef, 4> AllImportedModules;
bool ReplaceImportedEntities = false;
for (auto *IE : CU->getImportedEntities()) {
DIScope *Scope = IE->getScope();
assert(Scope && "Invalid Scope encoding!");
if (isa<DILocalScope>(Scope))
AllImportedModules.emplace_back(IE);
else
ReplaceImportedEntities = true;
}
if (ReplaceImportedEntities) {
if (!AllImportedModules.empty())
CU->replaceImportedEntities(MDTuple::get(
CU->getContext(),
SmallVector<Metadata *, 16>(AllImportedModules.begin(),
AllImportedModules.end())));
else
// If there were no local scope imported entities, we can map
// the whole list to nullptr.
ValueMap.MD()[CU->getRawImportedEntities()].reset(nullptr);
}
}
}
/// Insert all of the named MDNodes in Src into the Dest module.
void IRLinker::linkNamedMDNodes() {
const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
for (const NamedMDNode &NMD : SrcM->named_metadata()) {
// Don't link module flags here. Do them separately.
if (&NMD == SrcModFlags)
continue;
NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
// Add Src elements into Dest node.
for (const MDNode *Op : NMD.operands())
DestNMD->addOperand(Mapper.mapMDNode(*Op));
}
}
/// Merge the linker flags in Src into the Dest module.
Error IRLinker::linkModuleFlagsMetadata() {
// If the source module has no module flags, we are done.
const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
if (!SrcModFlags)
return Error::success();
// If the destination module doesn't have module flags yet, then just copy
// over the source module's flags.
NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
if (DstModFlags->getNumOperands() == 0) {
for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
DstModFlags->addOperand(SrcModFlags->getOperand(I));
return Error::success();
}
// First build a map of the existing module flags and requirements.
DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
SmallSetVector<MDNode *, 16> Requirements;
for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
MDNode *Op = DstModFlags->getOperand(I);
ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
MDString *ID = cast<MDString>(Op->getOperand(1));
if (Behavior->getZExtValue() == Module::Require) {
Requirements.insert(cast<MDNode>(Op->getOperand(2)));
} else {
Flags[ID] = std::make_pair(Op, I);
}
}
// Merge in the flags from the source module, and also collect its set of
// requirements.
for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
MDNode *SrcOp = SrcModFlags->getOperand(I);
ConstantInt *SrcBehavior =
mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
MDString *ID = cast<MDString>(SrcOp->getOperand(1));
MDNode *DstOp;
unsigned DstIndex;
std::tie(DstOp, DstIndex) = Flags.lookup(ID);
unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
// If this is a requirement, add it and continue.
if (SrcBehaviorValue == Module::Require) {
// If the destination module does not already have this requirement, add
// it.
if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
DstModFlags->addOperand(SrcOp);
}
continue;
}
// If there is no existing flag with this ID, just add it.
if (!DstOp) {
Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
DstModFlags->addOperand(SrcOp);
continue;
}
// Otherwise, perform a merge.
ConstantInt *DstBehavior =
mdconst::extract<ConstantInt>(DstOp->getOperand(0));
unsigned DstBehaviorValue = DstBehavior->getZExtValue();
auto overrideDstValue = [&]() {
DstModFlags->setOperand(DstIndex, SrcOp);
Flags[ID].first = SrcOp;
};
// If either flag has override behavior, handle it first.
if (DstBehaviorValue == Module::Override) {
// Diagnose inconsistent flags which both have override behavior.
if (SrcBehaviorValue == Module::Override &&
SrcOp->getOperand(2) != DstOp->getOperand(2))
return stringErr("linking module flags '" + ID->getString() +
"': IDs have conflicting override values");
continue;
} else if (SrcBehaviorValue == Module::Override) {
// Update the destination flag to that of the source.
overrideDstValue();
continue;
}
// Diagnose inconsistent merge behavior types.
if (SrcBehaviorValue != DstBehaviorValue)
return stringErr("linking module flags '" + ID->getString() +
"': IDs have conflicting behaviors");
auto replaceDstValue = [&](MDNode *New) {
Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
DstModFlags->setOperand(DstIndex, Flag);
Flags[ID].first = Flag;
};
// Perform the merge for standard behavior types.
switch (SrcBehaviorValue) {
case Module::Require:
case Module::Override:
llvm_unreachable("not possible");
case Module::Error: {
// Emit an error if the values differ.
if (SrcOp->getOperand(2) != DstOp->getOperand(2))
return stringErr("linking module flags '" + ID->getString() +
"': IDs have conflicting values");
continue;
}
case Module::Warning: {
// Emit a warning if the values differ.
if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
emitWarning("linking module flags '" + ID->getString() +
"': IDs have conflicting values");
}
continue;
}
case Module::Max: {
ConstantInt *DstValue =
mdconst::extract<ConstantInt>(DstOp->getOperand(2));
ConstantInt *SrcValue =
mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
if (SrcValue->getZExtValue() > DstValue->getZExtValue())
overrideDstValue();
break;
}
case Module::Append: {
MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
SmallVector<Metadata *, 8> MDs;
MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
MDs.append(DstValue->op_begin(), DstValue->op_end());
MDs.append(SrcValue->op_begin(), SrcValue->op_end());
replaceDstValue(MDNode::get(DstM.getContext(), MDs));
break;
}
case Module::AppendUnique: {
SmallSetVector<Metadata *, 16> Elts;
MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Elts.insert(DstValue->op_begin(), DstValue->op_end());
Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
replaceDstValue(MDNode::get(DstM.getContext(),
makeArrayRef(Elts.begin(), Elts.end())));
break;
}
}
}
// Check all of the requirements.
for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
MDNode *Requirement = Requirements[I];
MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Metadata *ReqValue = Requirement->getOperand(1);
MDNode *Op = Flags[Flag].first;
if (!Op || Op->getOperand(2) != ReqValue)
return stringErr("linking module flags '" + Flag->getString() +
"': does not have the required value");
}
return Error::success();
}
/// Return InlineAsm adjusted with target-specific directives if required.
/// For ARM and Thumb, we have to add directives to select the appropriate ISA
/// to support mixing module-level inline assembly from ARM and Thumb modules.
static std::string adjustInlineAsm(const std::string &InlineAsm,
const Triple &Triple) {
if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
return ".text\n.balign 2\n.thumb\n" + InlineAsm;
if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
return ".text\n.balign 4\n.arm\n" + InlineAsm;
return InlineAsm;
}
Error IRLinker::run() {
// Ensure metadata materialized before value mapping.
if (SrcM->getMaterializer())
if (Error Err = SrcM->getMaterializer()->materializeMetadata())
return Err;
// Inherit the target data from the source module if the destination module
// doesn't have one already.
if (DstM.getDataLayout().isDefault())
DstM.setDataLayout(SrcM->getDataLayout());
if (SrcM->getDataLayout() != DstM.getDataLayout()) {
emitWarning("Linking two modules of different data layouts: '" +
SrcM->getModuleIdentifier() + "' is '" +
SrcM->getDataLayoutStr() + "' whereas '" +
DstM.getModuleIdentifier() + "' is '" +
DstM.getDataLayoutStr() + "'\n");
}
// Copy the target triple from the source to dest if the dest's is empty.
if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
DstM.setTargetTriple(SrcM->getTargetTriple());
Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
if (!SrcM->getTargetTriple().empty()&&
!SrcTriple.isCompatibleWith(DstTriple))
emitWarning("Linking two modules of different target triples: " +
SrcM->getModuleIdentifier() + "' is '" +
SrcM->getTargetTriple() + "' whereas '" +
DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
"'\n");
DstM.setTargetTriple(SrcTriple.merge(DstTriple));
// Append the module inline asm string.
if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
std::string SrcModuleInlineAsm = adjustInlineAsm(SrcM->getModuleInlineAsm(),
SrcTriple);
if (DstM.getModuleInlineAsm().empty())
DstM.setModuleInlineAsm(SrcModuleInlineAsm);
else
DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
SrcModuleInlineAsm);
}
// Loop over all of the linked values to compute type mappings.
computeTypeMapping();
std::reverse(Worklist.begin(), Worklist.end());
while (!Worklist.empty()) {
GlobalValue *GV = Worklist.back();
Worklist.pop_back();
// Already mapped.
if (ValueMap.find(GV) != ValueMap.end() ||
AliasValueMap.find(GV) != AliasValueMap.end())
continue;
assert(!GV->isDeclaration());
Mapper.mapValue(*GV);
if (FoundError)
return std::move(*FoundError);
}
// Note that we are done linking global value bodies. This prevents
// metadata linking from creating new references.
DoneLinkingBodies = true;
Mapper.addFlags(RF_NullMapMissingGlobalValues);
// Remap all of the named MDNodes in Src into the DstM module. We do this
// after linking GlobalValues so that MDNodes that reference GlobalValues
// are properly remapped.
linkNamedMDNodes();
// Merge the module flags into the DstM module.
return linkModuleFlagsMetadata();
}
IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
: ETypes(E), IsPacked(P) {}
IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
: ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
return IsPacked == That.IsPacked && ETypes == That.ETypes;
}
bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
return !this->operator==(That);
}
StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
return DenseMapInfo<StructType *>::getEmptyKey();
}
StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
return DenseMapInfo<StructType *>::getTombstoneKey();
}
unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
Key.IsPacked);
}
unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
return getHashValue(KeyTy(ST));
}
bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
const StructType *RHS) {
if (RHS == getEmptyKey() || RHS == getTombstoneKey())
return false;
return LHS == KeyTy(RHS);
}
bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
const StructType *RHS) {
if (RHS == getEmptyKey() || RHS == getTombstoneKey())
return LHS == RHS;
return KeyTy(LHS) == KeyTy(RHS);
}
void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
assert(!Ty->isOpaque());
NonOpaqueStructTypes.insert(Ty);
}
void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
assert(!Ty->isOpaque());
NonOpaqueStructTypes.insert(Ty);
bool Removed = OpaqueStructTypes.erase(Ty);
(void)Removed;
assert(Removed);
}
void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
assert(Ty->isOpaque());
OpaqueStructTypes.insert(Ty);
}
StructType *
IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
bool IsPacked) {
IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
auto I = NonOpaqueStructTypes.find_as(Key);
return I == NonOpaqueStructTypes.end() ? nullptr : *I;
}
bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
if (Ty->isOpaque())
return OpaqueStructTypes.count(Ty);
auto I = NonOpaqueStructTypes.find(Ty);
return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
}
IRMover::IRMover(Module &M) : Composite(M) {
TypeFinder StructTypes;
StructTypes.run(M, /* OnlyNamed */ false);
for (StructType *Ty : StructTypes) {
if (Ty->isOpaque())
IdentifiedStructTypes.addOpaque(Ty);
else
IdentifiedStructTypes.addNonOpaque(Ty);
}
// Self-map metadatas in the destination module. This is needed when
// DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
// destination module may be reached from the source module.
for (auto *MD : StructTypes.getVisitedMetadata()) {
SharedMDs[MD].reset(const_cast<MDNode *>(MD));
}
}
Error IRMover::move(
std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
bool IsPerformingImport) {
IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
std::move(Src), ValuesToLink, std::move(AddLazyFor),
IsPerformingImport);
Error E = TheIRLinker.run();
Composite.dropTriviallyDeadConstantArrays();
return E;
}
|
#include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define EPS 1e-6
#define ll long long int
#define ld long double
#define fi first
#define se second
#define all(v) v.begin(),v.end()
#define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<"INF " : cout<<v[i]<<" "; } cout<<endl;}
#define t1(x) cerr<<#x<<" : "<<x<<endl
#define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl
#define t3(x, y, z) cerr<<#x<<" : " <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl
#define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl
#define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl
#define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__)
#define _ cerr<<"here"<<endl;
#define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);}
using namespace std;
template<class A, class B> ostream& operator<<(ostream& out, const pair<A, B> &a){ return out<<"("<<a.first<<", "<<a.second<<")";}
template <int> ostream& operator<<(ostream& os, const vector<int>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { if(v[i]!=INF) os << v[i]; else os << "INF";if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; }
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; ;if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; }
void countSort(vector<int> &ansPos, vector<int> currEquivPos)
{
int n = ansPos.size();
vector<int> ansNew(n);
vector<int> counter(n);
vector<int> index(n);
for(auto it : currEquivPos) counter[it]++;
int cumIndex = 0;
for(int i=1;i<n;i++) index[i] = index[i-1] + counter[i-1];
for(int i=0;i<n;i++)
{
int value = currEquivPos[ansPos[i]];
ansNew[index[value]] = ansPos[i];
index[value]++;
}
ansPos = ansNew;
}
void suffixArray(string &s, vector<int> &ansPos)
{
s += '$';
int n = s.size();
ansPos.resize(n);
vector<int> currEquivPos(n);
// Sort the length 1 elements
{
vector<pair<char,int> > tempSort;
for(int i=0;i<n;i++) tempSort.pu(mp(s[i],i));
sort(tempSort.begin(),tempSort.end());
for(int i=0;i<n;i++) ansPos[i] = tempSort[i].se;
int equivCls = -1;
char prevEquivCls = 0;
for(int i=0;i<n;i++)
{
equivCls = (prevEquivCls == tempSort[i].fi) ? equivCls : equivCls+1;
prevEquivCls = tempSort[i].fi;
currEquivPos[ansPos[i]] = equivCls;
}
}
int k = 0;
while((1<<k) < n)
{
int sortLen = (1<<k);
for(int i=0;i<n;i++) ansPos[i] = (ansPos[i] - sortLen + n) %n;
countSort(ansPos,currEquivPos);
int equivCls = -1;
pair<int,int> prevEquivCls = mp(-1,-1);
vector<int> currEquivPosNew(n);
for(int i=0;i<n;i++)
{
pair<int,int> currEquivCls = mp(currEquivPos[ansPos[i]],currEquivPos[(ansPos[i]+sortLen)%n]);
equivCls = (prevEquivCls == currEquivCls) ? equivCls : equivCls+1;
prevEquivCls = currEquivCls;
currEquivPosNew[ansPos[i]] = equivCls;
}
currEquivPos = currEquivPosNew;
k++;
}
}
void lcpArray(vector<int> &suffixArray,string &s,vector<int> &lcp)
{
int n = suffixArray.size();
vector<int> inv(n);
for(int i=0;i<n;i++) inv[suffixArray[i]] = i;
lcp.resize(n);
int prevMatch = 0;
for(int i=0;i<n-1;i++)
{
if(inv[i] == n-1) continue;
int strIndex1 = i;
int strIndex2 = suffixArray[inv[i]+1];
prevMatch = max(prevMatch-1,0);
while(s[strIndex1+prevMatch] == s[strIndex2+prevMatch]) // Breaks when encounters $. Don't worry about index errors
{
prevMatch++;
}
lcp[inv[i]] = prevMatch;
}
}
typedef struct SparseTable
{
static const int MAXN = 2e5+10;
static const int K = 20;
vector<vector<int> > st;
vector<int> log;
SparseTable(vector<int> &v)
{
st.resize(MAXN,vector<int>(K+1));
log.resize(MAXN);
initMin(v);
}
void init(vector<int> &v)
{
for (int i = 0; i < v.size(); i++)
st[i][0] = v[i];
for (int j = 1; j <= K; j++)
for (int i = 0; i + (1 << j) <= v.size(); i++)
st[i][j] = min(st[i][j-1],st[i + (1 << (j - 1))][j - 1]);
}
void initMin(vector<int> &v)
{
init(v);
log[1] = 0;
for (int i = 2; i <= MAXN; i++)
log[i] = log[i/2] + 1;
}
ll min(ll x, ll y) {return (x<y) ? x : y;}
int queryMin(int l, int r)
{
int j = log[r - l + 1];
int minimum = min(st[l][j], st[r - (1 << j) + 1][j]);
return minimum;
}
} Sparse;
ll max(ll x, ll y) {return (x>y) ? x : y;}
pair<ll,int> check(ll mid,Sparse &sp,int n)
{
int prev = -1;
ll max1 = -1;
int maxIndex = -1;
for(int i=0;i<=n;i++)
{
if(sp.queryMin(i,i) >= mid)
{
prev = (prev == -1) ? i : prev;
ll temp_max = (i-prev+2)*mid;
if(temp_max > max1)
{
max1 = temp_max;
maxIndex = prev;
}
}
else prev = -1;
}
return mp(max1,maxIndex);
}
int main()
{
__;
int n,k;
cin >> n >> k;
string s;
for(int i=0;i<n;i++)
{
char a;
cin >> a;
a--;
s += a;
}
vector<int> suffix,lcp;
suffixArray(s,suffix);
lcpArray(suffix,s,lcp);
Sparse sp(lcp);
int ansIndex = -1, ansLen = -1;
ll ans = -1;
for(int mid=1;mid<=n;mid++)
{
pair<ll,int> tempAns = check(mid,sp,n);
t(mid,tempAns,tempAns.fi/mid);
if(tempAns.fi > ans)
{
ans = tempAns.fi;
ansLen = mid;
ansIndex = tempAns.se;
}
}
// int beg = 1, end = n;
// while(beg <= end)
// {
// int mid = (beg+end) >> 1;
// pair<ll,int> leftAns = (mid==1) ? (pair<ll,int>) mp(0,0) : check(mid-1,sp,n);
// pair<ll,int> midAns = check(mid,sp,n);
// pair<ll,int> rightAns = (mid == n) ? (pair<ll,int>) mp(n,0) : check(mid+1,sp,n);
// // t(mid,leftAns,midAns,rightAns);
// if(midAns.fi >= leftAns.fi && midAns.fi >= rightAns.fi)
// {
// ans = midAns.fi;
// ansIndex = midAns.se;
// ansLen = mid;
// break;
// }
// else if(leftAns.fi <= midAns.fi && midAns.fi <= rightAns.fi) beg = mid+1;
// else end = mid-1;
// }
if(n == max(ans,n))
{
cout << n << endl;
cout << n << endl;
for(int i=0;i<n;i++) cout << (char)(s[i]+1) << " "; cout << endl;
}
else
{
ansIndex = suffix[ansIndex];
cout << ans << endl;
cout << ansLen << endl;
for(int i=ansIndex;i<ansIndex+ansLen;i++) cout << (char)(s[i]+1) << " "; cout << endl;
}
return 0;
}
// lcp(inv[i],inv[i+k])
// lcp (i,i+k) = 2k or > 2k
|
/**
* Copyright (c) 2018, University Osnabrück
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University Osnabrück 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 University Osnabrück 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 "lvr2/reconstruction/PanoramaNormals.hpp"
#include "lvr2/geometry/BaseVector.hpp"
#include "lvr2/geometry/Normal.hpp"
#include "lvr2/io/Progress.hpp"
#include "lvr2/io/Timestamp.hpp"
#include <Eigen/Dense>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
using std::cout;
using std::endl;
namespace lvr2
{
using Vec = BaseVector<float>;
PanoramaNormals::PanoramaNormals(ModelToImage* mti)
: m_mti(mti)
{
m_buffer = mti->pointBuffer();
}
PointBufferPtr PanoramaNormals::computeNormals(int width, int height, bool interpolate)
{
// Create new point buffer and tmp storages
PointBufferPtr out_buffer(new PointBuffer);
vector<float> pts;
vector<float> normals;
// Get input buffer's points
PointBufferPtr in_buffer = m_mti->pointBuffer();
size_t w_color;
size_t n_inPoints = in_buffer->numPoints();
floatArr in_points = in_buffer->getPointArray();
ucharArr in_colors = in_buffer->getColorArray(w_color);
// Reserve memory for output buffers (we need a deep copy)
floatArr p_arr(new float[n_inPoints * 3]);
floatArr n_arr(new float[n_inPoints * 3]);
ucharArr c_arr;
if(in_buffer->hasColors())
{
c_arr = ucharArr(new unsigned char[n_inPoints * 3]);
}
// Get panorama
ModelToImage::DepthListMatrix mat;
m_mti->computeDepthListMatrix(mat);
// If the desired neighborhood is larger than 2 x 2 pixels
// compute offsets for i und j dimension of the image.
int di = 2;
if(width > 2)
{
di = width / 2;
}
int dj = 2;
if(height > 2)
{
dj = height / 2;
}
// Compute normals
// Create progress output
string comment = timestamp.getElapsedTime() + "Computing normals ";
ProgressBar progress(mat.pixels.size(), comment);
for(size_t i = 0; i < mat.pixels.size(); i++)
{
#pragma omp parallel for
for(size_t j = 0; j < mat.pixels[i].size(); j++)
{
// Check if image entry is empty
if(mat.pixels[i][j].size() == 0)
{
continue;
}
// Collect 'neighboring' points
vector<ModelToImage::PanoramaPoint> nb;
// The points at the current position are part of the neighborhood
std::copy(mat.pixels[i][j].begin(), mat.pixels[i][j].end(), std::back_inserter(nb));
for(int off_i = -di; off_i <= di; off_i++)
{
for(int off_j = -dj; off_j <= dj; off_j++)
{
int p_i = i + off_i;
int p_j = j + off_j;
if(p_i >= 0 && p_i < mat.pixels.size() &&
p_j >= 0 && p_j < mat.pixels[i].size())
{
// We only save the first point as representative
// because using all points from list will likely
// result in undesirable configurations for local
// normal estimation
if(mat.pixels[p_i][p_j].size() > 0)
{
nb.push_back(mat.pixels[p_i][p_j][0]);
}
}
}
}
// Compute normal if more than three neighbors where found
if(nb.size() > 3)
{
// Compute mean
Vec mean;
for(int i = 0; i < nb.size(); i++)
{
// Determine position of geometry in point array
size_t index = nb[i].index * 3;
// Get point coordinates
Vec neighbor(in_points[index],
in_points[index + 1],
in_points[index + 2]);
// Add to mean
mean.x += neighbor.x;
mean.y += neighbor.y;
mean.z += neighbor.z;
}
mean.x /= nb.size();
mean.y /= nb.size();
mean.z /= nb.size();
// Calculate covariance
double covariance[9] = {0};
for(int i = 0; i < nb.size(); i++)
{
size_t index = nb[i].index * 3;
Vec pt(in_points[index ] - mean.x,
in_points[index + 1] - mean.y,
in_points[index + 3] - mean.z);
covariance[4] += pt.y * pt.y;
covariance[7] += pt.y * pt.z;
covariance[8] += pt.z * pt.z;
pt.x *= pt.x;
pt.y *= pt.x;
pt.z *= pt.x;
covariance[0] += pt.x;
covariance[1] += pt.y;
covariance[6] += pt.z;
}
covariance[3] = covariance[1];
covariance[2] = covariance[6];
covariance[5] = covariance[7];
for(int i = 0; i < 9; i++)
{
covariance[i] /= nb.size();
}
// Compute eigenvalues and eigenvectors using GSL
gsl_matrix_view m = gsl_matrix_view_array(covariance, 3, 3);
gsl_matrix* evec = gsl_matrix_alloc(3, 3);
gsl_vector* eval = gsl_vector_alloc(3);
gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3);
gsl_eigen_symmv (&m.matrix, eval, evec, w);
gsl_eigen_symmv_free (w);
gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC);
gsl_vector_view evec_0 = gsl_matrix_column(evec, 0);
float nx = gsl_vector_get(&evec_0.vector, 0);
float ny = gsl_vector_get(&evec_0.vector, 1);
float nz = gsl_vector_get(&evec_0.vector, 2);
// Flip normals towards reference point
Normal<float> nn(nx, ny, nz);
Vec center(0, 0, 0);
size_t index = mat.pixels[i][j][0].index * 3;
Vec p1 = center - Vec(in_points[index], in_points[index + 1], in_points[index + 2]);
if(Normal<float>(p1) * nn < 0)
{
nx *= -1;
ny *= -1;
nz *= -1;
}
for(size_t k = 0; k < mat.pixels[i][j].size(); k++)
{
// Assign the same normal to all points
// behind this pixel to preserve the complete
// point cloud
size_t index = mat.pixels[i][j][k].index * 3;
size_t color_index = mat.pixels[i][j][k].index * w_color;
// Copy point and normal to target buffer
p_arr[index ] = in_points[index];
p_arr[index + 1] = in_points[index + 1];
p_arr[index + 2] = in_points[index + 2];
if(in_buffer->hasColors())
{
c_arr[index ] = in_colors[color_index];
c_arr[index + 1] = in_colors[color_index + 1];
c_arr[index + 2] = in_colors[color_index + 2];
}
if(!interpolate)
{
n_arr[index ] = nx;
n_arr[index + 1] = ny;
n_arr[index + 2] = nz;
}
}
}
}
++progress;
}
cout << endl;
// if(interpolate)
// {
// cout << timestamp << " Interpolating normals" << endl;
// for(size_t i = 0; i < mat.pixels.size(); i++)
// {
// for(size_t j = 0; j < mat.pixels[i].size(); j++)
// {
// float x = 0.0f;
// float y = 0.0f;
// float z = 0.0f;
// int np = 0;
// for(int off_i = -di; off_i <= di; off_i++)
// {
// for(int off_j = -dj; off_j <= dj; off_j++)
// {
// int p_i = i + off_i;
// int p_j = j + off_j;
// if(p_i >= 0 && p_i < mat.pixels.size() &&
// p_j >= 0 && p_j < mat.pixels[i].size())
// {
// for(size_t k = 0; k < mat.pixels[p_i][p_j].size(); k++)
// {
// size_t index = mat.pixels[p_i][p_j][k].index;
// x += in_points[index];
// y += in_points[index + 1];
// z += in_points[index + 2];
// np++;
// }
// }
// }
// }
// if(np > 3) // Same condition as above
// {
// x /= np;
// y /= np;
// z /= np;
// normals.push_back(x);
// normals.push_back(y);
// normals.push_back(z);
// }
// }
// }
// cout << normals.size() << " " << pts.size() << endl;
// }
cout << timestamp << "Finished normal estimation" << endl;
if(in_buffer->hasColors())
{
out_buffer->setColorArray(c_arr, n_inPoints);
}
out_buffer->setPointArray(p_arr, n_inPoints);
out_buffer->setNormalArray(n_arr, n_inPoints);
return out_buffer;
}
} // namespace lvr2
|
#pragma once
#include "solver.hpp"
#include "var.hpp"
extern "C" {
enum miplib_SolverBackend {
Gurobi = 0, Scip = 1, Lpsolve = 2, BestAtCompileTime = 3, BestAtRunTime = 4
};
enum class miplib_VarType {
Continuous = 0, Binary = 1, Integer = 2
};
char const* miplib_get_last_error();
int miplib_create_solver(miplib::Solver** rp_solver, miplib_SolverBackend backend);
int miplib_destroy_solver(miplib::Solver* p_solver);
int miplib_shallow_copy_solver(miplib::Solver** rp_solver, miplib::Solver* p_solver);
int miplib_create_var(miplib::Var** rp_var, miplib::Solver* p_solver, miplib_VarType type);
int miplib_destroy_var(miplib::Var* p_var);
int miplib_shallow_copy_var(miplib::Var** rp_var, miplib::Var* p_var);
}
|
#pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function XpBoostInfoText.XpBoostInfoText_C.Update Available Boosts
struct UXpBoostInfoText_C_Update_Available_Boosts_Params
{
};
// Function XpBoostInfoText.XpBoostInfoText_C.Construct
struct UXpBoostInfoText_C_Construct_Params
{
};
// Function XpBoostInfoText.XpBoostInfoText_C.HandleAccountUpdate
struct UXpBoostInfoText_C_HandleAccountUpdate_Params
{
struct FFortPublicAccountInfo NewInfo; // (Parm)
};
// Function XpBoostInfoText.XpBoostInfoText_C.Xp Boost Changed
struct UXpBoostInfoText_C_Xp_Boost_Changed_Params
{
int BoostAmount; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function XpBoostInfoText.XpBoostInfoText_C.ExecuteUbergraph_XpBoostInfoText
struct UXpBoostInfoText_C_ExecuteUbergraph_XpBoostInfoText_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
/*! @file
@brief 文字コードセット設定ダイアログボックス
@author Uchi
@date 2010/6/14 新規作成
*/
/*
Copyright (C) 2010, Uchi
Copyright (C) 2018-2021, Sakura Editor Organization
This source code is designed for sakura editor.
Please contact the copyright holder to use this code for other purpose.
*/
#include "StdAfx.h"
#include "dlg/CDlgSetCharSet.h"
#include "func/Funccode.h"
#include "util/shell.h"
#include "env/DLLSHAREDATA.h"
#include "charset/CCodePage.h"
#include "sakura_rc.h"
#include "sakura.hh"
//文字コードセット設定 CDlgSetCharSet
const DWORD p_helpids[] = {
IDOK, HIDOK_GREP, //検索
IDCANCEL, HIDCANCEL_GREP, //キャンセル
IDC_BUTTON_HELP, HIDC_GREP_BUTTON_HELP, //ヘルプ
IDC_COMBO_CHARSET, HIDC_OPENDLG_COMBO_CODE, //文字コードセット
IDC_CHECK_BOM, HIDC_OPENDLG_CHECK_BOM, //条件
IDC_CHECK_CP, HIDC_OPENDLG_CHECK_CP, //CP
0, 0
};
CDlgSetCharSet::CDlgSetCharSet()
{
m_pnCharSet = NULL; // 文字コードセット
m_pbBom = NULL; // 文字コードセット
}
/* モーダルダイアログの表示 */
int CDlgSetCharSet::DoModal( HINSTANCE hInstance, HWND hwndParent, ECodeType* pnCharSet, bool* pbBom)
{
m_pnCharSet = pnCharSet; // 文字コードセット
m_pbBom = pbBom; // BOM
return (int)CDialog::DoModal( hInstance, hwndParent, IDD_SETCHARSET, (LPARAM)NULL );
}
BOOL CDlgSetCharSet::OnInitDialog( HWND hwndDlg, WPARAM wParam, LPARAM lParam )
{
_SetHwnd( hwndDlg );
m_hwndCharSet = GetItemHwnd( IDC_COMBO_CHARSET ); // 文字コードセットコンボボックス
m_hwndCheckBOM = GetItemHwnd( IDC_CHECK_BOM ); // BOMチェックボックス
// コンボボックスのユーザー インターフェイスを拡張インターフェースにする
Combo_SetExtendedUI( m_hwndCharSet, TRUE );
// 文字コードセット選択コンボボックス初期化
int i;
CCodeTypesForCombobox cCodeTypes;
Combo_ResetContent( m_hwndCharSet );
for (i = 1; i < cCodeTypes.GetCount(); ++i) {
int idx = Combo_AddString( m_hwndCharSet, cCodeTypes.GetName(i) );
Combo_SetItemData( m_hwndCharSet, idx, cCodeTypes.GetCode(i) );
}
/* 基底クラスメンバ */
return CDialog::OnInitDialog( hwndDlg, wParam, lParam );
}
BOOL CDlgSetCharSet::OnBnClicked( int wID )
{
switch( wID ){
case IDC_CHECK_CP:
::CheckDlgButton( GetHwnd(), IDC_CHECK_CP, TRUE );
::EnableWindow( GetItemHwnd( IDC_CHECK_CP ), FALSE );
CCodePage::AddComboCodePages( GetHwnd(), m_hwndCharSet, -1 );
return TRUE;
case IDC_BUTTON_HELP:
/* 「文字コードセット設定」のヘルプ */
MyWinHelp( GetHwnd(), HELP_CONTEXT, ::FuncID_To_HelpContextID(F_CHG_CHARSET) );
return TRUE;
case IDOK:
/* ダイアログデータの取得 */
if( GetData() ){
CloseDialog( TRUE );
}
return TRUE;
case IDCANCEL:
CloseDialog( FALSE );
return TRUE;
}
/* 基底クラスメンバ */
return CDialog::OnBnClicked( wID );
}
// BOM の設定
void CDlgSetCharSet::SetBOM( void )
{
int nIdx;
LRESULT lRes;
int fCheck;
nIdx = Combo_GetCurSel( m_hwndCharSet );
lRes = Combo_GetItemData( m_hwndCharSet, nIdx );
CCodeTypeName cCodeTypeName( lRes );
if (cCodeTypeName.UseBom()) {
::EnableWindow( m_hwndCheckBOM, TRUE );
if (lRes == *m_pnCharSet) {
fCheck = *m_pbBom ? BST_CHECKED : BST_UNCHECKED;
}
else{
fCheck = cCodeTypeName.IsBomDefOn() ? BST_CHECKED : BST_UNCHECKED;
}
}
else {
::EnableWindow( m_hwndCheckBOM, FALSE );
fCheck = BST_UNCHECKED;
}
BtnCtl_SetCheck( m_hwndCheckBOM, fCheck );
}
// 文字コード選択時の処理
BOOL CDlgSetCharSet::OnCbnSelChange( HWND hwndCtl, int wID )
{
int nIdx;
LRESULT lRes;
int fCheck;
switch (wID) {
// 文字コードの変更をBOMチェックボックスに反映
case IDC_COMBO_CHARSET:
SetBOM();
nIdx = Combo_GetCurSel( hwndCtl );
lRes = Combo_GetItemData( hwndCtl, nIdx );
CCodeTypeName cCodeTypeName( lRes );
if (cCodeTypeName.UseBom()) {
::EnableWindow( m_hwndCheckBOM, TRUE );
if (lRes == *m_pnCharSet) {
fCheck = *m_pbBom ? BST_CHECKED : BST_UNCHECKED;
}
else{
fCheck = cCodeTypeName.IsBomDefOn() ? BST_CHECKED : BST_UNCHECKED;
}
}
else {
::EnableWindow( m_hwndCheckBOM, FALSE );
fCheck = BST_UNCHECKED;
}
BtnCtl_SetCheck( m_hwndCheckBOM, fCheck );
break;
}
return TRUE;
}
LPVOID CDlgSetCharSet::GetHelpIdTable(void)
{
return (LPVOID)p_helpids;
}
/* ダイアログデータの設定 */
void CDlgSetCharSet::SetData( void )
{
// 文字コードセット
int nIdx, nCurIdx, nIdxOld;
ECodeType nCharSet;
CCodeTypesForCombobox cCodeTypes;
nIdxOld = Combo_GetCurSel( m_hwndCharSet );
nCurIdx = -1;
for (nIdx = 0; nIdx < Combo_GetCount( m_hwndCharSet ); nIdx++) {
nCharSet = (ECodeType)Combo_GetItemData( m_hwndCharSet, nIdx );
if (nCharSet == *m_pnCharSet) {
nCurIdx = nIdx;
}
}
if( -1 == nCurIdx ){
::CheckDlgButton( GetHwnd(), IDC_CHECK_CP, TRUE );
::EnableWindow( GetItemHwnd( IDC_CHECK_CP ), FALSE );
nCurIdx = CCodePage::AddComboCodePages( GetHwnd(), m_hwndCharSet, *m_pnCharSet );
if( nCurIdx == -1 ){
nCurIdx = nIdxOld;
}
}
Combo_SetCurSel( m_hwndCharSet, nCurIdx );
// BOMを設定
SetBOM();
}
/* ダイアログデータの取得 */
/* TRUE==正常 FALSE==入力エラー */
int CDlgSetCharSet::GetData( void )
{
// 文字コードセット
int nIdx;
nIdx = Combo_GetCurSel( m_hwndCharSet );
*m_pnCharSet = (ECodeType)Combo_GetItemData( m_hwndCharSet, nIdx );
// BOM
*m_pbBom = ( BtnCtl_GetCheck( m_hwndCheckBOM ) == BST_CHECKED );
return TRUE;
}
|
/*
* Vulkan Example - Model loading and rendering
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <vector>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include <vulkan/vulkan.h>
#include "vulkanexamplebase.h"
#include "VulkanTexture.hpp"
#define VERTEX_BUFFER_BIND_ID 0
#define ENABLE_VALIDATION false
class VulkanExample : public VulkanExampleBase
{
public:
bool wireframe = false;
struct {
vks::Texture2D colorMap;
} textures;
struct {
VkPipelineVertexInputStateCreateInfo inputState;
std::vector<VkVertexInputBindingDescription> bindingDescriptions;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
} vertices;
// Vertex layout used in this example
// This must fit input locations of the vertex shader used to render the model
struct Vertex {
glm::vec3 pos;
glm::vec3 normal;
glm::vec2 uv;
glm::vec3 color;
};
// Contains all Vulkan resources required to represent vertex and index buffers for a model
// This is for demonstration and learning purposes, the other examples use a model loader class for easy access
struct Model {
struct {
VkBuffer buffer;
VkDeviceMemory memory;
} vertices;
struct {
int count;
VkBuffer buffer;
VkDeviceMemory memory;
} indices;
// Destroys all Vulkan resources created for this model
void destroy(VkDevice device)
{
vkDestroyBuffer(device, vertices.buffer, nullptr);
vkFreeMemory(device, vertices.memory, nullptr);
vkDestroyBuffer(device, indices.buffer, nullptr);
vkFreeMemory(device, indices.memory, nullptr);
};
} model;
struct {
vks::Buffer scene;
} uniformBuffers;
struct {
glm::mat4 projection;
glm::mat4 model;
glm::vec4 lightPos = glm::vec4(25.0f, 5.0f, 5.0f, 1.0f);
} uboVS;
struct {
VkPipeline solid;
VkPipeline wireframe;
} pipelines;
VkPipelineLayout pipelineLayout;
VkDescriptorSet descriptorSet;
VkDescriptorSetLayout descriptorSetLayout;
VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION)
{
zoom = -5.5f;
zoomSpeed = 2.5f;
rotationSpeed = 0.5f;
rotation = { -0.5f, -112.75f, 0.0f };
cameraPos = { 0.1f, 1.1f, 0.0f };
enableTextOverlay = true;
title = "Vulkan Example - Model rendering";
// Enable physical device features required for this example
enabledFeatures.fillModeNonSolid = VK_TRUE;
}
~VulkanExample()
{
// Clean up used Vulkan resources
// Note : Inherited destructor cleans up resources stored in base class
vkDestroyPipeline(device, pipelines.solid, nullptr);
vkDestroyPipeline(device, pipelines.wireframe, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
model.destroy(device);
textures.colorMap.destroy();
uniformBuffers.scene.destroy();
}
void reBuildCommandBuffers()
{
if (!checkCommandBuffers())
{
destroyCommandBuffers();
createCommandBuffers();
}
buildCommandBuffers();
}
void buildCommandBuffers()
{
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = defaultClearColor;
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = renderPass;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = width;
renderPassBeginInfo.renderArea.extent.height = height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
for (int32_t i = 0; i < drawCmdBuffers.size(); ++i)
{
// Set target frame buffer
renderPassBeginInfo.framebuffer = frameBuffers[i];
VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo));
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport);
VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0);
vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor);
vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, wireframe ? pipelines.wireframe : pipelines.solid);
VkDeviceSize offsets[1] = { 0 };
// Bind mesh vertex buffer
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &model.vertices.buffer, offsets);
// Bind mesh index buffer
vkCmdBindIndexBuffer(drawCmdBuffers[i], model.indices.buffer, 0, VK_INDEX_TYPE_UINT32);
// Render mesh vertex buffer using it's indices
vkCmdDrawIndexed(drawCmdBuffers[i], model.indices.count, 1, 0, 0, 0);
vkCmdEndRenderPass(drawCmdBuffers[i]);
VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i]));
}
}
// Load a model from file using the ASSIMP model loader and generate all resources required to render the model
void loadModel(std::string filename)
{
// Load the model from file using ASSIMP
const aiScene* scene;
Assimp::Importer Importer;
// Flags for loading the mesh
static const int assimpFlags = aiProcess_FlipWindingOrder | aiProcess_Triangulate | aiProcess_PreTransformVertices;
#if defined(__ANDROID__)
// Meshes are stored inside the apk on Android (compressed)
// So they need to be loaded via the asset manager
AAsset* asset = AAssetManager_open(androidApp->activity->assetManager, filename.c_str(), AASSET_MODE_STREAMING);
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
void *meshData = malloc(size);
AAsset_read(asset, meshData, size);
AAsset_close(asset);
scene = Importer.ReadFileFromMemory(meshData, size, assimpFlags);
free(meshData);
#else
scene = Importer.ReadFile(filename.c_str(), assimpFlags);
#endif
// Generate vertex buffer from ASSIMP scene data
float scale = 1.0f;
std::vector<Vertex> vertexBuffer;
// Iterate through all meshes in the file and extract the vertex components
for (uint32_t m = 0; m < scene->mNumMeshes; m++)
{
for (uint32_t v = 0; v < scene->mMeshes[m]->mNumVertices; v++)
{
Vertex vertex;
// Use glm make_* functions to convert ASSIMP vectors to glm vectors
vertex.pos = glm::make_vec3(&scene->mMeshes[m]->mVertices[v].x) * scale;
vertex.normal = glm::make_vec3(&scene->mMeshes[m]->mNormals[v].x);
// Texture coordinates and colors may have multiple channels, we only use the first [0] one
vertex.uv = glm::make_vec2(&scene->mMeshes[m]->mTextureCoords[0][v].x);
// Mesh may not have vertex colors
vertex.color = (scene->mMeshes[m]->HasVertexColors(0)) ? glm::make_vec3(&scene->mMeshes[m]->mColors[0][v].r) : glm::vec3(1.0f);
// Vulkan uses a right-handed NDC (contrary to OpenGL), so simply flip Y-Axis
vertex.pos.y *= -1.0f;
vertexBuffer.push_back(vertex);
}
}
size_t vertexBufferSize = vertexBuffer.size() * sizeof(Vertex);
// Generate index buffer from ASSIMP scene data
std::vector<uint32_t> indexBuffer;
for (uint32_t m = 0; m < scene->mNumMeshes; m++)
{
uint32_t indexBase = static_cast<uint32_t>(indexBuffer.size());
for (uint32_t f = 0; f < scene->mMeshes[m]->mNumFaces; f++)
{
// We assume that all faces are triangulated
for (uint32_t i = 0; i < 3; i++)
{
indexBuffer.push_back(scene->mMeshes[m]->mFaces[f].mIndices[i] + indexBase);
}
}
}
size_t indexBufferSize = indexBuffer.size() * sizeof(uint32_t);
model.indices.count = static_cast<uint32_t>(indexBuffer.size());
// Static mesh should always be device local
bool useStaging = true;
if (useStaging)
{
struct {
VkBuffer buffer;
VkDeviceMemory memory;
} vertexStaging, indexStaging;
// Create staging buffers
// Vertex data
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
vertexBufferSize,
&vertexStaging.buffer,
&vertexStaging.memory,
vertexBuffer.data()));
// Index data
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
indexBufferSize,
&indexStaging.buffer,
&indexStaging.memory,
indexBuffer.data()));
// Create device local buffers
// Vertex buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
vertexBufferSize,
&model.vertices.buffer,
&model.vertices.memory));
// Index buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
indexBufferSize,
&model.indices.buffer,
&model.indices.memory));
// Copy from staging buffers
VkCommandBuffer copyCmd = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
VkBufferCopy copyRegion = {};
copyRegion.size = vertexBufferSize;
vkCmdCopyBuffer(
copyCmd,
vertexStaging.buffer,
model.vertices.buffer,
1,
©Region);
copyRegion.size = indexBufferSize;
vkCmdCopyBuffer(
copyCmd,
indexStaging.buffer,
model.indices.buffer,
1,
©Region);
VulkanExampleBase::flushCommandBuffer(copyCmd, queue, true);
vkDestroyBuffer(device, vertexStaging.buffer, nullptr);
vkFreeMemory(device, vertexStaging.memory, nullptr);
vkDestroyBuffer(device, indexStaging.buffer, nullptr);
vkFreeMemory(device, indexStaging.memory, nullptr);
}
else
{
// Vertex buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
vertexBufferSize,
&model.vertices.buffer,
&model.vertices.memory,
vertexBuffer.data()));
// Index buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
indexBufferSize,
&model.indices.buffer,
&model.indices.memory,
indexBuffer.data()));
}
}
void loadAssets()
{
loadModel(getAssetPath() + "models/voyager/voyager.dae");
textures.colorMap.loadFromFile(getAssetPath() + "models/voyager/voyager.ktx", VK_FORMAT_BC3_UNORM_BLOCK, vulkanDevice, queue);
}
void setupVertexDescriptions()
{
// Binding description
vertices.bindingDescriptions.resize(1);
vertices.bindingDescriptions[0] =
vks::initializers::vertexInputBindingDescription(
VERTEX_BUFFER_BIND_ID,
sizeof(Vertex),
VK_VERTEX_INPUT_RATE_VERTEX);
// Attribute descriptions
// Describes memory layout and shader positions
vertices.attributeDescriptions.resize(4);
// Location 0 : Position
vertices.attributeDescriptions[0] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
0,
VK_FORMAT_R32G32B32_SFLOAT,
offsetof(Vertex, pos));
// Location 1 : Normal
vertices.attributeDescriptions[1] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
1,
VK_FORMAT_R32G32B32_SFLOAT,
offsetof(Vertex, normal));
// Location 2 : Texture coordinates
vertices.attributeDescriptions[2] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
2,
VK_FORMAT_R32G32_SFLOAT,
offsetof(Vertex, uv));
// Location 3 : Color
vertices.attributeDescriptions[3] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID,
3,
VK_FORMAT_R32G32B32_SFLOAT,
offsetof(Vertex, color));
vertices.inputState = vks::initializers::pipelineVertexInputStateCreateInfo();
vertices.inputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertices.bindingDescriptions.size());
vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data();
vertices.inputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertices.attributeDescriptions.size());
vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data();
}
void setupDescriptorPool()
{
// Example uses one ubo and one combined image sampler
std::vector<VkDescriptorPoolSize> poolSizes =
{
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1),
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1),
};
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vks::initializers::descriptorPoolCreateInfo(
static_cast<uint32_t>(poolSizes.size()),
poolSizes.data(),
1);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout()
{
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings =
{
// Binding 0 : Vertex shader uniform buffer
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT,
0),
// Binding 1 : Fragment shader combined sampler
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
1),
};
VkDescriptorSetLayoutCreateInfo descriptorLayout =
vks::initializers::descriptorSetLayoutCreateInfo(
setLayoutBindings.data(),
static_cast<uint32_t>(setLayoutBindings.size()));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo =
vks::initializers::pipelineLayoutCreateInfo(
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout));
}
void setupDescriptorSet()
{
VkDescriptorSetAllocateInfo allocInfo =
vks::initializers::descriptorSetAllocateInfo(
descriptorPool,
&descriptorSetLayout,
1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
VkDescriptorImageInfo texDescriptor =
vks::initializers::descriptorImageInfo(
textures.colorMap.sampler,
textures.colorMap.view,
VK_IMAGE_LAYOUT_GENERAL);
std::vector<VkWriteDescriptorSet> writeDescriptorSets =
{
// Binding 0 : Vertex shader uniform buffer
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0,
&uniformBuffers.scene.descriptor),
// Binding 1 : Color map
vks::initializers::writeDescriptorSet(
descriptorSet,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
&texDescriptor)
};
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL);
}
void preparePipelines()
{
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState =
vks::initializers::pipelineInputAssemblyStateCreateInfo(
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
0,
VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState =
vks::initializers::pipelineRasterizationStateCreateInfo(
VK_POLYGON_MODE_FILL,
VK_CULL_MODE_BACK_BIT,
VK_FRONT_FACE_CLOCKWISE,
0);
VkPipelineColorBlendAttachmentState blendAttachmentState =
vks::initializers::pipelineColorBlendAttachmentState(
0xf,
VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState =
vks::initializers::pipelineColorBlendStateCreateInfo(
1,
&blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState =
vks::initializers::pipelineDepthStencilStateCreateInfo(
VK_TRUE,
VK_TRUE,
VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState =
vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState =
vks::initializers::pipelineMultisampleStateCreateInfo(
VK_SAMPLE_COUNT_1_BIT,
0);
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
VkPipelineDynamicStateCreateInfo dynamicState =
vks::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
static_cast<uint32_t>(dynamicStateEnables.size()),
0);
// Solid rendering pipeline
// Load shaders
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
shaderStages[0] = loadShader(getAssetPath() + "shaders/mesh/mesh.vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(getAssetPath() + "shaders/mesh/mesh.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VkGraphicsPipelineCreateInfo pipelineCreateInfo =
vks::initializers::pipelineCreateInfo(
pipelineLayout,
renderPass,
0);
pipelineCreateInfo.pVertexInputState = &vertices.inputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data();
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.solid));
// Wire frame rendering pipeline
rasterizationState.polygonMode = VK_POLYGON_MODE_LINE;
rasterizationState.lineWidth = 1.0f;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.wireframe));
}
// Prepare and initialize uniform buffer containing shader uniforms
void prepareUniformBuffers()
{
// Vertex shader uniform buffer block
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffers.scene,
sizeof(uboVS)));
// Map persistent
VK_CHECK_RESULT(uniformBuffers.scene.map());
updateUniformBuffers();
}
void updateUniformBuffers()
{
uboVS.projection = glm::perspective(glm::radians(60.0f), (float)width / (float)height, 0.1f, 256.0f);
glm::mat4 viewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, 0.0f, zoom));
uboVS.model = viewMatrix * glm::translate(glm::mat4(), cameraPos);
uboVS.model = glm::rotate(uboVS.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
uboVS.model = glm::rotate(uboVS.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
uboVS.model = glm::rotate(uboVS.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
memcpy(uniformBuffers.scene.mapped, &uboVS, sizeof(uboVS));
}
void draw()
{
VulkanExampleBase::prepareFrame();
// Command buffer to be sumitted to the queue
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
// Submit to queue
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
void prepare()
{
VulkanExampleBase::prepare();
loadAssets();
setupVertexDescriptions();
prepareUniformBuffers();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
prepared = true;
}
virtual void render()
{
if (!prepared)
return;
draw();
}
virtual void viewChanged()
{
updateUniformBuffers();
}
virtual void keyPressed(uint32_t keyCode)
{
switch (keyCode)
{
case KEY_W:
case GAMEPAD_BUTTON_A:
wireframe = !wireframe;
reBuildCommandBuffers();
break;
}
}
virtual void getOverlayText(VulkanTextOverlay *textOverlay)
{
#if defined(__ANDROID__)
textOverlay->addText("Press \"Button A\" to toggle wireframe", 5.0f, 85.0f, VulkanTextOverlay::alignLeft);
#else
textOverlay->addText("Press \"w\" to toggle wireframe", 5.0f, 85.0f, VulkanTextOverlay::alignLeft);
#endif
}
};
VULKAN_EXAMPLE_MAIN()
|
// Copyright (c) Andreas Fertig.
// SPDX-License-Identifier: MIT
#include <cstdio>
#include <list>
#include <vector>
template<template<class, class> class Container,
class T,
class Allocator = std::allocator<T>>
void Fun(const Container<T, Allocator>& c)
{
for(const auto& e : c) { printf("%d\n", e); }
}
int main()
{
std::vector<int> v{2, 3, 4};
Fun(v);
std::list<char> l{'a', 'b', 'c'};
Fun(l);
}
|
// Adapted from https://stackoverflow.com/questions/34511312/how-to-encode-a-video-from-several-images-generated-in-a-c-program-without-wri
// (Later) adapted from https://github.com/apc-llc/moviemaker-cpp
#ifndef FRAME_WRITER
#define FRAME_WRITER
#include <stdint.h>
#include <string>
#include <vector>
#include <map>
#define AUDIO_RATE 44100
extern "C"
{
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
#include <libavcodec/avcodec.h>
#include <libavutil/mathematics.h>
#include <libavformat/avformat.h>
#include <libavutil/pixdesc.h>
#include <libavutil/hwcontext.h>
#include <libavutil/opt.h>
}
enum InputFormat
{
INPUT_FORMAT_BGR0,
INPUT_FORMAT_RGB0
};
struct FrameWriterParams
{
std::string file;
int width;
int height;
InputFormat format;
std::string codec;
std::string hw_device; // used only if codec contains vaapi
std::map<std::string, std::string> codec_options;
int64_t audio_sync_offset;
bool enable_audio;
bool enable_ffmpeg_debug_output;
};
class FrameWriter
{
FrameWriterParams params;
void load_codec_options(AVDictionary **dict);
SwsContext* swsCtx;
AVOutputFormat* outputFmt;
AVStream* videoStream;
AVCodecContext* videoCodecCtx;
AVFormatContext* fmtCtx;
AVBufferRef *hw_device_context = NULL;
AVBufferRef *hw_frame_context = NULL;
AVPixelFormat choose_sw_format(AVCodec *codec);
AVPixelFormat get_input_format();
void init_hw_accel();
void init_sws();
void init_codecs();
void init_video_stream();
AVFrame *encoder_frame = NULL;
AVFrame *hw_frame = NULL;
SwrContext *swrCtx;
AVStream *audioStream;
AVCodecContext *audioCodecCtx;
void init_swr();
void init_audio_stream();
void send_audio_pkt(AVFrame *frame);
void finish_frame(AVPacket& pkt, bool isVideo);
public :
FrameWriter(const FrameWriterParams& params);
void add_frame(const uint8_t* pixels, int64_t usec, bool y_invert);
/* Buffer must have size get_audio_buffer_size() */
void add_audio(const void* buffer);
size_t get_audio_buffer_size();
~FrameWriter();
};
#include <memory>
#include <mutex>
#include <atomic>
extern std::mutex frame_writer_mutex, frame_writer_pending_mutex;
extern std::unique_ptr<FrameWriter> frame_writer;
extern std::atomic<bool> exit_main_loop;
#endif // FRAME_WRITER
|
//========================================================================
//
// SplashScreen.cc
//
//========================================================================
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include <stdlib.h>
#include <string.h>
#if HAVE_STD_SORT
#include <algorithm>
#endif
#include "gmem.h"
#include "SplashMath.h"
#include "SplashScreen.h"
//------------------------------------------------------------------------
static SplashScreenParams defaultParams = {
splashScreenDispersed, // type
2, // size
2, // dotRadius
1.0, // gamma
0.0, // blackThreshold
1.0 // whiteThreshold
};
//------------------------------------------------------------------------
struct SplashScreenPoint {
int x, y;
int dist;
};
#if HAVE_STD_SORT
struct cmpDistancesFunctor {
bool operator()(const SplashScreenPoint &p0, const SplashScreenPoint &p1) {
return p0.dist < p1.dist;
}
};
#else // HAVE_STD_SORT
static int cmpDistances(const void *p0, const void *p1) {
return ((SplashScreenPoint *)p0)->dist - ((SplashScreenPoint *)p1)->dist;
}
#endif
//------------------------------------------------------------------------
// SplashScreen
//------------------------------------------------------------------------
// If <clustered> is true, this generates a 45 degree screen using a
// circular dot spot function. DPI = resolution / ((size / 2) *
// sqrt(2)). If <clustered> is false, this generates an optimal
// threshold matrix using recursive tesselation. Gamma correction
// (gamma = 1 / 1.33) is also computed here.
SplashScreen::SplashScreen(SplashScreenParams *params) {
Guchar u;
int black, white, i;
if (!params) {
params = &defaultParams;
}
// size must be a power of 2, and at least 2
for (size = 2, log2Size = 1; size < params->size; size <<= 1, ++log2Size) ;
switch (params->type) {
case splashScreenDispersed:
mat = (Guchar *)gmallocn(size * size, sizeof(Guchar));
buildDispersedMatrix(size/2, size/2, 1, size/2, 1);
break;
case splashScreenClustered:
mat = (Guchar *)gmallocn(size * size, sizeof(Guchar));
buildClusteredMatrix();
break;
case splashScreenStochasticClustered:
// size must be at least 2*r
while (size < (params->dotRadius << 1)) {
size <<= 1;
++log2Size;
}
mat = (Guchar *)gmallocn(size * size, sizeof(Guchar));
buildSCDMatrix(params->dotRadius);
break;
}
sizeM1 = size - 1;
// do gamma correction and compute minVal/maxVal
minVal = 255;
maxVal = 0;
black = splashRound((SplashCoord)255.0 * params->blackThreshold);
if (black < 1) {
black = 1;
}
white = splashRound((SplashCoord)255.0 * params->whiteThreshold);
if (white > 255) {
white = 255;
}
for (i = 0; i < size * size; ++i) {
u = splashRound((SplashCoord)255.0 *
splashPow((SplashCoord)mat[i] / 255.0, params->gamma));
if (u < black) {
u = (Guchar)black;
} else if (u >= white) {
u = (Guchar)white;
}
mat[i] = u;
if (u < minVal) {
minVal = u;
} else if (u > maxVal) {
maxVal = u;
}
}
}
void SplashScreen::buildDispersedMatrix(int i, int j, int val,
int delta, int offset) {
if (delta == 0) {
// map values in [1, size^2] --> [1, 255]
mat[(i << log2Size) + j] = 1 + (254 * (val - 1)) / (size * size - 1);
} else {
buildDispersedMatrix(i, j,
val, delta / 2, 4*offset);
buildDispersedMatrix((i + delta) % size, (j + delta) % size,
val + offset, delta / 2, 4*offset);
buildDispersedMatrix((i + delta) % size, j,
val + 2*offset, delta / 2, 4*offset);
buildDispersedMatrix((i + 2*delta) % size, (j + delta) % size,
val + 3*offset, delta / 2, 4*offset);
}
}
void SplashScreen::buildClusteredMatrix() {
SplashCoord *dist;
SplashCoord u, v, d;
Guchar val;
int size2, x, y, x1, y1, i;
size2 = size >> 1;
// initialize the threshold matrix
for (y = 0; y < size; ++y) {
for (x = 0; x < size; ++x) {
mat[(y << log2Size) + x] = 0;
}
}
// build the distance matrix
dist = (SplashCoord *)gmallocn(size * size2, sizeof(SplashCoord));
for (y = 0; y < size2; ++y) {
for (x = 0; x < size2; ++x) {
if (x + y < size2 - 1) {
u = (SplashCoord)x + 0.5 - 0;
v = (SplashCoord)y + 0.5 - 0;
} else {
u = (SplashCoord)x + 0.5 - (SplashCoord)size2;
v = (SplashCoord)y + 0.5 - (SplashCoord)size2;
}
dist[y * size2 + x] = u*u + v*v;
}
}
for (y = 0; y < size2; ++y) {
for (x = 0; x < size2; ++x) {
if (x < y) {
u = (SplashCoord)x + 0.5 - 0;
v = (SplashCoord)y + 0.5 - (SplashCoord)size2;
} else {
u = (SplashCoord)x + 0.5 - (SplashCoord)size2;
v = (SplashCoord)y + 0.5 - 0;
}
dist[(size2 + y) * size2 + x] = u*u + v*v;
}
}
// build the threshold matrix
x1 = y1 = 0; // make gcc happy
for (i = 0; i < size * size2; ++i) {
d = -1;
for (y = 0; y < size; ++y) {
for (x = 0; x < size2; ++x) {
if (mat[(y << log2Size) + x] == 0 &&
dist[y * size2 + x] > d) {
x1 = x;
y1 = y;
d = dist[y1 * size2 + x1];
}
}
}
// map values in [0, 2*size*size2-1] --> [1, 255]
val = 1 + (254 * (2*i)) / (2*size*size2 - 1);
mat[(y1 << log2Size) + x1] = val;
val = 1 + (254 * (2*i+1)) / (2*size*size2 - 1);
if (y1 < size2) {
mat[((y1 + size2) << log2Size) + x1 + size2] = val;
} else {
mat[((y1 - size2) << log2Size) + x1 + size2] = val;
}
}
gfree(dist);
}
// Compute the distance between two points on a toroid.
int SplashScreen::distance(int x0, int y0, int x1, int y1) {
int dx0, dx1, dx, dy0, dy1, dy;
dx0 = abs(x0 - x1);
dx1 = size - dx0;
dx = dx0 < dx1 ? dx0 : dx1;
dy0 = abs(y0 - y1);
dy1 = size - dy0;
dy = dy0 < dy1 ? dy0 : dy1;
return dx * dx + dy * dy;
}
// Algorithm taken from:
// Victor Ostromoukhov and Roger D. Hersch, "Stochastic Clustered-Dot
// Dithering" in Color Imaging: Device-Independent Color, Color
// Hardcopy, and Graphic Arts IV, SPIE Vol. 3648, pp. 496-505, 1999.
void SplashScreen::buildSCDMatrix(int r) {
SplashScreenPoint *dots, *pts;
int dotsLen, dotsSize;
char *tmpl;
char *grid;
int *region, *dist;
int x, y, xx, yy, x0, x1, y0, y1, i, j, d, iMin, dMin, n;
//~ this should probably happen somewhere else
srand(123);
// generate the random space-filling curve
pts = (SplashScreenPoint *)gmallocn(size * size, sizeof(SplashScreenPoint));
i = 0;
for (y = 0; y < size; ++y) {
for (x = 0; x < size; ++x) {
pts[i].x = x;
pts[i].y = y;
++i;
}
}
for (i = 0; i < size * size; ++i) {
j = i + (int)((double)(size * size - i) *
(double)rand() / ((double)RAND_MAX + 1.0));
x = pts[i].x;
y = pts[i].y;
pts[i].x = pts[j].x;
pts[i].y = pts[j].y;
pts[j].x = x;
pts[j].y = y;
}
// construct the circle template
tmpl = (char *)gmallocn((r+1)*(r+1), sizeof(char));
for (y = 0; y <= r; ++y) {
for (x = 0; x <= r; ++x) {
tmpl[y*(r+1) + x] = (x * y <= r * r) ? 1 : 0;
}
}
// mark all grid cells as free
grid = (char *)gmallocn(size * size, sizeof(char));
for (y = 0; y < size; ++y) {
for (x = 0; x < size; ++x) {
grid[(y << log2Size) + x] = 0;
}
}
// walk the space-filling curve, adding dots
dotsLen = 0;
dotsSize = 32;
dots = (SplashScreenPoint *)gmallocn(dotsSize, sizeof(SplashScreenPoint));
for (i = 0; i < size * size; ++i) {
x = pts[i].x;
y = pts[i].y;
if (!grid[(y << log2Size) + x]) {
if (dotsLen == dotsSize) {
dotsSize *= 2;
dots = (SplashScreenPoint *)greallocn(dots, dotsSize,
sizeof(SplashScreenPoint));
}
dots[dotsLen++] = pts[i];
for (yy = 0; yy <= r; ++yy) {
y0 = (y + yy) % size;
y1 = (y - yy + size) % size;
for (xx = 0; xx <= r; ++xx) {
if (tmpl[yy*(r+1) + xx]) {
x0 = (x + xx) % size;
x1 = (x - xx + size) % size;
grid[(y0 << log2Size) + x0] = 1;
grid[(y0 << log2Size) + x1] = 1;
grid[(y1 << log2Size) + x0] = 1;
grid[(y1 << log2Size) + x1] = 1;
}
}
}
}
}
gfree(tmpl);
gfree(grid);
// assign each cell to a dot, compute distance to center of dot
region = (int *)gmallocn(size * size, sizeof(int));
dist = (int *)gmallocn(size * size, sizeof(int));
for (y = 0; y < size; ++y) {
for (x = 0; x < size; ++x) {
iMin = 0;
dMin = distance(dots[0].x, dots[0].y, x, y);
for (i = 1; i < dotsLen; ++i) {
d = distance(dots[i].x, dots[i].y, x, y);
if (d < dMin) {
iMin = i;
dMin = d;
}
}
region[(y << log2Size) + x] = iMin;
dist[(y << log2Size) + x] = dMin;
}
}
// compute threshold values
for (i = 0; i < dotsLen; ++i) {
n = 0;
for (y = 0; y < size; ++y) {
for (x = 0; x < size; ++x) {
if (region[(y << log2Size) + x] == i) {
pts[n].x = x;
pts[n].y = y;
pts[n].dist = distance(dots[i].x, dots[i].y, x, y);
++n;
}
}
}
#if HAVE_STD_SORT
std::sort(pts, pts + n, cmpDistancesFunctor());
#else
qsort(pts, n, sizeof(SplashScreenPoint), &cmpDistances);
#endif
for (j = 0; j < n; ++j) {
// map values in [0 .. n-1] --> [255 .. 1]
mat[(pts[j].y << log2Size) + pts[j].x] = 255 - (254 * j) / (n - 1);
}
}
gfree(pts);
gfree(region);
gfree(dist);
gfree(dots);
}
SplashScreen::SplashScreen(SplashScreen *screen) {
size = screen->size;
sizeM1 = screen->sizeM1;
log2Size = screen->log2Size;
mat = (Guchar *)gmallocn(size * size, sizeof(Guchar));
memcpy(mat, screen->mat, size * size * sizeof(Guchar));
minVal = screen->minVal;
maxVal = screen->maxVal;
}
SplashScreen::~SplashScreen() {
gfree(mat);
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/infobars/core/infobar.h"
#include <cmath>
#include <utility>
#include "base/logging.h"
#include "build/build_config.h"
#include "components/infobars/core/infobar_container.h"
#include "components/infobars/core/infobar_manager.h"
#include "ui/base/material_design/material_design_controller.h"
#include "ui/gfx/animation/slide_animation.h"
namespace infobars {
InfoBar::InfoBar(std::unique_ptr<InfoBarDelegate> delegate)
: owner_(NULL),
delegate_(std::move(delegate)),
container_(NULL),
animation_(this),
arrow_height_(0),
arrow_target_height_(0),
arrow_half_width_(0),
bar_height_(0),
bar_target_height_(-1) {
DCHECK(delegate_ != NULL);
animation_.SetTweenType(gfx::Tween::LINEAR);
delegate_->set_infobar(this);
}
InfoBar::~InfoBar() {
DCHECK(!owner_);
}
// static
SkColor InfoBar::GetTopColor(InfoBarDelegate::Type infobar_type) {
if (ui::MaterialDesignController::IsModeMaterial()) {
static const SkColor kWarningBackgroundColorMd =
SkColorSetRGB(0xFF, 0xEC, 0xB3); // Yellow
static const SkColor kPageActionBackgroundColorMd = SK_ColorWHITE;
return infobar_type == InfoBarDelegate::WARNING_TYPE ?
kWarningBackgroundColorMd : kPageActionBackgroundColorMd;
}
static const SkColor kWarningBackgroundColorTop =
SkColorSetRGB(255, 242, 183); // Yellow
static const SkColor kPageActionBackgroundColorTop =
SkColorSetRGB(237, 237, 237); // Gray
return (infobar_type == InfoBarDelegate::WARNING_TYPE) ?
kWarningBackgroundColorTop : kPageActionBackgroundColorTop;
}
// static
SkColor InfoBar::GetBottomColor(InfoBarDelegate::Type infobar_type) {
// No gradient in MD.
if (ui::MaterialDesignController::IsModeMaterial())
return GetTopColor(infobar_type);
static const SkColor kWarningBackgroundColorBottom =
SkColorSetRGB(250, 230, 145); // Yellow
static const SkColor kPageActionBackgroundColorBottom =
SkColorSetRGB(217, 217, 217); // Gray
return (infobar_type == InfoBarDelegate::WARNING_TYPE) ?
kWarningBackgroundColorBottom : kPageActionBackgroundColorBottom;
}
void InfoBar::SetOwner(InfoBarManager* owner) {
DCHECK(!owner_);
owner_ = owner;
delegate_->set_nav_entry_id(owner->GetActiveEntryID());
PlatformSpecificSetOwner();
}
void InfoBar::Show(bool animate) {
PlatformSpecificShow(animate);
if (animate) {
animation_.Show();
} else {
animation_.Reset(1.0);
RecalculateHeights(true);
}
}
void InfoBar::Hide(bool animate) {
PlatformSpecificHide(animate);
if (animate) {
animation_.Hide();
} else {
animation_.Reset(0.0);
// We want to remove ourselves from the container immediately even if we
// still have an owner, which MaybeDelete() won't do.
DCHECK(container_);
container_->RemoveInfoBar(this);
MaybeDelete(); // Necessary if the infobar was already closing.
}
}
void InfoBar::SetArrowTargetHeight(int height) {
// Once the closing animation starts, we ignore further requests to change the
// target height.
if ((arrow_target_height_ != height) && !animation_.IsClosing()) {
arrow_target_height_ = height;
RecalculateHeights(false);
}
}
void InfoBar::CloseSoon() {
owner_ = NULL;
PlatformSpecificOnCloseSoon();
MaybeDelete();
}
void InfoBar::RemoveSelf() {
if (owner_)
owner_->RemoveInfoBar(this);
}
void InfoBar::SetBarTargetHeight(int height) {
if (bar_target_height_ != height) {
bar_target_height_ = height;
RecalculateHeights(false);
}
}
void InfoBar::AnimationProgressed(const gfx::Animation* animation) {
RecalculateHeights(false);
}
void InfoBar::AnimationEnded(const gfx::Animation* animation) {
// When the animation ends, we must ensure the container is notified even if
// the heights haven't changed, lest it never get an "animation finished"
// notification. (If the browser doesn't get this notification, it will not
// bother to re-layout the content area for the new infobar size.)
RecalculateHeights(true);
MaybeDelete();
}
void InfoBar::RecalculateHeights(bool force_notify) {
// If there's no container delegate, there's no way to compute new element
// sizes, so return immediately. We don't need to worry that this might leave
// us with bogus sizes, because if we're ever re-added to a container, it will
// call Show(false) while re-adding us, which will compute a correct set of
// sizes.
if (!container_ || !container_->delegate())
return;
int old_arrow_height = arrow_height_;
int old_bar_height = bar_height_;
container_->delegate()->ComputeInfoBarElementSizes(
animation_, arrow_target_height_, bar_target_height_, &arrow_height_,
&arrow_half_width_, &bar_height_);
// Don't re-layout if nothing has changed, e.g. because the animation step was
// not large enough to actually change the heights by at least a pixel.
bool heights_differ =
(old_arrow_height != arrow_height_) || (old_bar_height != bar_height_);
if (heights_differ)
PlatformSpecificOnHeightsRecalculated();
if (heights_differ || force_notify)
container_->OnInfoBarStateChanged(animation_.is_animating());
}
void InfoBar::MaybeDelete() {
if (!owner_ && (animation_.GetCurrentValue() == 0.0)) {
if (container_)
container_->RemoveInfoBar(this);
delete this;
}
}
} // namespace infobars
|
//===----------------------------------------------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
// <list>
// template <class T, class Alloc>
// void swap(list<T,Alloc>& x, list<T,Alloc>& y);
#if _LIBCPP_DEBUG >= 1
#define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0))
#endif
#include <list>
#include <cassert>
#include <__debug>
#include "min_allocator.h"
int main()
{
#if _LIBCPP_DEBUG >= 1
{
int a1[] = {1, 3, 7, 9, 10};
int a2[] = {0, 2, 4, 5, 6, 8, 11};
std::list<int> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
std::list<int> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
std::list<int>::iterator i1 = c1.begin();
std::list<int>::iterator i2 = c2.begin();
swap(c1, c2);
c1.erase(i2);
c2.erase(i1);
std::list<int>::iterator j = i1;
c1.erase(i1);
assert(false);
}
#if __cplusplus >= 201103L
{
int a1[] = {1, 3, 7, 9, 10};
int a2[] = {0, 2, 4, 5, 6, 8, 11};
std::list<int, min_allocator<int>> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
std::list<int, min_allocator<int>> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
std::list<int, min_allocator<int>>::iterator i1 = c1.begin();
std::list<int, min_allocator<int>>::iterator i2 = c2.begin();
swap(c1, c2);
c1.erase(i2);
c2.erase(i1);
std::list<int, min_allocator<int>>::iterator j = i1;
c1.erase(i1);
assert(false);
}
#endif
#endif
}
|
#include <catch.hpp>
#include <PMMR/Common/MMRUtil.h>
TEST_CASE("MMRUtil::GetHeight")
{
REQUIRE(MMRUtil::GetHeight(0) == 0);
REQUIRE(MMRUtil::GetHeight(1) == 0);
REQUIRE(MMRUtil::GetHeight(2) == 1);
REQUIRE(MMRUtil::GetHeight(3) == 0);
REQUIRE(MMRUtil::GetHeight(4) == 0);
REQUIRE(MMRUtil::GetHeight(5) == 1);
REQUIRE(MMRUtil::GetHeight(6) == 2);
REQUIRE(MMRUtil::GetHeight(7) == 0);
REQUIRE(MMRUtil::GetHeight(8) == 0);
REQUIRE(MMRUtil::GetHeight(9) == 1);
REQUIRE(MMRUtil::GetHeight(10) == 0);
REQUIRE(MMRUtil::GetHeight(11) == 0);
REQUIRE(MMRUtil::GetHeight(12) == 1);
REQUIRE(MMRUtil::GetHeight(13) == 2);
REQUIRE(MMRUtil::GetHeight(14) == 3);
REQUIRE(MMRUtil::GetHeight(15) == 0);
REQUIRE(MMRUtil::GetHeight(16) == 0);
REQUIRE(MMRUtil::GetHeight(17) == 1);
REQUIRE(MMRUtil::GetHeight(18) == 0);
REQUIRE(MMRUtil::GetHeight(19) == 0);
REQUIRE(MMRUtil::GetHeight(20) == 1);
REQUIRE(MMRUtil::GetHeight(21) == 2);
REQUIRE(MMRUtil::GetHeight(22) == 0);
REQUIRE(MMRUtil::GetHeight(23) == 0);
REQUIRE(MMRUtil::GetHeight(24) == 1);
REQUIRE(MMRUtil::GetHeight(25) == 0);
REQUIRE(MMRUtil::GetHeight(26) == 0);
REQUIRE(MMRUtil::GetHeight(27) == 1);
REQUIRE(MMRUtil::GetHeight(28) == 2);
REQUIRE(MMRUtil::GetHeight(29) == 3);
REQUIRE(MMRUtil::GetHeight(30) == 4);
REQUIRE(MMRUtil::GetHeight(1048574) == 19);
}
TEST_CASE("MMRUtil::GetPeakIndices")
{
REQUIRE(MMRUtil::GetPeakIndices(0) == std::vector<uint64_t>({ }));
REQUIRE(MMRUtil::GetPeakIndices(1) == std::vector<uint64_t>({ 0 }));
REQUIRE(MMRUtil::GetPeakIndices(2) == std::vector<uint64_t>({ }));
REQUIRE(MMRUtil::GetPeakIndices(3) == std::vector<uint64_t>({ 2 }));
REQUIRE(MMRUtil::GetPeakIndices(4) == std::vector<uint64_t>({ 2, 3 }));
REQUIRE(MMRUtil::GetPeakIndices(5) == std::vector<uint64_t>({ }));
REQUIRE(MMRUtil::GetPeakIndices(6) == std::vector<uint64_t>({ }));
REQUIRE(MMRUtil::GetPeakIndices(7) == std::vector<uint64_t>({ 6 }));
REQUIRE(MMRUtil::GetPeakIndices(8) == std::vector<uint64_t>({ 6, 7 }));
REQUIRE(MMRUtil::GetPeakIndices(9) == std::vector<uint64_t>({ }));
REQUIRE(MMRUtil::GetPeakIndices(10) == std::vector<uint64_t>({ 6, 9 }));
REQUIRE(MMRUtil::GetPeakIndices(11) == std::vector<uint64_t>({ 6, 9, 10 }));
REQUIRE(MMRUtil::GetPeakIndices(22) == std::vector<uint64_t>({ 14, 21 }));
REQUIRE(MMRUtil::GetPeakIndices(32) == std::vector<uint64_t>({ 30, 31 }));
REQUIRE(MMRUtil::GetPeakIndices(35) == std::vector<uint64_t>({ 30, 33, 34 }));
REQUIRE(MMRUtil::GetPeakIndices(42) == std::vector<uint64_t>({ 30, 37, 40, 41 }));
}
TEST_CASE("MMRUtil::GetNumNodes")
{
REQUIRE(MMRUtil::GetNumNodes(0) == 1);
REQUIRE(MMRUtil::GetNumNodes(1) == 3);
REQUIRE(MMRUtil::GetNumNodes(2) == 3);
REQUIRE(MMRUtil::GetNumNodes(3) == 4);
REQUIRE(MMRUtil::GetNumNodes(4) == 7);
REQUIRE(MMRUtil::GetNumNodes(5) == 7);
REQUIRE(MMRUtil::GetNumNodes(6) == 7);
REQUIRE(MMRUtil::GetNumNodes(7) == 8);
REQUIRE(MMRUtil::GetNumNodes(8) == 10);
REQUIRE(MMRUtil::GetNumNodes(9) == 10);
REQUIRE(MMRUtil::GetNumNodes(10) == 11);
REQUIRE(MMRUtil::GetNumNodes(11) == 15);
REQUIRE(MMRUtil::GetNumNodes(12) == 15);
REQUIRE(MMRUtil::GetNumNodes(13) == 15);
REQUIRE(MMRUtil::GetNumNodes(14) == 15);
REQUIRE(MMRUtil::GetNumNodes(15) == 16);
REQUIRE(MMRUtil::GetNumNodes(16) == 18);
REQUIRE(MMRUtil::GetNumNodes(17) == 18);
REQUIRE(MMRUtil::GetNumNodes(18) == 19);
REQUIRE(MMRUtil::GetNumNodes(19) == 22);
REQUIRE(MMRUtil::GetNumNodes(20) == 22);
}
TEST_CASE("MMRUtil::GetParentIndex")
{
REQUIRE(MMRUtil::GetParentIndex(0) == 2);
REQUIRE(MMRUtil::GetParentIndex(1) == 2);
REQUIRE(MMRUtil::GetParentIndex(2) == 6);
REQUIRE(MMRUtil::GetParentIndex(3) == 5);
REQUIRE(MMRUtil::GetParentIndex(4) == 5);
REQUIRE(MMRUtil::GetParentIndex(5) == 6);
REQUIRE(MMRUtil::GetParentIndex(6) == 14);
REQUIRE(MMRUtil::GetParentIndex(7) == 9);
REQUIRE(MMRUtil::GetParentIndex(8) == 9);
REQUIRE(MMRUtil::GetParentIndex(9) == 13);
REQUIRE(MMRUtil::GetParentIndex(10) == 12);
REQUIRE(MMRUtil::GetParentIndex(11) == 12);
REQUIRE(MMRUtil::GetParentIndex(12) == 13);
REQUIRE(MMRUtil::GetParentIndex(13) == 14);
REQUIRE(MMRUtil::GetParentIndex(14) == 30);
REQUIRE(MMRUtil::GetParentIndex(15) == 17);
}
TEST_CASE("MMRUtil::GetSiblingIndex")
{
REQUIRE(MMRUtil::GetSiblingIndex(0) == 1);
REQUIRE(MMRUtil::GetSiblingIndex(1) == 0);
REQUIRE(MMRUtil::GetSiblingIndex(2) == 5);
REQUIRE(MMRUtil::GetSiblingIndex(3) == 4);
REQUIRE(MMRUtil::GetSiblingIndex(4) == 3);
REQUIRE(MMRUtil::GetSiblingIndex(5) == 2);
REQUIRE(MMRUtil::GetSiblingIndex(6) == 13);
REQUIRE(MMRUtil::GetSiblingIndex(7) == 8);
REQUIRE(MMRUtil::GetSiblingIndex(8) == 7);
REQUIRE(MMRUtil::GetSiblingIndex(9) == 12);
REQUIRE(MMRUtil::GetSiblingIndex(10) == 11);
REQUIRE(MMRUtil::GetSiblingIndex(11) == 10);
REQUIRE(MMRUtil::GetSiblingIndex(12) == 9);
REQUIRE(MMRUtil::GetSiblingIndex(13) == 6);
REQUIRE(MMRUtil::GetSiblingIndex(14) == 29);
REQUIRE(MMRUtil::GetSiblingIndex(15) == 16);
REQUIRE(MMRUtil::GetSiblingIndex(16) == 15);
REQUIRE(MMRUtil::GetSiblingIndex(29) == 14);
}
TEST_CASE("MMRUtil::GetNumLeaves")
{
REQUIRE(MMRUtil::GetNumLeaves(0) == 1);
REQUIRE(MMRUtil::GetNumLeaves(1) == 2);
REQUIRE(MMRUtil::GetNumLeaves(2) == 2);
REQUIRE(MMRUtil::GetNumLeaves(3) == 3);
REQUIRE(MMRUtil::GetNumLeaves(4) == 4);
REQUIRE(MMRUtil::GetNumLeaves(5) == 4);
REQUIRE(MMRUtil::GetNumLeaves(6) == 4);
REQUIRE(MMRUtil::GetNumLeaves(7) == 5);
REQUIRE(MMRUtil::GetNumLeaves(8) == 6);
REQUIRE(MMRUtil::GetNumLeaves(9) == 6);
REQUIRE(MMRUtil::GetNumLeaves(10) == 7);
}
|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/engine.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "flutter/common/settings.h"
#include "flutter/fml/eintr_wrapper.h"
#include "flutter/fml/file.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/trace_event.h"
#include "flutter/fml/unique_fd.h"
#include "flutter/lib/snapshot/snapshot.h"
#include "flutter/lib/ui/text/font_collection.h"
#include "flutter/shell/common/animator.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/shell.h"
#include "rapidjson/document.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
namespace flutter {
static constexpr char kAssetChannel[] = "flutter/assets";
static constexpr char kLifecycleChannel[] = "flutter/lifecycle";
static constexpr char kNavigationChannel[] = "flutter/navigation";
static constexpr char kLocalizationChannel[] = "flutter/localization";
static constexpr char kSettingsChannel[] = "flutter/settings";
static constexpr char kIsolateChannel[] = "flutter/isolate";
Engine::Engine(
Delegate& delegate,
const PointerDataDispatcherMaker& dispatcher_maker,
std::shared_ptr<fml::ConcurrentTaskRunner> image_decoder_task_runner,
TaskRunners task_runners,
Settings settings,
std::unique_ptr<Animator> animator,
fml::WeakPtr<IOManager> io_manager,
std::unique_ptr<RuntimeController> runtime_controller)
: delegate_(delegate),
settings_(std::move(settings)),
animator_(std::move(animator)),
runtime_controller_(std::move(runtime_controller)),
activity_running_(true),
have_surface_(false),
image_decoder_(task_runners, image_decoder_task_runner, io_manager),
task_runners_(std::move(task_runners)),
weak_factory_(this) {
pointer_data_dispatcher_ = dispatcher_maker(*this);
}
Engine::Engine(Delegate& delegate,
const PointerDataDispatcherMaker& dispatcher_maker,
DartVM& vm,
fml::RefPtr<const DartSnapshot> isolate_snapshot,
TaskRunners task_runners,
const PlatformData platform_data,
Settings settings,
std::unique_ptr<Animator> animator,
fml::WeakPtr<IOManager> io_manager,
fml::RefPtr<SkiaUnrefQueue> unref_queue,
fml::WeakPtr<SnapshotDelegate> snapshot_delegate)
: Engine(delegate,
dispatcher_maker,
vm.GetConcurrentWorkerTaskRunner(),
task_runners,
settings,
std::move(animator),
io_manager,
nullptr) {
runtime_controller_ = std::make_unique<RuntimeController>(
*this, // runtime delegate
&vm, // VM
std::move(isolate_snapshot), // isolate snapshot
task_runners_, // task runners
std::move(snapshot_delegate), // snapshot delegate
GetWeakPtr(), // hint freed delegate
std::move(io_manager), // io manager
std::move(unref_queue), // Skia unref queue
image_decoder_.GetWeakPtr(), // image decoder
settings_.advisory_script_uri, // advisory script uri
settings_.advisory_script_entrypoint, // advisory script entrypoint
settings_.idle_notification_callback, // idle notification callback
platform_data, // platform data
settings_.isolate_create_callback, // isolate create callback
settings_.isolate_shutdown_callback, // isolate shutdown callback
settings_.persistent_isolate_data // persistent isolate data
);
}
Engine::~Engine() = default;
float Engine::GetDisplayRefreshRate() const {
return animator_->GetDisplayRefreshRate();
}
fml::WeakPtr<Engine> Engine::GetWeakPtr() const {
return weak_factory_.GetWeakPtr();
}
void Engine::SetupDefaultFontManager() {
TRACE_EVENT0("flutter", "Engine::SetupDefaultFontManager");
font_collection_.SetupDefaultFontManager();
}
bool Engine::UpdateAssetManager(
std::shared_ptr<AssetManager> new_asset_manager) {
if (asset_manager_ == new_asset_manager) {
return false;
}
asset_manager_ = new_asset_manager;
if (!asset_manager_) {
return false;
}
// Using libTXT as the text engine.
font_collection_.RegisterFonts(asset_manager_);
if (settings_.use_test_fonts) {
font_collection_.RegisterTestFonts();
}
return true;
}
bool Engine::Restart(RunConfiguration configuration) {
TRACE_EVENT0("flutter", "Engine::Restart");
if (!configuration.IsValid()) {
FML_LOG(ERROR) << "Engine run configuration was invalid.";
return false;
}
delegate_.OnPreEngineRestart();
runtime_controller_ = runtime_controller_->Clone();
UpdateAssetManager(nullptr);
return Run(std::move(configuration)) == Engine::RunStatus::Success;
}
Engine::RunStatus Engine::Run(RunConfiguration configuration) {
if (!configuration.IsValid()) {
FML_LOG(ERROR) << "Engine run configuration was invalid.";
return RunStatus::Failure;
}
last_entry_point_ = configuration.GetEntrypoint();
last_entry_point_library_ = configuration.GetEntrypointLibrary();
auto isolate_launch_status =
PrepareAndLaunchIsolate(std::move(configuration));
if (isolate_launch_status == Engine::RunStatus::Failure) {
FML_LOG(ERROR) << "Engine not prepare and launch isolate.";
return isolate_launch_status;
} else if (isolate_launch_status ==
Engine::RunStatus::FailureAlreadyRunning) {
return isolate_launch_status;
}
std::shared_ptr<DartIsolate> isolate =
runtime_controller_->GetRootIsolate().lock();
bool isolate_running =
isolate && isolate->GetPhase() == DartIsolate::Phase::Running;
if (isolate_running) {
tonic::DartState::Scope scope(isolate.get());
if (settings_.root_isolate_create_callback) {
settings_.root_isolate_create_callback();
}
if (settings_.root_isolate_shutdown_callback) {
isolate->AddIsolateShutdownCallback(
settings_.root_isolate_shutdown_callback);
}
std::string service_id = isolate->GetServiceId();
fml::RefPtr<PlatformMessage> service_id_message =
fml::MakeRefCounted<flutter::PlatformMessage>(
kIsolateChannel,
std::vector<uint8_t>(service_id.begin(), service_id.end()),
nullptr);
HandlePlatformMessage(service_id_message);
}
return isolate_running ? Engine::RunStatus::Success
: Engine::RunStatus::Failure;
}
Engine::RunStatus Engine::PrepareAndLaunchIsolate(
RunConfiguration configuration) {
TRACE_EVENT0("flutter", "Engine::PrepareAndLaunchIsolate");
UpdateAssetManager(configuration.GetAssetManager());
auto isolate_configuration = configuration.TakeIsolateConfiguration();
std::shared_ptr<DartIsolate> isolate =
runtime_controller_->GetRootIsolate().lock();
if (!isolate) {
return RunStatus::Failure;
}
// This can happen on iOS after a plugin shows a native window and returns to
// the Flutter ViewController.
if (isolate->GetPhase() == DartIsolate::Phase::Running) {
FML_DLOG(WARNING) << "Isolate was already running!";
return RunStatus::FailureAlreadyRunning;
}
if (!isolate_configuration->PrepareIsolate(*isolate)) {
FML_LOG(ERROR) << "Could not prepare to run the isolate.";
return RunStatus::Failure;
}
if (configuration.GetEntrypointLibrary().empty()) {
if (!isolate->Run(configuration.GetEntrypoint(),
settings_.dart_entrypoint_args)) {
FML_LOG(ERROR) << "Could not run the isolate.";
return RunStatus::Failure;
}
} else {
if (!isolate->RunFromLibrary(configuration.GetEntrypointLibrary(),
configuration.GetEntrypoint(),
settings_.dart_entrypoint_args)) {
FML_LOG(ERROR) << "Could not run the isolate.";
return RunStatus::Failure;
}
}
return RunStatus::Success;
}
void Engine::BeginFrame(fml::TimePoint frame_time) {
TRACE_EVENT0("flutter", "Engine::BeginFrame");
runtime_controller_->BeginFrame(frame_time);
}
void Engine::ReportTimings(std::vector<int64_t> timings) {
TRACE_EVENT0("flutter", "Engine::ReportTimings");
runtime_controller_->ReportTimings(std::move(timings));
}
void Engine::HintFreed(size_t size) {
hint_freed_bytes_since_last_idle_ += size;
}
void Engine::NotifyIdle(int64_t deadline) {
auto trace_event = std::to_string(deadline - Dart_TimelineGetMicros());
TRACE_EVENT1("flutter", "Engine::NotifyIdle", "deadline_now_delta",
trace_event.c_str());
runtime_controller_->NotifyIdle(deadline, hint_freed_bytes_since_last_idle_);
hint_freed_bytes_since_last_idle_ = 0;
}
std::pair<bool, uint32_t> Engine::GetUIIsolateReturnCode() {
return runtime_controller_->GetRootIsolateReturnCode();
}
Dart_Port Engine::GetUIIsolateMainPort() {
return runtime_controller_->GetMainPort();
}
std::string Engine::GetUIIsolateName() {
return runtime_controller_->GetIsolateName();
}
bool Engine::UIIsolateHasLivePorts() {
return runtime_controller_->HasLivePorts();
}
tonic::DartErrorHandleType Engine::GetUIIsolateLastError() {
return runtime_controller_->GetLastError();
}
void Engine::OnOutputSurfaceCreated() {
have_surface_ = true;
StartAnimatorIfPossible();
ScheduleFrame();
}
void Engine::OnOutputSurfaceDestroyed() {
have_surface_ = false;
StopAnimator();
}
void Engine::SetViewportMetrics(const ViewportMetrics& metrics) {
bool dimensions_changed =
viewport_metrics_.physical_height != metrics.physical_height ||
viewport_metrics_.physical_width != metrics.physical_width ||
viewport_metrics_.device_pixel_ratio != metrics.device_pixel_ratio;
viewport_metrics_ = metrics;
runtime_controller_->SetViewportMetrics(viewport_metrics_);
if (animator_) {
if (dimensions_changed) {
animator_->SetDimensionChangePending();
}
if (have_surface_) {
ScheduleFrame();
}
}
}
void Engine::DispatchPlatformMessage(fml::RefPtr<PlatformMessage> message) {
std::string channel = message->channel();
if (channel == kLifecycleChannel) {
if (HandleLifecyclePlatformMessage(message.get())) {
return;
}
} else if (channel == kLocalizationChannel) {
if (HandleLocalizationPlatformMessage(message.get())) {
return;
}
} else if (channel == kSettingsChannel) {
HandleSettingsPlatformMessage(message.get());
return;
} else if (!runtime_controller_->IsRootIsolateRunning() &&
channel == kNavigationChannel) {
// If there's no runtime_, we may still need to set the initial route.
HandleNavigationPlatformMessage(std::move(message));
return;
}
if (runtime_controller_->IsRootIsolateRunning() &&
runtime_controller_->DispatchPlatformMessage(std::move(message))) {
return;
}
FML_DLOG(WARNING) << "Dropping platform message on channel: " << channel;
}
bool Engine::HandleLifecyclePlatformMessage(PlatformMessage* message) {
const auto& data = message->data();
std::string state(reinterpret_cast<const char*>(data.data()), data.size());
if (state == "AppLifecycleState.paused" ||
state == "AppLifecycleState.detached") {
activity_running_ = false;
StopAnimator();
} else if (state == "AppLifecycleState.resumed" ||
state == "AppLifecycleState.inactive") {
activity_running_ = true;
StartAnimatorIfPossible();
}
// Always schedule a frame when the app does become active as per API
// recommendation
// https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc
if (state == "AppLifecycleState.resumed" && have_surface_) {
ScheduleFrame();
}
runtime_controller_->SetLifecycleState(state);
// Always forward these messages to the framework by returning false.
return false;
}
bool Engine::HandleNavigationPlatformMessage(
fml::RefPtr<PlatformMessage> message) {
const auto& data = message->data();
rapidjson::Document document;
document.Parse(reinterpret_cast<const char*>(data.data()), data.size());
if (document.HasParseError() || !document.IsObject()) {
return false;
}
auto root = document.GetObject();
auto method = root.FindMember("method");
if (method->value != "setInitialRoute") {
return false;
}
auto route = root.FindMember("args");
initial_route_ = std::move(route->value.GetString());
return true;
}
bool Engine::HandleLocalizationPlatformMessage(PlatformMessage* message) {
const auto& data = message->data();
rapidjson::Document document;
document.Parse(reinterpret_cast<const char*>(data.data()), data.size());
if (document.HasParseError() || !document.IsObject()) {
return false;
}
auto root = document.GetObject();
auto method = root.FindMember("method");
if (method == root.MemberEnd()) {
return false;
}
const size_t strings_per_locale = 4;
if (method->value == "setLocale") {
// Decode and pass the list of locale data onwards to dart.
auto args = root.FindMember("args");
if (args == root.MemberEnd() || !args->value.IsArray()) {
return false;
}
if (args->value.Size() % strings_per_locale != 0) {
return false;
}
std::vector<std::string> locale_data;
for (size_t locale_index = 0; locale_index < args->value.Size();
locale_index += strings_per_locale) {
if (!args->value[locale_index].IsString() ||
!args->value[locale_index + 1].IsString()) {
return false;
}
locale_data.push_back(args->value[locale_index].GetString());
locale_data.push_back(args->value[locale_index + 1].GetString());
locale_data.push_back(args->value[locale_index + 2].GetString());
locale_data.push_back(args->value[locale_index + 3].GetString());
}
return runtime_controller_->SetLocales(locale_data);
}
return false;
}
void Engine::HandleSettingsPlatformMessage(PlatformMessage* message) {
const auto& data = message->data();
std::string jsonData(reinterpret_cast<const char*>(data.data()), data.size());
if (runtime_controller_->SetUserSettingsData(std::move(jsonData)) &&
have_surface_) {
ScheduleFrame();
}
}
void Engine::DispatchPointerDataPacket(
std::unique_ptr<PointerDataPacket> packet,
uint64_t trace_flow_id) {
TRACE_EVENT0("flutter", "Engine::DispatchPointerDataPacket");
TRACE_FLOW_STEP("flutter", "PointerEvent", trace_flow_id);
pointer_data_dispatcher_->DispatchPacket(std::move(packet), trace_flow_id);
}
void Engine::DispatchSemanticsAction(int id,
SemanticsAction action,
std::vector<uint8_t> args) {
runtime_controller_->DispatchSemanticsAction(id, action, std::move(args));
}
void Engine::SetSemanticsEnabled(bool enabled) {
runtime_controller_->SetSemanticsEnabled(enabled);
}
void Engine::SetAccessibilityFeatures(int32_t flags) {
runtime_controller_->SetAccessibilityFeatures(flags);
}
void Engine::StopAnimator() {
animator_->Stop();
}
void Engine::StartAnimatorIfPossible() {
if (activity_running_ && have_surface_) {
animator_->Start();
}
}
std::string Engine::DefaultRouteName() {
if (!initial_route_.empty()) {
return initial_route_;
}
return "/";
}
void Engine::ScheduleFrame(bool regenerate_layer_tree) {
animator_->RequestFrame(regenerate_layer_tree);
}
void Engine::Render(std::unique_ptr<flutter::LayerTree> layer_tree) {
if (!layer_tree) {
return;
}
// Ensure frame dimensions are sane.
if (layer_tree->frame_size().isEmpty() ||
layer_tree->device_pixel_ratio() <= 0.0f) {
return;
}
animator_->Render(std::move(layer_tree));
}
void Engine::UpdateSemantics(SemanticsNodeUpdates update,
CustomAccessibilityActionUpdates actions) {
delegate_.OnEngineUpdateSemantics(std::move(update), std::move(actions));
}
void Engine::HandlePlatformMessage(fml::RefPtr<PlatformMessage> message) {
if (message->channel() == kAssetChannel) {
HandleAssetPlatformMessage(std::move(message));
} else {
delegate_.OnEngineHandlePlatformMessage(std::move(message));
}
}
void Engine::UpdateIsolateDescription(const std::string isolate_name,
int64_t isolate_port) {
delegate_.UpdateIsolateDescription(isolate_name, isolate_port);
}
std::unique_ptr<std::vector<std::string>> Engine::ComputePlatformResolvedLocale(
const std::vector<std::string>& supported_locale_data) {
return delegate_.ComputePlatformResolvedLocale(supported_locale_data);
}
void Engine::SetNeedsReportTimings(bool needs_reporting) {
delegate_.SetNeedsReportTimings(needs_reporting);
}
FontCollection& Engine::GetFontCollection() {
return font_collection_;
}
void Engine::DoDispatchPacket(std::unique_ptr<PointerDataPacket> packet,
uint64_t trace_flow_id) {
animator_->EnqueueTraceFlowId(trace_flow_id);
if (runtime_controller_) {
runtime_controller_->DispatchPointerDataPacket(*packet);
}
}
void Engine::ScheduleSecondaryVsyncCallback(const fml::closure& callback) {
animator_->ScheduleSecondaryVsyncCallback(callback);
}
void Engine::HandleAssetPlatformMessage(fml::RefPtr<PlatformMessage> message) {
fml::RefPtr<PlatformMessageResponse> response = message->response();
if (!response) {
return;
}
const auto& data = message->data();
std::string asset_name(reinterpret_cast<const char*>(data.data()),
data.size());
if (asset_manager_) {
std::unique_ptr<fml::Mapping> asset_mapping =
asset_manager_->GetAsMapping(asset_name);
if (asset_mapping) {
response->Complete(std::move(asset_mapping));
return;
}
}
response->CompleteEmpty();
}
const std::string& Engine::GetLastEntrypoint() const {
return last_entry_point_;
}
const std::string& Engine::GetLastEntrypointLibrary() const {
return last_entry_point_library_;
}
} // namespace flutter
|
// dParserGenerator.cpp : Defines the entry point for the console application.
//
#include "dParserCompiler.h"
bool CheckDependency(const char* const target, const char* const source)
{
struct _stat sourceStat;
struct _stat targetStat;
int result = _stat (target, &targetStat);
if( result == 0 ) {
result = _stat (source, &sourceStat);
if( result == 0 ) {
return targetStat.st_mtime > sourceStat.st_mtime;
}
}
return false;
}
int main(int argc, char* argv[])
{
#ifdef _MSC_VER
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
if (argc < 4) {
fprintf (stdout, "usage: dParcelGenerator [GrammarFile] [scannerClasName] [OutputFileName]\n");
fprintf (stdout, "[GrammarFile] name of the file containing a Yacc like Grammar file\n");
fprintf (stdout, "[ScannerClass] Name of the Scanner Class Generated by dLexGenerator\n");
fprintf (stdout, "[OutputFileName] name of the file cpp output file\n");
exit (0);
}
const char* const inputRulesFileName = argv[1];
const char* const scannerClassName = argv[2];
const char* const outputFileName = argv[3];
if (!CheckDependency (outputFileName, inputRulesFileName)) {
FILE* const rules = fopen (inputRulesFileName, "rb");
if (!rules) {
fprintf (stdout, "Rule file \"%s\" not found\n", inputRulesFileName);
exit (0);
}
dString buffer;
buffer.LoadFile(rules);
fclose (rules);
dParserCompiler parcel (buffer, outputFileName, scannerClassName);
}
return 0;
}
|
// Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Signer.h"
#include "Address.h"
#include "Protobuf/ZilliqaMessage.pb.h"
#include "../Hash.h"
#include "../HexCoding.h"
#include "../uint256.h"
#include <cassert>
using namespace TW;
using namespace TW::Zilliqa;
static inline Data prependZero(Data& data) {
if (data.size() < 16) {
Data zero = Data(16 - data.size(), 0);
zero.insert(zero.end(), data.begin(), data.end());
return zero;
}
return Data(data);
}
Data Signer::getPreImage(const Proto::SigningInput& input) noexcept {
auto internal = ZilliqaMessage::ProtoTransactionCoreInfo();
const auto key = PrivateKey(Data(input.private_key().begin(), input.private_key().end()));
const auto address = Cosmos::Address::decode(input.to_address());
const auto pubKey = key.getPublicKey(TWPublicKeyTypeSECP256k1);
internal.set_version(input.version());
internal.set_nonce(input.nonce());
internal.set_toaddr(address.first.keyHash.data(), address.first.keyHash.size());
auto sender = new ZilliqaMessage::ByteArray();
sender->set_data(pubKey.bytes.data(), pubKey.bytes.size());
internal.set_allocated_senderpubkey(sender);
auto amountArray = new ZilliqaMessage::ByteArray();
auto amount = Data(input.amount().begin(), input.amount().end());
amount = prependZero(amount);
amountArray->set_data(amount.data(), amount.size());
internal.set_allocated_amount(amountArray);
auto gasPriceArray = new ZilliqaMessage::ByteArray();
auto gasPrice = Data(input.gas_price().begin(), input.gas_price().end());
gasPrice = prependZero(gasPrice);
gasPriceArray->set_data(gasPrice.data(), gasPrice.size());
internal.set_allocated_gasprice(gasPriceArray);
internal.set_gaslimit(input.gas_limit());
const auto serialized = internal.SerializeAsString();
return Data(serialized.begin(), serialized.end());
}
Proto::SigningOutput Signer::sign(const Data& preImage, const PrivateKey& key) noexcept {
auto output = Proto::SigningOutput();
const auto signature = key.signSchnorr(preImage, TWCurveSECP256k1);
output.set_signature(signature.data(), signature.size());
return output;
}
|
/*
* Copyright 2015-2017, Intel Corporation
*
* 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 copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*/
/*
* obj_cpp_ptr.c -- cpp bindings test
*
*/
#include "unittest.h"
#include <libpmemobj++/make_persistent.hpp>
#include <libpmemobj++/make_persistent_array_atomic.hpp>
#include <libpmemobj++/make_persistent_atomic.hpp>
#include <libpmemobj++/p.hpp>
#include <libpmemobj++/persistent_ptr.hpp>
#include <libpmemobj++/pool.hpp>
#include <libpmemobj++/transaction.hpp>
#define LAYOUT "cpp"
namespace nvobj = nvml::obj;
namespace
{
/*
* test_null_ptr -- verifies if the pointer correctly behaves like a
* nullptr-value
*/
void
test_null_ptr(nvobj::persistent_ptr<int> &f)
{
UT_ASSERT(OID_IS_NULL(f.raw()));
UT_ASSERT((bool)f == false);
UT_ASSERT(!f);
UT_ASSERTeq(f.get(), nullptr);
UT_ASSERT(f == nullptr);
}
/*
* get_temp -- returns a temporary persistent_ptr
*/
nvobj::persistent_ptr<int>
get_temp()
{
nvobj::persistent_ptr<int> int_null = nullptr;
return int_null;
}
/*
* test_ptr_operators_null -- verifies various operations on nullptr pointers
*/
void
test_ptr_operators_null()
{
nvobj::persistent_ptr<int> int_default_null;
test_null_ptr(int_default_null);
nvobj::persistent_ptr<int> int_explicit_ptr_null = nullptr;
test_null_ptr(int_explicit_ptr_null);
nvobj::persistent_ptr<int> int_explicit_oid_null = OID_NULL;
test_null_ptr(int_explicit_oid_null);
nvobj::persistent_ptr<int> int_base = nullptr;
nvobj::persistent_ptr<int> int_same = int_base;
int_same = int_base;
test_null_ptr(int_same);
swap(int_base, int_same);
auto temp_ptr = get_temp();
test_null_ptr(temp_ptr);
}
const int TEST_INT = 10;
const int TEST_ARR_SIZE = 10;
const char TEST_CHAR = 'a';
struct foo {
nvobj::p<int> bar;
nvobj::p<char> arr[TEST_ARR_SIZE];
};
struct nested {
nvobj::persistent_ptr<foo> inner;
};
struct root {
nvobj::persistent_ptr<foo> pfoo;
nvobj::persistent_ptr<nvobj::p<int>[TEST_ARR_SIZE]> parr;
/* This variable is unused, but it's here to check if the persistent_ptr
* does not violate it's own restrictions.
*/
nvobj::persistent_ptr<nested> outer;
};
/*
* test_ptr_atomic -- verifies the persistent ptr with the atomic C API
*/
void
test_ptr_atomic(nvobj::pool<root> &pop)
{
nvobj::persistent_ptr<foo> pfoo;
try {
nvobj::make_persistent_atomic<foo>(pop, pfoo);
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERTne(pfoo.get(), nullptr);
(*pfoo).bar = TEST_INT;
pop.persist(pfoo);
pop.memset_persist(pfoo->arr, TEST_CHAR, sizeof(pfoo->arr));
for (auto c : pfoo->arr) {
UT_ASSERTeq(c, TEST_CHAR);
}
try {
nvobj::delete_persistent_atomic<foo>(pfoo);
pfoo = nullptr;
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERTeq(pfoo.get(), nullptr);
}
/*
* test_ptr_transactional -- verifies the persistent ptr with the tx C API
*/
void
test_ptr_transactional(nvobj::pool<root> &pop)
{
auto r = pop.get_root();
nvobj::persistent_ptr<foo> to_swap;
try {
nvobj::transaction::exec_tx(pop, [&] {
UT_ASSERT(r->pfoo == nullptr);
r->pfoo = nvobj::make_persistent<foo>();
/* allocate for future swap test */
to_swap = nvobj::make_persistent<foo>();
});
} catch (...) {
UT_ASSERT(0);
}
auto pfoo = r->pfoo;
try {
nvobj::transaction::exec_tx(pop, [&] {
pfoo->bar = TEST_INT;
/* raw memory access requires extra care */
nvml::detail::conditional_add_to_tx(&pfoo->arr);
memset(&pfoo->arr, TEST_CHAR, sizeof(pfoo->arr));
/* do the swap test */
nvobj::persistent_ptr<foo> foo_ptr{r->pfoo};
nvobj::persistent_ptr<foo> swap_ptr{to_swap};
to_swap.swap(r->pfoo);
UT_ASSERT(to_swap == foo_ptr);
UT_ASSERT(r->pfoo == swap_ptr);
swap(r->pfoo, to_swap);
UT_ASSERT(to_swap == swap_ptr);
UT_ASSERT(r->pfoo == foo_ptr);
nvobj::delete_persistent<foo>(to_swap);
});
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERTeq(pfoo->bar, TEST_INT);
for (auto c : pfoo->arr) {
UT_ASSERTeq(c, TEST_CHAR);
}
bool exception_thrown = false;
try {
nvobj::transaction::exec_tx(pop, [&] {
pfoo->bar = 0;
nvobj::transaction::abort(-1);
});
} catch (nvml::manual_tx_abort &) {
exception_thrown = true;
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERT(exception_thrown);
UT_ASSERTeq(pfoo->bar, TEST_INT);
try {
nvobj::transaction::exec_tx(
pop, [&] { nvobj::delete_persistent<foo>(r->pfoo); });
r->pfoo = nullptr;
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERT(r->pfoo == nullptr);
UT_ASSERT(pfoo != nullptr);
}
/*
* test_ptr_array -- verifies the array specialization behavior
*/
void
test_ptr_array(nvobj::pool<root> &pop)
{
nvobj::persistent_ptr<nvobj::p<int>[]> parr_vsize;
try {
nvobj::make_persistent_atomic<nvobj::p<int>[]>(pop, parr_vsize,
TEST_ARR_SIZE);
} catch (...) {
UT_ASSERT(0);
}
{
nvobj::transaction::manual tx(pop);
for (int i = 0; i < TEST_ARR_SIZE; ++i)
parr_vsize[i] = i;
nvobj::transaction::commit();
}
for (int i = 0; i < TEST_ARR_SIZE; ++i)
UT_ASSERTeq(parr_vsize[i], i);
auto r = pop.get_root();
try {
nvobj::transaction::exec_tx(pop, [&] {
r->parr = pmemobj_tx_zalloc(sizeof(int) * TEST_ARR_SIZE,
0);
});
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERT(r->parr != nullptr);
bool exception_thrown = false;
try {
nvobj::transaction::exec_tx(pop, [&] {
for (int i = 0; i < TEST_ARR_SIZE; ++i)
r->parr[i] = TEST_INT;
nvobj::transaction::abort(-1);
});
} catch (nvml::manual_tx_abort &) {
exception_thrown = true;
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERT(exception_thrown);
exception_thrown = false;
try {
nvobj::transaction::exec_tx(pop, [&] {
for (int i = 0; i < TEST_ARR_SIZE; ++i)
r->parr[i] = TEST_INT;
nvobj::transaction::abort(-1);
});
} catch (nvml::manual_tx_abort &) {
exception_thrown = true;
} catch (...) {
UT_ASSERT(0);
}
UT_ASSERT(exception_thrown);
for (int i = 0; i < TEST_ARR_SIZE; ++i)
UT_ASSERTeq(r->parr[i], 0);
}
/*
* test_offset -- test offset calculation within a hierarchy
*/
void
test_offset(nvobj::pool<root> &pop)
{
struct A {
uint64_t a;
};
struct B {
uint64_t b;
};
struct C : public A, public B {
uint64_t c;
};
try {
nvobj::transaction::exec_tx(pop, [&pop] {
auto cptr = nvobj::make_persistent<C>();
nvobj::persistent_ptr<B> bptr = cptr;
UT_ASSERT((bptr.raw().off - cptr.raw().off) ==
sizeof(A));
nvobj::delete_persistent<C>(cptr);
});
} catch (...) {
UT_ASSERT(0);
}
}
}
int
main(int argc, char *argv[])
{
START(argc, argv, "obj_cpp_ptr");
if (argc != 2)
UT_FATAL("usage: %s file-name", argv[0]);
const char *path = argv[1];
nvobj::pool<root> pop;
try {
pop = nvobj::pool<struct root>::create(
path, LAYOUT, PMEMOBJ_MIN_POOL, S_IWUSR | S_IRUSR);
} catch (nvml::pool_error &pe) {
UT_FATAL("!pool::create: %s %s", pe.what(), path);
}
test_ptr_operators_null();
test_ptr_atomic(pop);
test_ptr_transactional(pop);
test_ptr_array(pop);
test_offset(pop);
pop.close();
DONE(nullptr);
}
|
#include "traversalgroup.h"
#include <algorithm>
namespace gui {
TraversalGroup::TraversalGroup() : lastFocusIndex_(0),
verticalArrows_(false), horizontalArrows_(false), tab_(true) {
}
void TraversalGroup::add(const std::shared_ptr<Component>& component) {
components_.push_back(component);
}
void TraversalGroup::remove(const std::shared_ptr<Component>& component) {
auto it = std::find(components_.begin(), components_.end(), component);
if (it != components_.end()) {
if (it - components_.begin() < lastFocusIndex_) {
// Move focus in order for the focus to remain on the same component.
// If the focus points to the removed component, then the focus is moved
// to the component to the left.
lastFocusIndex_--;
}
// Remove component.
components_.erase(it);
}
}
void TraversalGroup::removeAll() {
components_.clear();
}
void TraversalGroup::handleKeyboard(const SDL_Event& keyEvent) {
switch (keyEvent.type) {
case SDL_KEYDOWN:
switch (keyEvent.key.keysym.sym) {
case SDLK_LEFT:
if (horizontalArrows_) {
changeToNext(true);
}
break;
case SDLK_RIGHT:
if (horizontalArrows_) {
changeToNext(false);
}
break;
case SDLK_DOWN:
if (verticalArrows_) {
changeToNext(true);
}
break;
case SDLK_UP:
if (verticalArrows_) {
changeToNext(false);
}
break;
case SDLK_TAB:
if (tab_) {
const Uint8* state = SDL_GetKeyboardState(0);
if (state[SDL_SCANCODE_LSHIFT] || state[SDL_SCANCODE_RSHIFT]) {
changeToNext(false);
} else {
changeToNext(true);
}
}
break;
case SDLK_RETURN:
// Fall through!
case SDLK_KP_ENTER:
for (auto& c : components_) {
if (c->hasFocus() && c->isVisible()) {
c->doAction();
break;
}
}
break;
}
break;
}
}
void TraversalGroup::verticalSort() {
std::sort(components_.rbegin(), components_.rend(), [](const std::shared_ptr<Component>& c1, const std::shared_ptr<Component>& c2) {
Point p1 = c1->getLocation();
Point p2 = c2->getLocation();
if (p1.y_ == p2.y_) {
return p1.x_ < p2.x_;
}
return p1.y_ < p2.y_;
});
}
void TraversalGroup::horizontalSort() {
std::sort(components_.rbegin(), components_.rend(), [](const std::shared_ptr<Component>& c1, const std::shared_ptr<Component>& c2) {
Point p1 = c1->getLocation();
Point p2 = c2->getLocation();
if (p1.x_ == p2.x_) {
return p1.y_ < p2.y_;
}
return p1.x_ < p2.x_;
});
}
void TraversalGroup::changeToNext(bool nextItem) {
bool oneAtLeastVisible = false;
for (auto& c : components_) {
if (c->isVisible()) {
oneAtLeastVisible = true;
break;
}
}
if (oneAtLeastVisible) {
unsigned int index = lastFocusIndex_;
bool findFocusedItem = false;
for (unsigned int i = 0; i < components_.size(); ++i) {
if (nextItem) {
index = (lastFocusIndex_ + i + 1) % components_.size();
} else {
index = (lastFocusIndex_ - i - 1 + components_.size()) % components_.size();
}
if (components_[index]->isVisible()) {
findFocusedItem = true;
break;
}
}
// At least one unit has focus?
if (findFocusedItem) {
// Take focus from all items.
for (auto& c : components_) {
c->setFocus(false);
}
// Give focus to next item.
if (components_[index]->isVisible()) {
components_[index]->setFocus(true);
lastFocusIndex_ = index;
}
} else {
// Find first visible item and give focus.
for (auto& c : components_) {
if (c->isVisible()) {
c->setFocus(true);
break;
}
}
}
}
}
} // Namespace gui.
|
#include "time.h"
#include "classes/c_timer.h"
CTimer::CTimer()
{
startticks = 0;
pausedticks = 0;
started = false;
paused = false;
}
bool CTimer::IsStarted() { return started; }
bool CTimer::IsPaused() { return paused; }
void CTimer::Start()
{
started = true;
paused = false;
#ifdef __emscripten_h__
startticks = emscripten_get_now();
#else
startticks = SDL_GetTicks();
#endif
pausedticks = 0;
}
void CTimer::Stop()
{
started = false;
paused = false;
#ifdef __emscripten_h__
pausedticks = emscripten_get_now()-startticks;
#else
pausedticks = SDL_GetTicks()-startticks;
#endif
}
void CTimer::Pause()
{
if ( (started) && (paused==false) )
{
paused = true;
#ifdef __emscripten_h__
pausedticks = emscripten_get_now()-startticks;
#else
pausedticks = SDL_GetTicks()-startticks;
#endif
}
}
void CTimer::Unpause()
{
if ( paused )
{
paused = false;
pausedticks = 0;
#ifdef __emscripten_h__
startticks = emscripten_get_now()-pausedticks;
#else
startticks = SDL_GetTicks()-pausedticks;
#endif
}
}
#ifdef __emscripten_h__
float CTimer::GetTicks()
{
if( started )
{
if (paused) return pausedticks;
else return emscripten_get_now()-startticks;
}
return 0;
}
#else
int CTimer::GetTicks()
{
if( started )
{
if (paused) return pausedticks;
else return SDL_GetTicks()-startticks;
}
return 0;
}
#endif
float CTimer::GetSeconds()
{
if (started) return float( GetTicks() )/1000.f;
return 0;
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "UIManager.h"
#include <react/core/ShadowNodeFragment.h>
#include <react/debug/SystraceSection.h>
#include <react/graphics/Geometry.h>
#include <glog/logging.h>
namespace facebook {
namespace react {
UIManager::~UIManager() {
LOG(WARNING) << "UIManager::~UIManager() was called (address: " << this
<< ").";
}
SharedShadowNode UIManager::createNode(
Tag tag,
std::string const &name,
SurfaceId surfaceId,
const RawProps &rawProps,
SharedEventTarget eventTarget) const {
SystraceSection s("UIManager::createNode");
auto &componentDescriptor = componentDescriptorRegistry_->at(name);
auto fallbackDescriptor =
componentDescriptorRegistry_->getFallbackComponentDescriptor();
auto family = componentDescriptor.createFamily(
ShadowNodeFamilyFragment{tag, surfaceId, nullptr},
std::move(eventTarget));
auto const props = componentDescriptor.cloneProps(nullptr, rawProps);
auto const state =
componentDescriptor.createInitialState(ShadowNodeFragment{props}, family);
auto shadowNode = componentDescriptor.createShadowNode(
ShadowNodeFragment{
/* .props = */
fallbackDescriptor != nullptr &&
fallbackDescriptor->getComponentHandle() ==
componentDescriptor.getComponentHandle()
? componentDescriptor.cloneProps(
props, RawProps(folly::dynamic::object("name", name)))
: props,
/* .children = */ ShadowNodeFragment::childrenPlaceholder(),
/* .state = */ state,
},
family);
if (delegate_) {
delegate_->uiManagerDidCreateShadowNode(shadowNode);
}
return shadowNode;
}
SharedShadowNode UIManager::cloneNode(
const ShadowNode::Shared &shadowNode,
const SharedShadowNodeSharedList &children,
const RawProps *rawProps) const {
SystraceSection s("UIManager::cloneNode");
auto &componentDescriptor = shadowNode->getComponentDescriptor();
auto clonedShadowNode = componentDescriptor.cloneShadowNode(
*shadowNode,
{
/* .props = */
rawProps ? componentDescriptor.cloneProps(
shadowNode->getProps(), *rawProps)
: ShadowNodeFragment::propsPlaceholder(),
/* .children = */ children,
});
return clonedShadowNode;
}
void UIManager::appendChild(
const ShadowNode::Shared &parentShadowNode,
const ShadowNode::Shared &childShadowNode) const {
SystraceSection s("UIManager::appendChild");
auto &componentDescriptor = parentShadowNode->getComponentDescriptor();
componentDescriptor.appendChild(parentShadowNode, childShadowNode);
}
void UIManager::completeSurface(
SurfaceId surfaceId,
const SharedShadowNodeUnsharedList &rootChildren) const {
SystraceSection s("UIManager::completeSurface");
shadowTreeRegistry_.visit(surfaceId, [&](ShadowTree const &shadowTree) {
shadowTree.commit(
[&](RootShadowNode::Shared const &oldRootShadowNode) {
return std::make_shared<RootShadowNode>(
*oldRootShadowNode,
ShadowNodeFragment{
/* .props = */ ShadowNodeFragment::propsPlaceholder(),
/* .children = */ rootChildren,
});
},
true);
});
}
void UIManager::setJSResponder(
const ShadowNode::Shared &shadowNode,
const bool blockNativeResponder) const {
if (delegate_) {
delegate_->uiManagerDidSetJSResponder(
shadowNode->getSurfaceId(), shadowNode, blockNativeResponder);
}
}
void UIManager::clearJSResponder() const {
if (delegate_) {
delegate_->uiManagerDidClearJSResponder();
}
}
ShadowNode::Shared UIManager::getNewestCloneOfShadowNode(
ShadowNode const &shadowNode) const {
auto findNewestChildInParent =
[&](auto const &parentNode) -> ShadowNode::Shared {
for (auto const &child : parentNode.getChildren()) {
if (ShadowNode::sameFamily(*child, shadowNode)) {
return child;
}
}
return nullptr;
};
auto ancestorShadowNode = ShadowNode::Shared{};
shadowTreeRegistry_.visit(
shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) {
shadowTree.tryCommit(
[&](RootShadowNode::Shared const &oldRootShadowNode) {
ancestorShadowNode = oldRootShadowNode;
return nullptr;
},
true);
});
if (!ancestorShadowNode) {
return nullptr;
}
auto ancestors = shadowNode.getFamily().getAncestors(*ancestorShadowNode);
if (ancestors.empty()) {
return nullptr;
}
return findNewestChildInParent(ancestors.rbegin()->first.get());
}
ShadowNode::Shared UIManager::findNodeAtPoint(
ShadowNode::Shared const &node,
Point point) const {
return LayoutableShadowNode::findNodeAtPoint(
getNewestCloneOfShadowNode(*node), point);
}
void UIManager::setNativeProps(
ShadowNode const &shadowNode,
RawProps const &rawProps) const {
SystraceSection s("UIManager::setNativeProps");
auto &componentDescriptor = shadowNode.getComponentDescriptor();
auto props = componentDescriptor.cloneProps(shadowNode.getProps(), rawProps);
shadowTreeRegistry_.visit(
shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) {
shadowTree.tryCommit(
[&](RootShadowNode::Shared const &oldRootShadowNode) {
return std::static_pointer_cast<RootShadowNode>(
oldRootShadowNode->cloneTree(
shadowNode.getFamily(),
[&](ShadowNode const &oldShadowNode) {
return oldShadowNode.clone({
/* .props = */ props,
});
}));
},
true);
});
}
LayoutMetrics UIManager::getRelativeLayoutMetrics(
ShadowNode const &shadowNode,
ShadowNode const *ancestorShadowNode,
LayoutableShadowNode::LayoutInspectingPolicy policy) const {
SystraceSection s("UIManager::getRelativeLayoutMetrics");
// We might store here an owning pointer to `ancestorShadowNode` to ensure
// that the node is not deallocated during method execution lifetime.
auto owningAncestorShadowNode = ShadowNode::Shared{};
if (!ancestorShadowNode) {
shadowTreeRegistry_.visit(
shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) {
shadowTree.tryCommit(
[&](RootShadowNode::Shared const &oldRootShadowNode) {
ancestorShadowNode = oldRootShadowNode.get();
return nullptr;
},
true);
});
} else {
// It is possible for JavaScript (or other callers) to have a reference
// to a previous version of ShadowNodes, but we enforce that
// metrics are only calculated on most recently committed versions.
owningAncestorShadowNode = getNewestCloneOfShadowNode(*ancestorShadowNode);
ancestorShadowNode = owningAncestorShadowNode.get();
}
auto layoutableAncestorShadowNode =
traitCast<LayoutableShadowNode const *>(ancestorShadowNode);
if (!layoutableAncestorShadowNode) {
return EmptyLayoutMetrics;
}
return LayoutableShadowNode::computeRelativeLayoutMetrics(
shadowNode.getFamily(), *layoutableAncestorShadowNode, policy);
}
void UIManager::updateState(StateUpdate const &stateUpdate) const {
auto &callback = stateUpdate.callback;
auto &family = stateUpdate.family;
auto &componentDescriptor = family->getComponentDescriptor();
shadowTreeRegistry_.visit(
family->getSurfaceId(), [&](ShadowTree const &shadowTree) {
shadowTree.tryCommit([&](RootShadowNode::Shared const
&oldRootShadowNode) {
return std::static_pointer_cast<
RootShadowNode>(oldRootShadowNode->cloneTree(
*family, [&](ShadowNode const &oldShadowNode) {
auto newData =
callback(oldShadowNode.getState()->getDataPointer());
auto newState =
componentDescriptor.createState(*family, newData);
return oldShadowNode.clone({
/* .props = */ ShadowNodeFragment::propsPlaceholder(),
/* .children = */ ShadowNodeFragment::childrenPlaceholder(),
/* .state = */ newState,
});
}));
});
});
}
void UIManager::dispatchCommand(
const ShadowNode::Shared &shadowNode,
std::string const &commandName,
folly::dynamic const args) const {
if (delegate_) {
delegate_->uiManagerDidDispatchCommand(shadowNode, commandName, args);
}
}
void UIManager::configureNextLayoutAnimation(
RawValue const &config,
SharedEventTarget successCallback,
SharedEventTarget errorCallback) const {
if (animationDelegate_) {
animationDelegate_->uiManagerDidConfigureNextLayoutAnimation(
config, successCallback, errorCallback);
}
}
void UIManager::setComponentDescriptorRegistry(
const SharedComponentDescriptorRegistry &componentDescriptorRegistry) {
componentDescriptorRegistry_ = componentDescriptorRegistry;
}
void UIManager::setDelegate(UIManagerDelegate *delegate) {
delegate_ = delegate;
}
UIManagerDelegate *UIManager::getDelegate() {
return delegate_;
}
void UIManager::visitBinding(
std::function<void(UIManagerBinding const &uiManagerBinding)> callback)
const {
if (!uiManagerBinding_) {
return;
}
callback(*uiManagerBinding_);
}
ShadowTreeRegistry const &UIManager::getShadowTreeRegistry() const {
return shadowTreeRegistry_;
}
#pragma mark - ShadowTreeDelegate
void UIManager::shadowTreeDidFinishTransaction(
ShadowTree const &shadowTree,
MountingCoordinator::Shared const &mountingCoordinator) const {
SystraceSection s("UIManager::shadowTreeDidFinishTransaction");
if (delegate_) {
delegate_->uiManagerDidFinishTransaction(mountingCoordinator);
}
}
#pragma mark - UIManagerAnimationDelegate
void UIManager::setAnimationDelegate(UIManagerAnimationDelegate *delegate) {
animationDelegate_ = delegate;
}
void UIManager::animationTick() {
if (animationDelegate_ != nullptr &&
animationDelegate_->shouldAnimateFrame()) {
shadowTreeRegistry_.enumerate(
[&](ShadowTree const &shadowTree, bool &stop) {
shadowTree.notifyDelegatesOfUpdates();
});
}
}
} // namespace react
} // namespace facebook
|
#include <iostream>
#include <vector>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n - 1); }
template <class T> using V = vector<T>;
template <class T> using VV = V<V<T>>;
// s[0..r[i]] == s[i..i+r[i]]
template <class S> V<int> z_algo(const S& s) {
int n = int(s.size());
V<int> r(n + 1);
r[0] = 0;
for (int i = 1, j = 0; i <= n; i++) {
int& k = r[i];
k = (j + r[j] <= i) ? 0 : min(j + r[j] - i, r[i - j]);
while (i + k < n && s[k] == s[i + k]) k++;
if (j + r[j] < i + r[i]) j = i;
}
r[0] = n;
return r;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
string s;
cin >> s;
int n = int(s.size());
auto z = z_algo(s);
for (int i = 0; i < n; i++) {
cout << z[i];
if (i + 1 != n) cout << " ";
}
cout << endl;
return 0;
}
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/emr/model/ModifyFlowForWebResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Emr;
using namespace AlibabaCloud::Emr::Model;
ModifyFlowForWebResult::ModifyFlowForWebResult() :
ServiceResult()
{}
ModifyFlowForWebResult::ModifyFlowForWebResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ModifyFlowForWebResult::~ModifyFlowForWebResult()
{}
void ModifyFlowForWebResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Data"].isNull())
data_ = value["Data"].asString() == "true";
}
bool ModifyFlowForWebResult::getData()const
{
return data_;
}
|
/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* DataMan.cpp classes for DataMan streaming format
*
* Created on: May 11, 2018
* Author: Jason Wang
*/
#include "DataMan.tcc"
#include <cstring> //std::memcpy
#include <iostream>
namespace adios2
{
namespace format
{
void DataManSerializer::New(size_t size)
{
m_Buffer = std::make_shared<std::vector<char>>();
m_Buffer->reserve(size);
m_Position = 0;
}
const std::shared_ptr<std::vector<char>> DataManSerializer::Get()
{
return m_Buffer;
}
void DataManDeserializer::Put(std::shared_ptr<std::vector<char>> data)
{
int key = rand();
m_MutexBuffer.lock();
while (m_BufferMap.count(key) > 0)
{
key = rand();
}
m_BufferMap[key] = data;
m_MutexBuffer.unlock();
size_t position = 0;
while (position < data->capacity())
{
uint32_t metasize;
std::memcpy(&metasize, data->data() + position, sizeof(metasize));
position += sizeof(metasize);
if (position + metasize > data->size())
{
break;
}
DataManVar var;
try
{
nlohmann::json metaj =
nlohmann::json::parse(data->data() + position);
position += metasize;
var.name = metaj["N"].get<std::string>();
var.type = metaj["Y"].get<std::string>();
var.shape = metaj["S"].get<Dims>();
var.count = metaj["C"].get<Dims>();
var.start = metaj["O"].get<Dims>();
var.step = metaj["T"].get<size_t>();
var.size = metaj["I"].get<size_t>();
var.rank = metaj["R"].get<int>();
var.doid = metaj["D"].get<std::string>();
var.position = position;
var.index = key;
auto it = metaj.find("Z");
if (it != metaj.end())
{
var.compression = it->get<std::string>();
}
it = metaj.find("ZR");
if (it != metaj.end())
{
var.compressionRate = it->get<float>();
}
if (position + var.size > data->capacity())
{
break;
}
m_MutexMetaData.lock();
if (m_MetaDataMap[var.step] == nullptr)
{
m_MetaDataMap[var.step] =
std::make_shared<std::vector<DataManVar>>();
}
m_MetaDataMap[var.step]->push_back(std::move(var));
m_MutexMetaData.unlock();
position += var.size;
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
m_MutexMaxMin.lock();
if (m_MaxStep < var.step)
{
m_MaxStep = var.step;
}
if (m_MinStep > var.step)
{
m_MinStep = var.step;
}
m_MutexMaxMin.unlock();
}
}
void DataManDeserializer::Erase(size_t step)
{
m_MutexMetaData.lock();
const auto &i = m_MetaDataMap.find(step);
if (i != m_MetaDataMap.end())
{
for (const auto &k : *i->second)
{
if (BufferContainsSteps(k.index, step + 1, MaxStep()) == false)
{
m_MutexBuffer.lock();
m_BufferMap.erase(k.index);
m_MutexBuffer.unlock();
}
}
}
m_MetaDataMap.erase(step);
m_MutexMetaData.unlock();
m_MutexMaxMin.lock();
m_MinStep = step + 1;
m_MutexMaxMin.unlock();
}
size_t DataManDeserializer::MaxStep()
{
std::lock_guard<std::mutex> l(m_MutexMaxMin);
return m_MaxStep;
}
size_t DataManDeserializer::MinStep()
{
std::lock_guard<std::mutex> l(m_MutexMaxMin);
return m_MinStep;
}
const std::shared_ptr<std::vector<DataManDeserializer::DataManVar>>
DataManDeserializer::GetMetaData(size_t step)
{
std::lock_guard<std::mutex> l(m_MutexMetaData);
const auto &i = m_MetaDataMap.find(step);
if (i != m_MetaDataMap.end())
{
return m_MetaDataMap[step];
}
else
{
return nullptr;
}
}
bool DataManDeserializer::BufferContainsSteps(int index, size_t begin,
size_t end)
{
// This is a private function and is always called after m_MutexMetaData is
// locked, so there is no need to lock again here.
for (size_t i = begin; i <= end; ++i)
{
const auto &j = m_MetaDataMap.find(i);
if (j != m_MetaDataMap.end())
{
for (const auto &k : *j->second)
{
if (k.index == index)
{
return true;
}
}
}
}
return false;
}
Dims DataManDeserializer::GetRelativePosition(const Dims &inner,
const Dims &outer)
{
Dims ret;
size_t size = inner.size();
ret.resize(size);
for (int i = 0; i < size; ++i)
{
ret[i] = inner[i] - outer[i];
}
return ret;
}
Dims DataManDeserializer::GetAbsolutePosition(const Dims &inner,
const Dims &outer)
{
Dims ret;
size_t size = inner.size();
ret.resize(size);
for (int i = 0; i < size; ++i)
{
ret[i] = inner[i] + outer[i];
}
return ret;
}
size_t DataManDeserializer::MultiToOne(const Dims &global, const Dims &position)
{
size_t index = 0;
for (int i = 1; i < global.size(); ++i)
{
index += std::accumulate(global.begin() + i, global.end(),
position[i - 1], std::multiplies<size_t>());
}
index += position.back();
return index;
}
Dims DataManDeserializer::OneToMulti(const Dims &global, size_t position)
{
std::vector<size_t> index(global.size());
for (int i = 1; i < global.size(); ++i)
{
size_t s = std::accumulate(global.begin() + i, global.end(), 1,
std::multiplies<size_t>());
index[i - 1] = position / s;
position -= index[i - 1] * s;
}
index.back() = position;
return index;
}
void DataManDeserializer::CopyLocalToGlobal(char *dst, const Box<Dims> &dstBox,
const char *src,
const Box<Dims> &srcBox,
const size_t size,
const Box<Dims> &overlapBox)
{
size_t dimensions = overlapBox.first.size();
size_t overlapSize = 1;
for (int i = 0; i < dimensions; ++i)
{
overlapSize =
overlapSize * (overlapBox.second[i] - overlapBox.first[i]);
}
Dims srcCount(dimensions);
for (int i = 0; i < dimensions; ++i)
{
srcCount[i] = srcBox.second[i] - srcBox.first[i];
}
Dims dstCount(dimensions);
for (int i = 0; i < dimensions; ++i)
{
dstCount[i] = dstBox.second[i] - dstBox.first[i];
}
if (IsContinuous(overlapBox, srcBox) && IsContinuous(overlapBox, dstBox))
{
Dims overlapInSrcRelativeLeftBoundary =
GetRelativePosition(overlapBox.first, srcBox.first);
Dims overlapInDstRelativeLeftBoundary =
GetRelativePosition(overlapBox.first, dstBox.first);
size_t srcStartPtrOffset =
MultiToOne(srcCount, overlapInSrcRelativeLeftBoundary);
size_t dstStartPtrOffset =
MultiToOne(dstCount, overlapInDstRelativeLeftBoundary);
std::memcpy(dst + dstStartPtrOffset * size,
src + srcStartPtrOffset * size, overlapSize * size);
}
else
{
size_t overlapChunkSize =
(overlapBox.second.back() - overlapBox.first.back());
Dims overlapCount(dimensions);
for (int i = 0; i < dimensions; ++i)
{
overlapCount[i] = overlapBox.second[i] - overlapBox.first[i];
}
for (size_t i = 0; i < overlapSize; i += overlapChunkSize)
{
Dims currentPositionLocal = OneToMulti(overlapCount, i);
Dims currentPositionGlobal =
GetAbsolutePosition(currentPositionLocal, overlapBox.first);
Dims overlapInSrcRelativeCurrentPosition =
GetRelativePosition(currentPositionGlobal, srcBox.first);
Dims overlapInDstRelativeCurrentPosition =
GetRelativePosition(currentPositionGlobal, dstBox.first);
size_t srcStartPtrOffset =
MultiToOne(srcCount, overlapInSrcRelativeCurrentPosition);
size_t dstStartPtrOffset =
MultiToOne(dstCount, overlapInDstRelativeCurrentPosition);
std::memcpy(dst + dstStartPtrOffset * size,
src + srcStartPtrOffset * size,
overlapChunkSize * size);
}
}
}
bool DataManDeserializer::GetOverlap(const Box<Dims> &b1, const Box<Dims> &b2,
Box<Dims> &overlapBox)
{
overlapBox.first.resize(b1.first.size());
overlapBox.second.resize(b1.first.size());
for (size_t i = 0; i < b1.first.size(); ++i)
{
if (b1.first[i] > b2.first[i])
{
overlapBox.first[i] = b1.first[i];
}
else
{
overlapBox.first[i] = b2.first[i];
}
if (b1.second[i] < b2.second[i])
{
overlapBox.second[i] = b1.second[i];
}
else
{
overlapBox.second[i] = b2.second[i];
}
}
for (size_t i = 0; i < overlapBox.first.size(); ++i)
{
if (overlapBox.first[i] > overlapBox.second[i])
{
return false;
}
}
return true;
}
bool DataManDeserializer::IsContinuous(const Box<Dims> &inner,
const Box<Dims> &outer)
{
for (size_t i = 1; i < inner.first.size(); ++i)
{
if (inner.first[i] != outer.first[i])
{
return false;
}
if (inner.second[i] != outer.second[i])
{
return false;
}
}
return true;
}
bool DataManDeserializer::GetVarList(size_t step,
std::vector<DataManVar> &varList)
{
m_MutexMetaData.lock();
auto metaDataStep = m_MetaDataMap.find(step);
if (metaDataStep == m_MetaDataMap.end())
{
return false;
}
for (auto &i : *metaDataStep->second)
{
bool hasVar = false;
for (DataManVar &j : varList)
{
if (j.name == i.name)
{
hasVar = true;
}
}
if (hasVar == false)
{
DataManVar var;
var.name = i.name;
var.shape = i.shape;
var.type = i.type;
var.doid = i.doid;
varList.push_back(std::move(var));
}
}
m_MutexMetaData.unlock();
return true;
}
void DataManDeserializer::PrintBox(const Box<Dims> in, std::string name)
{
std::cout << name << " Left boundary: [";
for (auto &i : in.first)
{
std::cout << i << ", ";
}
std::cout << "]" << std::endl;
std::cout << name << " Right boundary: [";
for (auto &i : in.second)
{
std::cout << i << ", ";
}
std::cout << "]" << std::endl;
}
} // namespace format
} // namespace adios2
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The xx developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/infinitemoneycoin-config.h"
#endif
#include "util.h"
#include "uritests.h"
#ifdef ENABLE_WALLET
#include "paymentservertests.h"
#endif
#include <QCoreApplication>
#include <QObject>
#include <QTest>
#include <openssl/ssl.h>
#if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
#endif
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
SetupEnvironment();
bool fInvalid = false;
// Don't remove this, it's needed to access
// QCoreApplication:: in the tests
QCoreApplication app(argc, argv);
app.setApplicationName("infinitemoneycoin-Qt-test");
SSL_library_init();
URITests test1;
if (QTest::qExec(&test1) != 0)
fInvalid = true;
#ifdef ENABLE_WALLET
PaymentServerTests test2;
if (QTest::qExec(&test2) != 0)
fInvalid = true;
#endif
return fInvalid;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/infinex-config.h"
#endif
#include "tinyformat.h"
#include "utiltime.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
using namespace std;
static int64_t nMockTime = 0; //! For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
time_t now = time(NULL);
assert(now > 0);
return now;
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
int64_t GetTimeMillis()
{
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
assert(now > 0);
return now;
}
int64_t GetTimeMicros()
{
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
assert(now > 0);
return now;
}
int64_t GetSystemTimeInSeconds()
{
return GetTimeMicros()/1000000;
}
/** Return a time useful for the debug log */
int64_t GetLogTimeMicros()
{
if (nMockTime) return nMockTime*1000000;
return GetTimeMicros();
}
void MilliSleep(int64_t n)
{
/**
* Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
* until fixed in 1.52. Use the deprecated sleep method for the broken case.
* See: https://svn.boost.org/trac/boost/ticket/7238
*/
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
// std::locale takes ownership of the pointer
std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
std::stringstream ss;
ss.imbue(loc);
ss << boost::posix_time::from_time_t(nTime);
return ss.str();
}
std::string DurationToDHMS(int64_t nDurationTime)
{
int seconds = nDurationTime % 60;
nDurationTime /= 60;
int minutes = nDurationTime % 60;
nDurationTime /= 60;
int hours = nDurationTime % 24;
int days = nDurationTime / 24;
if(days)
return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
if(hours)
return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
return strprintf("%02dm:%02ds", minutes, seconds);
}
|
/*
*******************************************************************************
* Copyright (C) 2012-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* uitercollationiterator.cpp
*
* created on: 2012sep23 (from utf16collationiterator.cpp)
* created by: Markus W. Scherer
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/uiter.h"
#include "charstr.h"
#include "cmemory.h"
#include "collation.h"
#include "collationdata.h"
#include "collationfcd.h"
#include "collationiterator.h"
#include "normalizer2impl.h"
#include "uassert.h"
#include "uitercollationiterator.h"
U_NAMESPACE_BEGIN
UIterCollationIterator::~UIterCollationIterator() {}
void
UIterCollationIterator::resetToOffset(int32_t newOffset) {
reset();
iter.move(&iter, newOffset, UITER_START);
}
int32_t
UIterCollationIterator::getOffset() const {
return iter.getIndex(&iter, UITER_CURRENT);
}
uint32_t
UIterCollationIterator::handleNextCE32(UChar32 &c, UErrorCode & /*errorCode*/) {
c = iter.next(&iter);
if(c < 0) {
return Collation::FALLBACK_CE32;
}
return UTRIE2_GET32_FROM_U16_SINGLE_LEAD(trie, c);
}
UChar
UIterCollationIterator::handleGetTrailSurrogate() {
UChar32 trail = iter.next(&iter);
if(!U16_IS_TRAIL(trail) && trail >= 0) { iter.previous(&iter); }
return (UChar)trail;
}
UChar32
UIterCollationIterator::nextCodePoint(UErrorCode & /*errorCode*/) {
return uiter_next32(&iter);
}
UChar32
UIterCollationIterator::previousCodePoint(UErrorCode & /*errorCode*/) {
return uiter_previous32(&iter);
}
void
UIterCollationIterator::forwardNumCodePoints(int32_t num, UErrorCode & /*errorCode*/) {
while(num > 0 && (uiter_next32(&iter)) >= 0) {
--num;
}
}
void
UIterCollationIterator::backwardNumCodePoints(int32_t num, UErrorCode & /*errorCode*/) {
while(num > 0 && (uiter_previous32(&iter)) >= 0) {
--num;
}
}
// FCDUIterCollationIterator ----------------------------------------------- ***
FCDUIterCollationIterator::~FCDUIterCollationIterator() {}
void
FCDUIterCollationIterator::resetToOffset(int32_t newOffset) {
UIterCollationIterator::resetToOffset(newOffset);
start = newOffset;
state = ITER_CHECK_FWD;
}
int32_t
FCDUIterCollationIterator::getOffset() const {
if(state <= ITER_CHECK_BWD) {
return iter.getIndex(&iter, UITER_CURRENT);
} else if(state == ITER_IN_FCD_SEGMENT) {
return pos;
} else if(pos == 0) {
return start;
} else {
return limit;
}
}
uint32_t
FCDUIterCollationIterator::handleNextCE32(UChar32 &c, UErrorCode &errorCode) {
for(;;) {
if(state == ITER_CHECK_FWD) {
c = iter.next(&iter);
if(c < 0) {
return Collation::FALLBACK_CE32;
}
if(CollationFCD::hasTccc(c)) {
if(CollationFCD::maybeTibetanCompositeVowel(c) ||
CollationFCD::hasLccc(iter.current(&iter))) {
iter.previous(&iter);
if(!nextSegment(errorCode)) {
c = U_SENTINEL;
return Collation::FALLBACK_CE32;
}
continue;
}
}
break;
} else if(state == ITER_IN_FCD_SEGMENT && pos != limit) {
c = iter.next(&iter);
++pos;
U_ASSERT(c >= 0);
break;
} else if(state >= IN_NORM_ITER_AT_LIMIT && pos != normalized.length()) {
c = normalized[pos++];
break;
} else {
switchToForward();
}
}
return UTRIE2_GET32_FROM_U16_SINGLE_LEAD(trie, c);
}
UChar
FCDUIterCollationIterator::handleGetTrailSurrogate() {
if(state <= ITER_IN_FCD_SEGMENT) {
UChar32 trail = iter.next(&iter);
if(U16_IS_TRAIL(trail)) {
if(state == ITER_IN_FCD_SEGMENT) { ++pos; }
} else if(trail >= 0) {
iter.previous(&iter);
}
return (UChar)trail;
} else {
U_ASSERT(pos < normalized.length());
UChar trail;
if(U16_IS_TRAIL(trail = normalized[pos])) { ++pos; }
return trail;
}
}
UChar32
FCDUIterCollationIterator::nextCodePoint(UErrorCode &errorCode) {
UChar32 c;
for(;;) {
if(state == ITER_CHECK_FWD) {
c = iter.next(&iter);
if(c < 0) {
return c;
}
if(CollationFCD::hasTccc(c)) {
if(CollationFCD::maybeTibetanCompositeVowel(c) ||
CollationFCD::hasLccc(iter.current(&iter))) {
iter.previous(&iter);
if(!nextSegment(errorCode)) {
return U_SENTINEL;
}
continue;
}
}
if(U16_IS_LEAD(c)) {
UChar32 trail = iter.next(&iter);
if(U16_IS_TRAIL(trail)) {
return U16_GET_SUPPLEMENTARY(c, trail);
} else if(trail >= 0) {
iter.previous(&iter);
}
}
return c;
} else if(state == ITER_IN_FCD_SEGMENT && pos != limit) {
c = uiter_next32(&iter);
pos += U16_LENGTH(c);
U_ASSERT(c >= 0);
return c;
} else if(state >= IN_NORM_ITER_AT_LIMIT && pos != normalized.length()) {
c = normalized.char32At(pos);
pos += U16_LENGTH(c);
return c;
} else {
switchToForward();
}
}
}
UChar32
FCDUIterCollationIterator::previousCodePoint(UErrorCode &errorCode) {
UChar32 c;
for(;;) {
if(state == ITER_CHECK_BWD) {
c = iter.previous(&iter);
if(c < 0) {
start = pos = 0;
state = ITER_IN_FCD_SEGMENT;
return U_SENTINEL;
}
if(CollationFCD::hasLccc(c)) {
UChar32 prev = U_SENTINEL;
if(CollationFCD::maybeTibetanCompositeVowel(c) ||
CollationFCD::hasTccc(prev = iter.previous(&iter))) {
iter.next(&iter);
if(prev >= 0) {
iter.next(&iter);
}
if(!previousSegment(errorCode)) {
return U_SENTINEL;
}
continue;
}
// hasLccc(trail)=true for all trail surrogates
if(U16_IS_TRAIL(c)) {
if(prev < 0) {
prev = iter.previous(&iter);
}
if(U16_IS_LEAD(prev)) {
return U16_GET_SUPPLEMENTARY(prev, c);
}
}
if(prev >= 0) {
iter.next(&iter);
}
}
return c;
} else if(state == ITER_IN_FCD_SEGMENT && pos != start) {
c = uiter_previous32(&iter);
pos -= U16_LENGTH(c);
U_ASSERT(c >= 0);
return c;
} else if(state >= IN_NORM_ITER_AT_LIMIT && pos != 0) {
c = normalized.char32At(pos - 1);
pos -= U16_LENGTH(c);
return c;
} else {
switchToBackward();
}
}
}
void
FCDUIterCollationIterator::forwardNumCodePoints(int32_t num, UErrorCode &errorCode) {
// Specify the class to avoid a virtual-function indirection.
// In Java, we would declare this class final.
while(num > 0 && FCDUIterCollationIterator::nextCodePoint(errorCode) >= 0) {
--num;
}
}
void
FCDUIterCollationIterator::backwardNumCodePoints(int32_t num, UErrorCode &errorCode) {
// Specify the class to avoid a virtual-function indirection.
// In Java, we would declare this class final.
while(num > 0 && FCDUIterCollationIterator::previousCodePoint(errorCode) >= 0) {
--num;
}
}
void
FCDUIterCollationIterator::switchToForward() {
U_ASSERT(state == ITER_CHECK_BWD ||
(state == ITER_IN_FCD_SEGMENT && pos == limit) ||
(state >= IN_NORM_ITER_AT_LIMIT && pos == normalized.length()));
if(state == ITER_CHECK_BWD) {
// Turn around from backward checking.
start = pos = iter.getIndex(&iter, UITER_CURRENT);
if(pos == limit) {
state = ITER_CHECK_FWD; // Check forward.
} else { // pos < limit
state = ITER_IN_FCD_SEGMENT; // Stay in FCD segment.
}
} else {
// Reached the end of the FCD segment.
if(state == ITER_IN_FCD_SEGMENT) {
// The input text segment is FCD, extend it forward.
} else {
// The input text segment needed to be normalized.
// Switch to checking forward from it.
if(state == IN_NORM_ITER_AT_START) {
iter.move(&iter, limit - start, UITER_CURRENT);
}
start = limit;
}
state = ITER_CHECK_FWD;
}
}
UBool
FCDUIterCollationIterator::nextSegment(UErrorCode &errorCode) {
if(U_FAILURE(errorCode)) { return FALSE; }
U_ASSERT(state == ITER_CHECK_FWD);
// The input text [start..(iter index)[ passes the FCD check.
pos = iter.getIndex(&iter, UITER_CURRENT);
// Collect the characters being checked, in case they need to be normalized.
UnicodeString s;
uint8_t prevCC = 0;
for(;;) {
// Fetch the next character and its fcd16 value.
UChar32 c = uiter_next32(&iter);
if(c < 0) { break; }
uint16_t fcd16 = nfcImpl.getFCD16(c);
uint8_t leadCC = (uint8_t)(fcd16 >> 8);
if(leadCC == 0 && !s.isEmpty()) {
// FCD boundary before this character.
uiter_previous32(&iter);
break;
}
s.append(c);
if(leadCC != 0 && (prevCC > leadCC || CollationFCD::isFCD16OfTibetanCompositeVowel(fcd16))) {
// Fails FCD check. Find the next FCD boundary and normalize.
for(;;) {
c = uiter_next32(&iter);
if(c < 0) { break; }
if(nfcImpl.getFCD16(c) <= 0xff) {
uiter_previous32(&iter);
break;
}
s.append(c);
}
if(!normalize(s, errorCode)) { return FALSE; }
start = pos;
limit = pos + s.length();
state = IN_NORM_ITER_AT_LIMIT;
pos = 0;
return TRUE;
}
prevCC = (uint8_t)fcd16;
if(prevCC == 0) {
// FCD boundary after the last character.
break;
}
}
limit = pos + s.length();
U_ASSERT(pos != limit);
iter.move(&iter, -s.length(), UITER_CURRENT);
state = ITER_IN_FCD_SEGMENT;
return TRUE;
}
void
FCDUIterCollationIterator::switchToBackward() {
U_ASSERT(state == ITER_CHECK_FWD ||
(state == ITER_IN_FCD_SEGMENT && pos == start) ||
(state >= IN_NORM_ITER_AT_LIMIT && pos == 0));
if(state == ITER_CHECK_FWD) {
// Turn around from forward checking.
limit = pos = iter.getIndex(&iter, UITER_CURRENT);
if(pos == start) {
state = ITER_CHECK_BWD; // Check backward.
} else { // pos > start
state = ITER_IN_FCD_SEGMENT; // Stay in FCD segment.
}
} else {
// Reached the start of the FCD segment.
if(state == ITER_IN_FCD_SEGMENT) {
// The input text segment is FCD, extend it backward.
} else {
// The input text segment needed to be normalized.
// Switch to checking backward from it.
if(state == IN_NORM_ITER_AT_LIMIT) {
iter.move(&iter, start - limit, UITER_CURRENT);
}
limit = start;
}
state = ITER_CHECK_BWD;
}
}
UBool
FCDUIterCollationIterator::previousSegment(UErrorCode &errorCode) {
if(U_FAILURE(errorCode)) { return FALSE; }
U_ASSERT(state == ITER_CHECK_BWD);
// The input text [(iter index)..limit[ passes the FCD check.
pos = iter.getIndex(&iter, UITER_CURRENT);
// Collect the characters being checked, in case they need to be normalized.
UnicodeString s;
uint8_t nextCC = 0;
for(;;) {
// Fetch the previous character and its fcd16 value.
UChar32 c = uiter_previous32(&iter);
if(c < 0) { break; }
uint16_t fcd16 = nfcImpl.getFCD16(c);
uint8_t trailCC = (uint8_t)fcd16;
if(trailCC == 0 && !s.isEmpty()) {
// FCD boundary after this character.
uiter_next32(&iter);
break;
}
s.append(c);
if(trailCC != 0 && ((nextCC != 0 && trailCC > nextCC) ||
CollationFCD::isFCD16OfTibetanCompositeVowel(fcd16))) {
// Fails FCD check. Find the previous FCD boundary and normalize.
while(fcd16 > 0xff) {
c = uiter_previous32(&iter);
if(c < 0) { break; }
fcd16 = nfcImpl.getFCD16(c);
if(fcd16 == 0) {
(void)uiter_next32(&iter);
break;
}
s.append(c);
}
s.reverse();
if(!normalize(s, errorCode)) { return FALSE; }
limit = pos;
start = pos - s.length();
state = IN_NORM_ITER_AT_START;
pos = normalized.length();
return TRUE;
}
nextCC = (uint8_t)(fcd16 >> 8);
if(nextCC == 0) {
// FCD boundary before the following character.
break;
}
}
start = pos - s.length();
U_ASSERT(pos != start);
iter.move(&iter, s.length(), UITER_CURRENT);
state = ITER_IN_FCD_SEGMENT;
return TRUE;
}
UBool
FCDUIterCollationIterator::normalize(const UnicodeString &s, UErrorCode &errorCode) {
// NFD without argument checking.
U_ASSERT(U_SUCCESS(errorCode));
nfcImpl.decompose(s, normalized, errorCode);
return U_SUCCESS(errorCode);
}
U_NAMESPACE_END
#endif // !UCONFIG_NO_COLLATION
|
#ifndef BOOST_METAPARSE_V1_CPP98_IMPL_NTH_OF_C_HPP
#define BOOST_METAPARSE_V1_CPP98_IMPL_NTH_OF_C_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/metaparse/v1/cpp98/impl/nth_of_c_impl.hpp>
#include <boost/metaparse/v1/error/index_out_of_range.hpp>
#include <boost/metaparse/v1/fail.hpp>
#include <boost/metaparse/limit_sequence_size.hpp>
#include <boost/mpl/list.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/cat.hpp>
namespace boost
{
namespace metaparse
{
namespace v1
{
namespace impl
{
#ifdef BOOST_METAPARSE_NTH_OF_CASE
# error BOOST_METAPARSE_NTH_OF_CASE already defined
#endif
#define BOOST_METAPARSE_NTH_OF_CASE(z, n, unused) \
template < \
int K BOOST_PP_COMMA_IF(n) \
BOOST_PP_ENUM_PARAMS(n, class P) \
> \
struct BOOST_PP_CAT(nth_of_c, n) : \
boost::mpl::if_< \
boost::mpl::bool_<(0 <= K && K < n)>, \
nth_of_c_impl< \
K, \
boost::mpl::list<BOOST_PP_ENUM_PARAMS(n, P)> \
>, \
fail<error::index_out_of_range<0, n - 1, K> > \
>::type \
{};
BOOST_PP_REPEAT(
BOOST_METAPARSE_LIMIT_SEQUENCE_SIZE,
BOOST_METAPARSE_NTH_OF_CASE,
~
)
#undef BOOST_METAPARSE_NTH_OF_CASE
}
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.